<commit_before>'use strict';

// branch(0) loadstore(1) alu(2) drop-fear(3) lit_slot(4) PS-change(5) RS-change(6)
var words = [
    {name:'LIT4',        use:[0, 0, 0, 1, 1,   1, 0, -1, 0]}, // (          -- x )
    {name:'LIT8',        use:[0, 0, 0, 1, 1,   1, 0, -1, 0]}, // (          -- x )
    {name:'LIT16',       use:[0, 0, 0, 1, 1,   1, 0, -1, 0]}, // (          -- x )
    {name:'LIT32',       use:[0, 0, 0, 1, 1,   1, 0, -1, 0]}, // (          -- x )
    {name:'BRANCH',      use:[1, 0, 0, 1, 0,  -1, 0,  1, 0]}, // (     addr --   )

    {name:'CALL',        use:[1, 0, 0, 1, 0,  -1, 0,  1,-1]}, // (     addr --   | -- z )
    {name:'@',           use:[0, 1, 0, 1, 0,   0, 0,  0, 0]}, // (     addr -- val )
    {name:'PICK',        use:[0, 0, 0, 1, 0,   1, 0,  0, 0]}, // (          -- x )
    {name:'DUP',         use:[0, 0, 0, 1, 0,   1, 0,  0, 0]}, // (        x -- x x )
    {name:'R>',          use:[0, 0, 0, 0, 0,   1,-1, -1, 1]}, // (          -- x | x --   )
    {name:'OVER_SWAP_!', use:[0, 1, 0, 0, 0,  -1, 0,  2, 0]}, // ( val addr -- val )
    {name:'ALU',         use:[0, 0, 1, 1, 1,  -1, 0,  1, 0]}, // (      x y -- z )
    {name:'DROP',        use:[0, 0, 0, 0, 0,  -1, 0,  1, 0]}, // (        x --   )
    {name:'>R',          use:[0, 0, 0, 0, 0,  -1, 1,  1,-1]}, // (        x --   |   -- x )
];

var options = {
    loadstore: 1,
    alu: 1,
    dropfear: 1,
    lit_slots: 1,
    r2r: 1,
    litalu1: 1,
    ps_push: 1,
    ps_pop: 1,
    rs_push: 1,
    rs_pop: 1,
    branch: 1
};

exports.options = options;

function good_loadstore (arr) {
    if (!options.loadstore) { return 1; }
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[1]; // loadstore
    }
    if (count > 1) { return 0; }
    return 1;
}

function good_alu (arr) {
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[2]; // ALUs
    }
    if (count > options.alu) { return 0; }
    return 1;
}

function good_dropfear (arr) {
    if (options.dropfear) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'DROP') && (words[arr[i-1]].use[3])) { return 0; } // drop fear
    }
    return 1;
}

function good_lit_slot (arr) {
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[4]; // LIT slots
    }
    if (count > options.lit_slots) { return 0; }
    return 1;
}

function good_r2r (arr) {
    if (options.r2r) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'R>') && (words[arr[i-1]].name === '>R')) { return 0; }
        if ((words[arr[i]].name === '>R') && (words[arr[i-1]].name === 'R>')) { return 0; }
    }
    return 1;
}

function good_litalu1 (arr) {
    if (options.litalu1) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'ALU1') && (words[arr[i-1]].name === 'LIT')) { return 0; }
    }
    return 1;
}

function good_balance (arr) {
    var i, count;

    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[5]; // PS balance
    }
    if (count >  options.ps_push) { return 0; }
    if (count < -options.ps_pop) { return 0; }
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[6]; // RS balance
    }
    if (count >  options.rs_push) { return 0; }
    if (count < -options.rs_pop) { return 0; }
    return 1;
}

function good_to_go (arr) {
    return good_alu(arr)
        && good_loadstore(arr)
        && good_dropfear(arr)
        && good_r2r(arr)
        && good_litalu1(arr)
        && good_balance(arr)
        && good_lit_slot(arr);
}

function print_row (arr) {
    var i, ret, count;

    ret = '<tr> <td> ';
    for (i = 0; i < arr.length; i++) {
        ret += words[arr[i]].name + ' ';
    }
    ret += ' </td> <td> ';
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[5];
    }
    ret += count + ' </td> <td> ';
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[6];
    }
    ret += count + ' </td>\n';
    return ret;
}

exports.dump = function (arr) {
    arr[0].forEach(function (e) {
        console.log(
            (
                e.reduce(function (a, i) {
                    return a + ' ' + words[i].name;
                }, '') + ' '.repeat(50)
            ).slice(0, 40) +
            (
                e.reduce(function (a, i) {
                    return a + words[i].use[5];
                }, 0) + ' '.repeat(5)
            ).slice(0, 5) +
            (
                e.reduce(function (a, i) {
                    return a + words[i].use[6];
                }, 0) + ' '.repeat(5)
            ).slice(0, 5)
        );
    });
    console.log('total: %s', arr[1]);
};

exports.run1 = function run1 () {
    var i,
        count = 0,
        ret = [];

    for (i = 0; i < words.length; i++) {
        if (good_to_go([i])) {
            ret.push([i]);
            count += 1;
        }
    }
    return [ret, count];
};

exports.run2 = function run2 () {
    var i0, i1,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (good_to_go([i0, i1])) {
                ret.push([i0, i1]);
                count += 1;
            }
        }}
    }
    return [ret, count];
};

exports.run3 = function run3 (reports) {
    var i0, i1, i2,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (good_to_go([i0, i1, i2])) {
                    if (count < reports) { ret.push([i0, i1, i2]); }
                    count += 1;
                }
            }}
        }}
    }
    return [ret, count];
};

exports.run4 = function run4 (reports) {
    var i0, i1, i2, i3,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (!(branch && (words[i2].use[0]))) { // branch slot
                for (i3 = 0; i3 < words.length; i3++) {
                    if (good_to_go([i0, i1, i2, i3])) {
                        if (count < reports) { ret.push([i0, i1, i2, i3]); }
                        if (count > 1000000) {
                            return [ret, count];
                        }
                        count += 1;
                    }
                }}
            }}
        }}
    }
    return [ret, count];
};

exports.run5 = function run5 (reports) {
    var i0, i1, i2, i3, i4,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (!(branch && (words[i2].use[0]))) { // branch slot
                for (i3 = 0; i3 < words.length; i3++) {
                    if (!(branch && (words[i3].use[0]))) { // branch slot
                    for (i4 = 0; i4 < words.length; i4++) {
                        if (good_to_go([i0, i1, i2, i3, i4])) {
                            if (count < reports) { ret.push([i0, i1, i2, i3, i4]); }
                            if (count > 1000000) {
                                return [ret, count];
                            }
                            count += 1;
                        }
                    }}
                }}
            }}
        }}
    }
    return [ret, count];
};
<commit_msg>fixed combiner<commit_after>'use strict';

// branch(0) loadstore(1) alu(2) drop-fear(3) tail(4) PS(5) RS(6)
var words = [
    {name:'LIT4',   use:[0, 0, 0, 1,  4,  1, 0, -1, 0]}, // (          -- x )
    {name:'LIT8',   use:[0, 0, 0, 1,  8,  1, 0, -1, 0]}, // (          -- x )
    {name:'LIT16',  use:[0, 0, 0, 1, 16,  1, 0, -1, 0]}, // (          -- x )
    {name:'LIT32',  use:[0, 0, 0, 1, 32,  1, 0, -1, 0]}, // (          -- x )
    {name:'BRANCH', use:[1, 0, 0, 1,  4, -1, 0,  1, 0]}, // (     addr --   )

    {name:'CALL',   use:[1, 0, 0, 1,  0, -1, 1,  1,-1]}, // (     addr --   | -- z )
    {name:'LOAD',   use:[0, 1, 0, 1,  4,  0, 0,  0, 0]}, // (     addr -- val )
    {name:'PICK',   use:[0, 0, 0, 1,  4,  1, 0,  0, 0]}, // (          -- x )
    {name:'DUP',    use:[0, 0, 0, 1,  0,  1, 0,  0, 0]}, // (        x -- x x )
    {name:'R>',     use:[0, 0, 0, 0,  0,  1,-1, -1, 1]}, // (          -- x | x --   )
    {name:'STORE',  use:[0, 1, 0, 0,  4, -1, 0,  2, 0]}, // ( val addr -- val )
    {name:'ALU',    use:[0, 0, 1, 1,  4, -1, 0,  1, 0]}, // (      x y -- z )
    {name:'DROP',   use:[0, 0, 0, 0,  0, -1, 0,  1, 0]}, // (        x --   )
    {name:'>R',     use:[0, 0, 0, 0,  0, -1, 1,  1,-1]}, // (        x --   |   -- x )
];

var options = {
    loadstore: 1,
    alu: 1,
    dropfear: 1,
    lit_slots: 120,
    r2r: 0,
    litalu1: 1,
    ps_push: 1,
    ps_pop: 1,
    rs_push: 1,
    rs_pop: 1,
    branch: 1
};

exports.options = options;

function good_loadstore (arr) {
    if (!options.loadstore) { return 1; }
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[1]; // loadstore
    }
    if (count > 1) { return 0; }
    return 1;
}

function good_alu (arr) {
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[2]; // ALUs
    }
    if (count > options.alu) { return 0; }
    return 1;
}

function good_dropfear (arr) {
    if (!options.dropfear) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'DROP') && (words[arr[i-1]].use[3])) { return 0; } // drop fear
    }
    return 1;
}

function good_lit_slot (arr) {
    var i, count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[4]; // tail
    }
    if (count > options.lit_slots) { return 0; }
    return 1;
}

function good_r2r (arr) {
    if (options.r2r) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'R>') && (words[arr[i-1]].name === '>R')) { return 0; }
        if ((words[arr[i]].name === '>R') && (words[arr[i-1]].name === 'R>')) { return 0; }
    }
    return 1;
}

function good_litalu1 (arr) {
    if (options.litalu1) { return 1; }
    var i;
    for (i = 1; i < arr.length; i++) {
        if ((words[arr[i]].name === 'ALU1') && (words[arr[i-1]].name === 'LIT')) { return 0; }
    }
    return 1;
}

function good_balance (arr) {
    var i, count;

    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[5]; // PS balance
    }
    if (count >  options.ps_push) { return 0; }
    if (count < -options.ps_pop) { return 0; }
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[6]; // RS balance
    }
    if (count >  options.rs_push) { return 0; }
    if (count < -options.rs_pop) { return 0; }
    return 1;
}

function good_to_go (arr) {
    return good_alu(arr)
        && good_loadstore(arr)
        && good_dropfear(arr)
        && good_r2r(arr)
        // && good_litalu1(arr)
        && good_balance(arr)
        && good_lit_slot(arr);
}

function print_row (arr) {
    var i, ret, count;

    ret = '<tr> <td> ';
    for (i = 0; i < arr.length; i++) {
        ret += words[arr[i]].name + ' ';
    }
    ret += ' </td> <td> ';
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[5];
    }
    ret += count + ' </td> <td> ';
    count = 0;
    for (i = 0; i < arr.length; i++) {
        count += words[arr[i]].use[6];
    }
    ret += count + ' </td>\n';
    return ret;
}

exports.dump = function (arr) {
    arr[0].forEach(function (e) {
        console.log(
            (
                e.reduce(function (a, i) {
                    return a + ' ' + words[i].name;
                }, '') + ' '.repeat(50)
            ).slice(0, 40) +
            (
                e.reduce(function (a, i) {
                    return a + words[i].use[5];
                }, 0) + ' '.repeat(5)
            ).slice(0, 5) +
            (
                e.reduce(function (a, i) {
                    return a + words[i].use[6];
                }, 0) + ' '.repeat(5)
            ).slice(0, 5)
        );
    });
    console.log('%s particles of %s quarks', arr[1], arr[0][0].length);
};

exports.run1 = function run1 () {
    var i,
        count = 0,
        ret = [];

    for (i = 0; i < words.length; i++) {
        if (good_to_go([i])) {
            ret.push([i]);
            count += 1;
        }
    }
    return [ret, count];
};

exports.run2 = function run2 () {
    var i0, i1,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (good_to_go([i0, i1])) {
                ret.push([i0, i1]);
                count += 1;
            }
        }}
    }
    return [ret, count];
};

exports.run3 = function run3 (reports) {
    var i0, i1, i2,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (good_to_go([i0, i1, i2])) {
                    if (count < reports) { ret.push([i0, i1, i2]); }
                    count += 1;
                }
            }}
        }}
    }
    return [ret, count];
};

exports.run4 = function run4 (reports) {
    var i0, i1, i2, i3,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (!(branch && (words[i2].use[0]))) { // branch slot
                for (i3 = 0; i3 < words.length; i3++) {
                    if (good_to_go([i0, i1, i2, i3])) {
                        if (count < reports) { ret.push([i0, i1, i2, i3]); }
                        if (count > 1000000) {
                            return [ret, count];
                        }
                        count += 1;
                    }
                }}
            }}
        }}
    }
    return [ret, count];
};

exports.run5 = function run5 (reports) {
    var i0, i1, i2, i3, i4,
        count = 0,
        branch = options.branch,
        ret = [];

    for (i0 = 0; i0 < words.length; i0++) {
        if (!(branch && (words[i0].use[0]))) { // branch slot
        for (i1 = 0; i1 < words.length; i1++) {
            if (!(branch && (words[i1].use[0]))) { // branch slot
            for (i2 = 0; i2 < words.length; i2++) {
                if (!(branch && (words[i2].use[0]))) { // branch slot
                for (i3 = 0; i3 < words.length; i3++) {
                    if (!(branch && (words[i3].use[0]))) { // branch slot
                    for (i4 = 0; i4 < words.length; i4++) {
                        if (good_to_go([i0, i1, i2, i3, i4])) {
                            if (count < reports) { ret.push([i0, i1, i2, i3, i4]); }
                            if (count > 1000000) {
                                return [ret, count];
                            }
                            count += 1;
                        }
                    }}
                }}
            }}
        }}
    }
    return [ret, count];
};
<|endoftext|>


<commit_before>var prog = require('commander');

templateDir = '/Users/adam/.mgen/';

// Main mgen command options
prog
  .version('0.0.1')
  .option('-p, --peppers', 'Add peppers');

// Components Command
prog.command('comp <component_name>')
  .description('Create a component template, JS, and Sass files')

  .option("-d, --directory <path>", "Change the default directory [client/components]", "client/components/")

  .action(function(compName, options){
    require('./component').run(compName, options);
  })

  .on('--help', function() {
    console.log('  Plural item names will produce a parent & child component. e.g. posts with child post');
    console.log('  Use and underscore for any spaced and it will be camelcased and hyph.');
    console.log();
    console.log('  Examples:');
    console.log('    $ mgen comp post');
    console.log('    $ mgen comp posts');
    console.log('    $ mgen comp other_thing');
    console.log('    $ mgen comp other_things');
    console.log();
  });

// fire up Commander
prog.parse(process.argv);
<commit_msg>clean up comments and help file<commit_after>var prog = require('commander');

// global template directory
// TODO add this to config file
templateDir = '/Users/adam/.mgen/';

// Main mgen command options
prog
  .version('0.0.1');

// Components Command
// copies a Meteor component boilerplate folder and moves it into component directory.
prog.command('comp <component_name>')
  .description('Create a component template, JS, and Sass files')

  .option("-d, --directory <path>", "Change the default component directory 'client/components'", "client/components/")

  .action(function(compName, options){
    require('./component').run(compName, options);
  })

  .on('--help', function() {
    console.log('  Create a component boilerplate folder including a HTML template, JS, & Sass file.');
    console.log('  Plural item names will produce a parent & child component. e.g. posts with child post');
    console.log("  If a component name has multiple words use 'snake_case'");
    console.log();
    console.log('  Examples:');
    console.log('  $ mgen comp posts');
    console.log('  $ mgen comp widget_delux');
    console.log();
  });

// fire up Commander
prog.parse(process.argv);

<|endoftext|>


<commit_before>'use strict';

// Node.js built-ins

const childProcess = require('child_process');
const os = require('os');
const path = require('path');

// foreign modules

const fs = require('graceful-fs');
const isExe = require('is-executable').sync;

// this module

const isWindows = os.type().indexOf('Windows') === 0;

function arrayToSet (array) {
  return new Set(array);
}

function setToArray (set) {
  return [...set];
}

function unique (array) {
  return setToArray(arrayToSet(array));
}

function cpSpawn (command, args, options) {
  return new Promise((resolve, reject) => {
    childProcess.spawn(command, args, options)
      .on('error', (err) => {
        reject(err);
      })
      .on('close', () => {
        resolve();
      });
  });
}

function fsReadDir (dirPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, (err, entries) => {
      if (err) {
        if (err.code === 'ENOENT') {
          resolve([]);
          return;
        }
        reject(err);
        return;
      }
      resolve(entries.map((entry) => path.join(dirPath, entry)));
    });
  });
}

// filterBlinkm (commands: String[]) => String[]
function filterBlinkm (input) {
  return unique(input.filter((i) => path.basename(i).match(/^blinkm-/)));
}

// filterExe (commands: String[]) => String[]
function filterExe (input) {
  return input.filter((i) => isExe(i));
}

// list () => Promise
function list () {
  const PATH = process.env.PATH;
  const delimiter = isWindows ? ';' : ':';
  const paths = PATH.split(delimiter);

  return Promise.all(
    paths.map(fsReadDir)
  )
    .then((results) => {
      return filterExe(filterBlinkm([].concat(...results)));
    });
}

// basename (filePath: String) => String
function basename (filePath) {
  if (isWindows) {
    // Windows executables must have an extension, so strip it away
    return path.basename(filePath, path.extname(filePath));
  }
  return path.basename(filePath);
}

// find (needle: String, haystack: String[]) => String
function find (needle, haystack) {
  let matches;
  matches = haystack.filter((entry) => basename(entry) === needle);
  return matches[0];
}

function exec (command) {
  return list()
    .then((commands) => find(`blinkm-${command}`, commands))
    .then((cmdPath) => {
      if (!cmdPath) {
        let err = new Error('ENOENT');
        err.code = 'ENOENT';
        return Promise.reject(err);
      }
      return Promise.resolve(cmdPath);
    })
    .then((cmdPath) => {
      return cpSpawn(cmdPath, process.argv.slice(3), {
        cwd: process.cwd(),
        detached: false,
        env: process.env,
        stdio: 'inherit'
      });
    });
}

module.exports = { exec, filterBlinkm,  find, list };
<commit_msg>ACF-9 # remove use of spread operator<commit_after>'use strict';

// Node.js built-ins

const childProcess = require('child_process');
const os = require('os');
const path = require('path');

// foreign modules

const fs = require('graceful-fs');
const isExe = require('is-executable').sync;

// this module

const isWindows = os.type().indexOf('Windows') === 0;

function arrayToSet (array) {
  return new Set(array);
}

function setToArray (set) {
  return Array.from(set.values());
}

function unique (array) {
  return setToArray(arrayToSet(array));
}

function cpSpawn (command, args, options) {
  return new Promise((resolve, reject) => {
    childProcess.spawn(command, args, options)
      .on('error', (err) => {
        reject(err);
      })
      .on('close', () => {
        resolve();
      });
  });
}

function fsReadDir (dirPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, (err, entries) => {
      if (err) {
        if (err.code === 'ENOENT') {
          resolve([]);
          return;
        }
        reject(err);
        return;
      }
      resolve(entries.map((entry) => path.join(dirPath, entry)));
    });
  });
}

// filterBlinkm (commands: String[]) => String[]
function filterBlinkm (input) {
  return unique(input.filter((i) => path.basename(i).match(/^blinkm-/)));
}

// filterExe (commands: String[]) => String[]
function filterExe (input) {
  return input.filter((i) => isExe(i));
}

// list () => Promise
function list () {
  const PATH = process.env.PATH;
  const delimiter = isWindows ? ';' : ':';
  const paths = PATH.split(delimiter);

  return Promise.all(
    paths.map(fsReadDir)
  )
    .then((results) => {
      let mergedResults = [];
      mergedResults = mergedResults.concat.apply(mergedResults, results);
      return filterExe(filterBlinkm(mergedResults));
    });
}

// basename (filePath: String) => String
function basename (filePath) {
  if (isWindows) {
    // Windows executables must have an extension, so strip it away
    return path.basename(filePath, path.extname(filePath));
  }
  return path.basename(filePath);
}

// find (needle: String, haystack: String[]) => String
function find (needle, haystack) {
  let matches;
  matches = haystack.filter((entry) => basename(entry) === needle);
  return matches[0];
}

function exec (command) {
  return list()
    .then((commands) => find(`blinkm-${command}`, commands))
    .then((cmdPath) => {
      if (!cmdPath) {
        let err = new Error('ENOENT');
        err.code = 'ENOENT';
        return Promise.reject(err);
      }
      return Promise.resolve(cmdPath);
    })
    .then((cmdPath) => {
      return cpSpawn(cmdPath, process.argv.slice(3), {
        cwd: process.cwd(),
        detached: false,
        env: process.env,
        stdio: 'inherit'
      });
    });
}

module.exports = { exec, filterBlinkm,  find, list };
<|endoftext|>


<commit_before>
var commands = module.exports.commands = [
    'addMultiSigAddress'
  , 'backupWallet'
  , 'createRawTransaction'
  , 'decodeRawTransaction'
  , 'dumpPrivKey'
  , 'encryptWallet'
  , 'getAccount'
  , 'getAccountAddress'
  , 'getAddressesByAccount'
  , 'getBalance'
  , 'getBlock'
  , 'getBlockCount'
  , 'getBlockHash'
  , 'getBlockCount'
  , 'getConnectionCount'
  , 'getDifficulty'
  , 'getGenerate'
  , 'getHashesPerSec'
  , 'getHashesPerSec'
  , 'getInfo'
  , 'getMemoryPool'
  , 'getMemoryPool'
  , 'getMiningInfo'
  , 'getNewAddress'
  , 'getRawTransaction'
  , 'getReceivedByAccount'
  , 'getReceivedByAddress'
  , 'getTransaction'
  , 'getWork'
  , 'help'
  , 'importPrivKey'
  , 'importAddress'
  , 'keyPoolRefill'
  , 'listAccounts'
  , 'listReceivedByAccount'
  , 'listReceivedByAddress'
  , 'listSinceBlock'
  , 'listTransactions'
  , 'listUnspent'
  , 'move'
  , 'sendFrom'
  , 'sendMany'
  , 'sendRawTransaction'
  , 'sendToAddress'
  , 'setAccount'
  , 'setGenerate'
  , 'setTxFee'
  , 'signMessage'
  , 'signRawTransaction'
  , 'stop'
  , 'validateAddress'
  , 'verifyMessage'
  , 'walletLock'
  , 'walletPassphrase'
  , 'walletPassphraseChange'
]

module.exports.isCommand = function(command) {
    command = command.toLowerCase();
    var lowerCaseCommands = commands.map(function (item) {
        return item.toLowerCase();
    });
    return lowerCaseCommands.indexOf(command) !== -1 ? true : false;
}
<commit_msg>Removing Ternary<commit_after>
var commands = module.exports.commands = [
    'addMultiSigAddress'
  , 'backupWallet'
  , 'createRawTransaction'
  , 'decodeRawTransaction'
  , 'dumpPrivKey'
  , 'encryptWallet'
  , 'getAccount'
  , 'getAccountAddress'
  , 'getAddressesByAccount'
  , 'getBalance'
  , 'getBlock'
  , 'getBlockCount'
  , 'getBlockHash'
  , 'getBlockCount'
  , 'getConnectionCount'
  , 'getDifficulty'
  , 'getGenerate'
  , 'getHashesPerSec'
  , 'getHashesPerSec'
  , 'getInfo'
  , 'getMemoryPool'
  , 'getMemoryPool'
  , 'getMiningInfo'
  , 'getNewAddress'
  , 'getRawTransaction'
  , 'getReceivedByAccount'
  , 'getReceivedByAddress'
  , 'getTransaction'
  , 'getWork'
  , 'help'
  , 'importPrivKey'
  , 'importAddress'
  , 'keyPoolRefill'
  , 'listAccounts'
  , 'listReceivedByAccount'
  , 'listReceivedByAddress'
  , 'listSinceBlock'
  , 'listTransactions'
  , 'listUnspent'
  , 'move'
  , 'sendFrom'
  , 'sendMany'
  , 'sendRawTransaction'
  , 'sendToAddress'
  , 'setAccount'
  , 'setGenerate'
  , 'setTxFee'
  , 'signMessage'
  , 'signRawTransaction'
  , 'stop'
  , 'validateAddress'
  , 'verifyMessage'
  , 'walletLock'
  , 'walletPassphrase'
  , 'walletPassphraseChange'
]

module.exports.isCommand = function(command) {
    command = command.toLowerCase();
    var lowerCaseCommands = commands.map(function (item) {
        return item.toLowerCase();
    });
    return lowerCaseCommands.indexOf(command) !== -1;
}
<|endoftext|>


<commit_before>var hasOwn = Object.prototype.hasOwnProperty;
var keywordPattern = /\b(import|export)\b/g;
var Parser = require("acorn").Parser;
var parserOptions = {
  ecmaVersion: 7,
  sourceType: "module",
  allowImportExportEverywhere: true,
  allowReturnOutsideFunction: true,
  allowHashBang: true
};

// TODO Cache this.
exports.compile = function (code) {
  return new Compiler(code).compile();
};

function Compiler(code) {
  this.code = code;
}

var Cp = Compiler.prototype;

Cp.compile = function (start, end) {
  if (typeof start === "undefined") start = 0;
  if (typeof end === "undefined") end = this.code.length;

  keywordPattern.lastIndex = start;

  var match;
  var declarations = [];

  while ((match = keywordPattern.exec(this.code))) {
    if (match.index < end) {
      var node = this.parseFrom(match.index);
      if (node && hasOwn.call(Cp, node.type) &&
          (node.type === "ImportDeclaration" ||
           node.type === "ExportAllDeclaration" ||
           node.type === "ExportNamedDeclaration")) {
        declarations.push(node);

        // Any import or export statements contained by the current node
        // will be handled recursively below, so we must skip them here.
        keywordPattern.lastIndex = Math.max(
          keywordPattern.lastIndex,
          node.end
        );
      }
    }
  }

  return this.replace(declarations, function (decl) {
    return this[decl.type](decl);
  }, start, end);
};

// TODO Could this be cached in memory?
// TODO What if start falls in a string literal?
//      Might have to parse the whole file!
Cp.parseFrom = function (start) {
  var p = new Parser(parserOptions, this.code, start);
  p.nextToken();
  try {
    var node = p.parseStatement();
  } finally {
    return node;
  }
};

Cp.replace = function (nodes, callback, start, end) {
  var fragments = [];

  for (var i = nodes.length - 1; i >= 0; --i) {
    var node = nodes[i];

    // All the nodes we're given should fall within [start, end), but just
    // to be safe we ignore those that start or end outside that interval.
    if (node.end > end ||
        node.start < start) {
      continue;
    }

    fragments.push(
      this.code.slice(node.end, end),
      // TODO Pad to as many lines as original.
      callback.call(this, node, i)
    );

    end = node.start;
  }

  fragments.push(this.code.slice(start, end));

  return fragments.reverse().join("");
};

// TODO Always generate a trailing semicolon!

Cp.ImportDeclaration = function (decl) {
  var code = this.code;
  var parts = [];

  if (decl.specifiers.length > 0) {
    // It's tempting to use let instead of var when possible, but that
    // makes it impossible to redeclare variables, which is quite handy.
    parts.push("var ");

    decl.specifiers.forEach(function (s, i) {
      var isLast = i === decl.specifiers.length - 1;
      parts.push(s.local.name, isLast ? ";" : ",");
    });
  }

  parts.push(
    "module.import(",
    this.code.slice(decl.source.start,
                    decl.source.end)
  );

  if (decl.specifiers.length === 0) {
    parts.push(");");
    return parts.join("");
  }

  parts.push(",{");

  decl.specifiers.forEach(function (s, i) {
    var local = s.local.name;
    var imported =
      s.type === "ImportSpecifier" ? s.imported.name :
      s.type === "ImportDefaultSpecifier" ? "default" :
      s.type === "ImportNamespaceSpecifier" ? "*" :
      null;

    var valueArg = "v";
    if (valueArg === local) {
      // Since we're creating a new scope, it's easy to avoid collisions
      // with the one other variable name that we care about.
      valueArg = "_" + valueArg;
    }

    var isLast = i === decl.specifiers.length - 1;
    parts.push(
      JSON.stringify(imported),
      ":function(", valueArg, "){",
      local, "=", valueArg,
      isLast ? "}" : "},"
    );
  });

  parts.push("});");

  return parts.join("");
};

Cp.ExportAllDeclaration = function (decl) {
  return [
    "module.import(",
    this.code.slice(decl.source.start,
                    decl.source.end),
    ",{'*':function(all){",
    "this.assign(exports,all);",
    "return true;",
    "}});"
  ].join("");
};

Cp.ExportNamedDeclaration = function (decl) {
  var dd = decl.declaration;
  if (dd) {
    return this[dd.type](dd);
  }

  if (decl.specifiers) {
    // TODO
  }

  throw new Error("export by name not yet fully supported");
};

Cp.FunctionDeclaration =
Cp.ClassDeclaration = function (decl) {
  return [
    this.compile(decl.start, decl.end),
    ";exports.", decl.id.name, "=", decl.id.name, ";"
  ].join("");
};

Cp.VariableDeclaration = function (decl) {
  return this.replace(decl.declarations, function (item) {
    return this.replace([
      item.id,
      item.init
    ], function (node, i) {
      if (i === 0) {
        // node === item.id
        return node.name + " = exports." + node.name;
      }

      if (i === 1) {
        // node === item.init
        return this.compile(node.start, node.end);
      }

    }, item.start, item.end);
  }, decl.start, decl.end);
};
<commit_msg>Decompose toModuleImport and computeSpecifierMap helper functions.<commit_after>var hasOwn = Object.prototype.hasOwnProperty;
var keywordPattern = /\b(import|export)\b/g;
var Parser = require("acorn").Parser;
var parserOptions = {
  ecmaVersion: 7,
  sourceType: "module",
  allowImportExportEverywhere: true,
  allowReturnOutsideFunction: true,
  allowHashBang: true
};

// TODO Cache this.
exports.compile = function (code) {
  return new Compiler(code).compile();
};

function Compiler(code) {
  this.code = code;
}

var Cp = Compiler.prototype;

Cp.compile = function (start, end) {
  if (typeof start === "undefined") start = 0;
  if (typeof end === "undefined") end = this.code.length;

  keywordPattern.lastIndex = start;

  var match;
  var declarations = [];

  while ((match = keywordPattern.exec(this.code))) {
    if (match.index < end) {
      var node = this.parseFrom(match.index);
      if (node && hasOwn.call(Cp, node.type) &&
          (node.type === "ImportDeclaration" ||
           node.type === "ExportAllDeclaration" ||
           node.type === "ExportNamedDeclaration")) {
        declarations.push(node);

        // Any import or export statements contained by the current node
        // will be handled recursively below, so we must skip them here.
        keywordPattern.lastIndex = Math.max(
          keywordPattern.lastIndex,
          node.end
        );
      }
    }
  }

  return this.replace(declarations, function (decl) {
    return this[decl.type](decl);
  }, start, end);
};

// TODO Could this be cached in memory?
// TODO What if start falls in a string literal?
//      Might have to parse the whole file!
Cp.parseFrom = function (start) {
  var p = new Parser(parserOptions, this.code, start);
  p.nextToken();
  try {
    var node = p.parseStatement();
  } finally {
    return node;
  }
};

Cp.replace = function (nodes, callback, start, end) {
  var fragments = [];

  for (var i = nodes.length - 1; i >= 0; --i) {
    var node = nodes[i];

    // All the nodes we're given should fall within [start, end), but just
    // to be safe we ignore those that start or end outside that interval.
    if (node.end > end ||
        node.start < start) {
      continue;
    }

    fragments.push(
      this.code.slice(node.end, end),
      // TODO Pad to as many lines as original.
      callback.call(this, node, i)
    );

    end = node.start;
  }

  fragments.push(this.code.slice(start, end));

  return fragments.reverse().join("");
};

// TODO Always generate a trailing semicolon!

Cp.ImportDeclaration = function (decl) {
  var code = this.code;
  var parts = [];

  if (decl.specifiers.length > 0) {
    // It's tempting to use let instead of var when possible, but that
    // makes it impossible to redeclare variables, which is quite handy.
    parts.push("var ");

    decl.specifiers.forEach(function (s, i) {
      var isLast = i === decl.specifiers.length - 1;
      parts.push(s.local.name, isLast ? ";" : ",");
    });
  }

  parts.push(toModuleImport(
    this.code.slice(decl.source.start,
                    decl.source.end),
    computeSpecifierMap(decl.specifiers)
  ));

  return parts.join("");
};

function computeSpecifierMap(specifiers) {
  var specifierMap;

  specifiers.forEach(function (s) {
    var local = s.local.name;
    var imported =
      s.type === "ImportSpecifier" ? s.imported.name :
      s.type === "ImportDefaultSpecifier" ? "default" :
      s.type === "ImportNamespaceSpecifier" ? "*" :
      null;

    specifierMap = specifierMap || {};
    specifierMap[local] = imported;
  });

  return specifierMap;
}

function toModuleImport(source, specifierMap) {
  var parts = ["module.import(", source];
  var locals = specifierMap && Object.keys(specifierMap);

  if (! locals || locals.length === 0) {
    parts.push(");");
    return parts.join("");
  }

  parts.push(",{");

  locals.forEach(function (local, i) {
    var isLast = i === locals.length - 1;
    var imported = specifierMap[local];

    var valueArg = "v";
    if (valueArg === local) {
      // Since we're creating a new scope, it's easy to avoid collisions
      // with the one other variable name that we care about.
      valueArg = "_" + valueArg;
    }

    parts.push(
      JSON.stringify(imported),
      ":function(", valueArg, "){",
      local, "=", valueArg,
      isLast ? "}" : "},"
    );
  });

  parts.push("});");

  return parts.join("");
}

Cp.ExportAllDeclaration = function (decl) {
  return [
    "module.import(",
    this.code.slice(decl.source.start,
                    decl.source.end),
    ",{'*':function(all){",
    "this.assign(exports,all);",
    "return true;",
    "}});"
  ].join("");
};

Cp.ExportNamedDeclaration = function (decl) {
  var dd = decl.declaration;
  if (dd) {
    return this[dd.type](dd);
  }

  if (decl.specifiers) {
    // TODO
  }

  throw new Error("export by name not yet fully supported");
};

Cp.FunctionDeclaration =
Cp.ClassDeclaration = function (decl) {
  return [
    this.compile(decl.start, decl.end),
    ";exports.", decl.id.name, "=", decl.id.name, ";"
  ].join("");
};

Cp.VariableDeclaration = function (decl) {
  return this.replace(decl.declarations, function (item) {
    return this.replace([
      item.id,
      item.init
    ], function (node, i) {
      if (i === 0) {
        // node === item.id
        return node.name + " = exports." + node.name;
      }

      if (i === 1) {
        // node === item.init
        return this.compile(node.start, node.end);
      }

    }, item.start, item.end);
  }, decl.start, decl.end);
};
<|endoftext|>


<commit_before>module.exports = {
  // 开发环境编译配置
  development : config => ({
    compiler_public_path : `http://${config.server_host}:${config.server_port}/`
  }),

  // 生产环境编译配置
  production : config => ({
    compiler_public_path     : `/${config.project_name}/`,
    compiler_fail_on_warning : false,
    compiler_hash_type       : 'chunkhash',
    compiler_devtool         : null,
    compiler_stats           : {
      chunks       : true,
      chunkModules : true,
      colors       : true
    }
  })
}
<commit_msg>update<commit_after>module.exports = {
  // 开发环境编译配置
  development : config => ({
    compiler_public_path : `http://${config.server_host}:${config.server_port}/`
  }),

  // 生产环境编译配置
  production : config => ({
    compiler_public_path     : config.project_name ? `/${config.project_name}/` : '/',
    compiler_fail_on_warning : false,
    compiler_hash_type       : 'chunkhash',
    compiler_devtool         : null,
    compiler_stats           : {
      chunks       : true,
      chunkModules : true,
      colors       : true
    }
  })
}
<|endoftext|>


<commit_before>
/*!
 * Jade - Compiler
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var nodes = require('./nodes')
  , filters = require('./filters')
  , doctypes = require('./doctypes')
  , selfClosing = require('./self-closing')
  , utils = require('./utils');

// if browser
// if (!String.prototype.trimLeft) {
//   String.prototype.trimLeft = function(){
//     return this.replace(/^\s+/, '');
//   }
// }
// end

/**
 * Initialize `Compiler` with the given `node`.
 *
 * @param {Node} node
 * @param {Object} options
 * @api public
 */

var Compiler = module.exports = function Compiler(node, options) {
  this.options = options = options || {};
  this.node = node;
};

/**
 * Compiler prototype.
 */

Compiler.prototype = {

  /**
   * Compile parse tree to JavaScript.
   *
   * @api public
   */

  compile: function(){
    this.buf = ['var interp;'];
    this.visit(this.node);
    return this.buf.join('\n');
  },

  /**
   * Buffer the given `str` optionally escaped.
   *
   * @param {String} str
   * @param {Boolean} esc
   * @api public
   */

  buffer: function(str, esc){
    if (esc) str = utils.escape(str);
    this.buf.push("buf.push('" + str + "');");
  },

  /**
   * Buffer the given `node`'s lineno.
   *
   * @param {Node} node
   * @api public
   */

  line: function(node){
    if (node.instrumentLineNumber === false) return;
    this.buf.push('__.lineno = ' + node.line + ';');
  },

  /**
   * Visit `node`.
   *
   * @param {Node} node
   * @api public
   */

  visit: function(node){
    this.line(node);
    return this.visitNode(node);
  },

  /**
   * Visit `node`.
   *
   * @param {Node} node
   * @api public
   */

  visitNode: function(node){
    var name = node.constructor.name
      || node.constructor.toString().match(/function ([^(\s]+)()/)[1];
    return this['visit' + name](node);
  },

  /**
   * Visit all nodes in `block`.
   *
   * @param {Block} block
   * @api public
   */

  visitBlock: function(block){
    var len = len = block.nodes.length;
    for (var i = 0; i < len; ++i) {
      this.visit(block.nodes[i]);
    }
  },

  /**
   * Visit `doctype`. Sets terse mode to `true` when html 5
   * is used, causing self-closing tags to end with ">" vs "/>",
   * and boolean attributes are not mirrored.
   *
   * @param {Doctype} doctype
   * @api public
   */

  visitDoctype: function(doctype){
    var name = doctype.val;
    if ('5' == name) this.terse = true;
    doctype = doctypes[name || 'default'];
    this.xml = 0 == doctype.indexOf('<?xml');
    if (!doctype) throw new Error('unknown doctype "' + name + '"');
    this.buffer(doctype);
  },

  /**
   * Visit `tag` buffering tag markup, generating
   * attributes, visiting the `tag`'s code and block.
   *
   * @param {Tag} tag
   * @api public
   */

  visitTag: function(tag){
    var name = tag.name;

    if (~selfClosing.indexOf(name) && !this.xml) {
      this.buffer('<' + name);
      this.visitAttributes(tag.attrs);
      this.terse
        ? this.buffer('>')
        : this.buffer('/>');
    } else {
      // Optimize attributes buffering
      if (tag.attrs.length) {
        this.buffer('<' + name);
        if (tag.attrs.length) this.visitAttributes(tag.attrs);
        this.buffer('>');
      } else {
        this.buffer('<' + name + '>');
      }
      if (tag.code) this.visitCode(tag.code);
      if (tag.text) this.buffer(utils.text(tag.text.nodes[0].trimLeft()));
      this.escape = 'pre' == tag.name;
      this.visit(tag.block);
      this.buffer('</' + name + '>');
    }
  },

  /**
   * Visit `filter`, throwing when the filter does not exist.
   *
   * @param {Filter} filter
   * @api public
   */

  visitFilter: function(filter){
    var fn = filters[filter.name];

    // unknown filter
    if (!fn) {
      if (filter.isASTFilter) {
        throw new Error('unknown ast filter "' + filter.name + ':"');
      } else {
        throw new Error('unknown filter ":' + filter.name + '"');
      }
    }
    if (filter.isASTFilter) {
      this.buf.push(fn(filter.block, this, filter.attrs));
    } else {
      var text = filter.block.nodes.join('');
      this.buffer(utils.text(fn(text, filter.attrs)));
    }
  },

  /**
   * Visit `text` node.
   *
   * @param {Text} text
   * @api public
   */

  visitText: function(text){
    text = utils.text(text.nodes.join(''));
    if (this.escape) text = escape(text);
    this.buffer(text);
    this.buffer('\\n');
  },

  /**
   * Visit a `comment`, only buffering when the buffer flag is set.
   *
   * @param {Comment} comment
   * @api public
   */

  visitComment: function(comment){
    if (!comment.buffer) return;
    this.buffer('<!--' + utils.escape(comment.val) + '-->');
  },

  /**
   * Visit a `BlockComment`.
   *
   * @param {Comment} comment
   * @api public
   */

  visitBlockComment: function(comment){
    if (0 == comment.val.indexOf('if')) {
      this.buffer('<!--[' + comment.val + ']>');
      this.visit(comment.block);
      this.buffer('<![endif]-->');
    } else {
      this.buffer('<!--' + comment.val);
      this.visit(comment.block);
      this.buffer('-->');
    }
  },

  /**
   * Visit `code`, respecting buffer / escape flags.
   * If the code is followed by a block, wrap it in
   * a self-calling function.
   *
   * @param {Code} code
   * @api public
   */

  visitCode: function(code){
    // Wrap code blocks with {}.
    // we only wrap unbuffered code blocks ATM
    // since they are usually flow control

    // Buffer code
    if (code.buffer) {
      var val = code.val.trimLeft();
      this.buf.push('var __val__ = ' + val);
      val = 'null == __val__ ? "" : __val__';
      if (code.escape) val = 'escape(' + val + ')';
      this.buf.push("buf.push(" + val + ");");
    } else {
      this.buf.push(code.val);
    }

    // Block support
    if (code.block) {
      if (!code.buffer) this.buf.push('{');
      this.visit(code.block);
      if (!code.buffer) this.buf.push('}');
    }
  },

  /**
   * Visit `each` block.
   *
   * @param {Each} each
   * @api public
   */

  visitEach: function(each){
    this.buf.push(''
      + '// iterate ' + each.obj + '\n'
      + '(function(){\n'
      + '  if (\'number\' == typeof ' + each.obj + '.length) {\n'
      + '    for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n'
      + '      var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');

    this.visit(each.block);

    this.buf.push(''
      + '    }\n'
      + '  } else {\n'
      + '    for (var ' + each.key + ' in ' + each.obj + ') {\n'
      // if browser
      // + '      if (' + each.obj + '.hasOwnProperty(' + each.key + ')){'
      // end
      + '      var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');

    this.visit(each.block);

    // if browser
    // this.buf.push('      }\n');
    // end

    this.buf.push('   }\n  }\n}).call(this);\n');
  },

  /**
   * Visit `attrs`.
   *
   * @param {Array} attrs
   * @api public
   */

  visitAttributes: function(attrs){
    var buf = []
      , classes = [];

    if (this.terse) buf.push('terse: true');

    attrs.forEach(function(attr){
      if (attr.name == 'class') {
        classes.push('(' + attr.val + ')');
      } else {
        var pair = "'" + attr.name + "':(" + attr.val + ')';
        buf.push(pair);
      }
    });

    if (classes.length) {
      classes = classes.join(" + ' ' + ");
      buf.push("class: " + classes);
    }

    buf = buf.join(', ').replace('class:', '"class":');

    this.buf.push("buf.push(attrs({ " + buf + " }));");
  }
};

/**
 * Escape the given string of `html`.
 *
 * @param {String} html
 * @return {String}
 * @api private
 */

function escape(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
}
<commit_msg>Added Object.keys() for the client-side<commit_after>
/*!
 * Jade - Compiler
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var nodes = require('./nodes')
  , filters = require('./filters')
  , doctypes = require('./doctypes')
  , selfClosing = require('./self-closing')
  , utils = require('./utils');

// if browser
//
// if (!Object.keys) {
//   Object.keys = function(obj){
//     var arr;
//     for (var key in obj) {
//       if (obj.hasOwnProperty(key)) {
//         arr.push(obj);
//       }
//     }
//     return arr;
//   }
// }
//
// if (!String.prototype.trimLeft) {
//   String.prototype.trimLeft = function(){
//     return this.replace(/^\s+/, '');
//   }
// }
//
// end

/**
 * Initialize `Compiler` with the given `node`.
 *
 * @param {Node} node
 * @param {Object} options
 * @api public
 */

var Compiler = module.exports = function Compiler(node, options) {
  this.options = options = options || {};
  this.node = node;
};

/**
 * Compiler prototype.
 */

Compiler.prototype = {

  /**
   * Compile parse tree to JavaScript.
   *
   * @api public
   */

  compile: function(){
    this.buf = ['var interp;'];
    this.visit(this.node);
    return this.buf.join('\n');
  },

  /**
   * Buffer the given `str` optionally escaped.
   *
   * @param {String} str
   * @param {Boolean} esc
   * @api public
   */

  buffer: function(str, esc){
    if (esc) str = utils.escape(str);
    this.buf.push("buf.push('" + str + "');");
  },

  /**
   * Buffer the given `node`'s lineno.
   *
   * @param {Node} node
   * @api public
   */

  line: function(node){
    if (node.instrumentLineNumber === false) return;
    this.buf.push('__.lineno = ' + node.line + ';');
  },

  /**
   * Visit `node`.
   *
   * @param {Node} node
   * @api public
   */

  visit: function(node){
    this.line(node);
    return this.visitNode(node);
  },

  /**
   * Visit `node`.
   *
   * @param {Node} node
   * @api public
   */

  visitNode: function(node){
    var name = node.constructor.name
      || node.constructor.toString().match(/function ([^(\s]+)()/)[1];
    return this['visit' + name](node);
  },

  /**
   * Visit all nodes in `block`.
   *
   * @param {Block} block
   * @api public
   */

  visitBlock: function(block){
    var len = len = block.nodes.length;
    for (var i = 0; i < len; ++i) {
      this.visit(block.nodes[i]);
    }
  },

  /**
   * Visit `doctype`. Sets terse mode to `true` when html 5
   * is used, causing self-closing tags to end with ">" vs "/>",
   * and boolean attributes are not mirrored.
   *
   * @param {Doctype} doctype
   * @api public
   */

  visitDoctype: function(doctype){
    var name = doctype.val;
    if ('5' == name) this.terse = true;
    doctype = doctypes[name || 'default'];
    this.xml = 0 == doctype.indexOf('<?xml');
    if (!doctype) throw new Error('unknown doctype "' + name + '"');
    this.buffer(doctype);
  },

  /**
   * Visit `tag` buffering tag markup, generating
   * attributes, visiting the `tag`'s code and block.
   *
   * @param {Tag} tag
   * @api public
   */

  visitTag: function(tag){
    var name = tag.name;

    if (~selfClosing.indexOf(name) && !this.xml) {
      this.buffer('<' + name);
      this.visitAttributes(tag.attrs);
      this.terse
        ? this.buffer('>')
        : this.buffer('/>');
    } else {
      // Optimize attributes buffering
      if (tag.attrs.length) {
        this.buffer('<' + name);
        if (tag.attrs.length) this.visitAttributes(tag.attrs);
        this.buffer('>');
      } else {
        this.buffer('<' + name + '>');
      }
      if (tag.code) this.visitCode(tag.code);
      if (tag.text) this.buffer(utils.text(tag.text.nodes[0].trimLeft()));
      this.escape = 'pre' == tag.name;
      this.visit(tag.block);
      this.buffer('</' + name + '>');
    }
  },

  /**
   * Visit `filter`, throwing when the filter does not exist.
   *
   * @param {Filter} filter
   * @api public
   */

  visitFilter: function(filter){
    var fn = filters[filter.name];

    // unknown filter
    if (!fn) {
      if (filter.isASTFilter) {
        throw new Error('unknown ast filter "' + filter.name + ':"');
      } else {
        throw new Error('unknown filter ":' + filter.name + '"');
      }
    }
    if (filter.isASTFilter) {
      this.buf.push(fn(filter.block, this, filter.attrs));
    } else {
      var text = filter.block.nodes.join('');
      this.buffer(utils.text(fn(text, filter.attrs)));
    }
  },

  /**
   * Visit `text` node.
   *
   * @param {Text} text
   * @api public
   */

  visitText: function(text){
    text = utils.text(text.nodes.join(''));
    if (this.escape) text = escape(text);
    this.buffer(text);
    this.buffer('\\n');
  },

  /**
   * Visit a `comment`, only buffering when the buffer flag is set.
   *
   * @param {Comment} comment
   * @api public
   */

  visitComment: function(comment){
    if (!comment.buffer) return;
    this.buffer('<!--' + utils.escape(comment.val) + '-->');
  },

  /**
   * Visit a `BlockComment`.
   *
   * @param {Comment} comment
   * @api public
   */

  visitBlockComment: function(comment){
    if (0 == comment.val.indexOf('if')) {
      this.buffer('<!--[' + comment.val + ']>');
      this.visit(comment.block);
      this.buffer('<![endif]-->');
    } else {
      this.buffer('<!--' + comment.val);
      this.visit(comment.block);
      this.buffer('-->');
    }
  },

  /**
   * Visit `code`, respecting buffer / escape flags.
   * If the code is followed by a block, wrap it in
   * a self-calling function.
   *
   * @param {Code} code
   * @api public
   */

  visitCode: function(code){
    // Wrap code blocks with {}.
    // we only wrap unbuffered code blocks ATM
    // since they are usually flow control

    // Buffer code
    if (code.buffer) {
      var val = code.val.trimLeft();
      this.buf.push('var __val__ = ' + val);
      val = 'null == __val__ ? "" : __val__';
      if (code.escape) val = 'escape(' + val + ')';
      this.buf.push("buf.push(" + val + ");");
    } else {
      this.buf.push(code.val);
    }

    // Block support
    if (code.block) {
      if (!code.buffer) this.buf.push('{');
      this.visit(code.block);
      if (!code.buffer) this.buf.push('}');
    }
  },

  /**
   * Visit `each` block.
   *
   * @param {Each} each
   * @api public
   */

  visitEach: function(each){
    this.buf.push(''
      + '// iterate ' + each.obj + '\n'
      + '(function(){\n'
      + '  if (\'number\' == typeof ' + each.obj + '.length) {\n'
      + '    for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n'
      + '      var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');

    this.visit(each.block);

    this.buf.push(''
      + '    }\n'
      + '  } else {\n'
      + '    for (var ' + each.key + ' in ' + each.obj + ') {\n'
      // if browser
      // + '      if (' + each.obj + '.hasOwnProperty(' + each.key + ')){'
      // end
      + '      var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');

    this.visit(each.block);

    // if browser
    // this.buf.push('      }\n');
    // end

    this.buf.push('   }\n  }\n}).call(this);\n');
  },

  /**
   * Visit `attrs`.
   *
   * @param {Array} attrs
   * @api public
   */

  visitAttributes: function(attrs){
    var buf = []
      , classes = [];

    if (this.terse) buf.push('terse: true');

    attrs.forEach(function(attr){
      if (attr.name == 'class') {
        classes.push('(' + attr.val + ')');
      } else {
        var pair = "'" + attr.name + "':(" + attr.val + ')';
        buf.push(pair);
      }
    });

    if (classes.length) {
      classes = classes.join(" + ' ' + ");
      buf.push("class: " + classes);
    }

    buf = buf.join(', ').replace('class:', '"class":');

    this.buf.push("buf.push(attrs({ " + buf + " }));");
  }
};

/**
 * Escape the given string of `html`.
 *
 * @param {String} html
 * @return {String}
 * @api private
 */

function escape(html){
  return String(html)
    .replace(/&(?!\w+;)/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"');
}
<|endoftext|>


<commit_before>var atomSassActivated = false;
const fs = require('fs');

module.exports = Compiler = (function() {
    function Compiler() {
        var _this = this;

        if (atomSassActivated === false)
        {
            atom.notifications.addSuccess( 'Now watching for Sass files.' );
            atomSassActivated = true;

            atom.project.observeBuffers(function( buffer )
            {
                var textBuffer = buffer;

                //  there was previously a check for the sass extension before watching a file
                //  that is possibly a bug a sa file could be saved to a different name.
                //  now watching all files and doing that check in onSaves call-back

                textBuffer.onDidChangeModified(function(){
                        textBuffer['atom-sass-view-modified'] = true;
                });
                textBuffer.onDidSave( function( e )
                {
                    var saveFilePath = e['path'];

                    if ( !textBuffer['atom-sass-view-modified'] ) {
                            return false;
                    }
                    textBuffer['atom-sass-view-modified'] = false;

                    var path = require('path');
                    var extension = path.extname(saveFilePath);
                    if ( extension === '.scss' || extension === '.sass' ) {
                            _this.compile( saveFilePath );
                    }
                });
            });
        } else
        {
            atom.notifications.addSuccess( 'Already watching for Sass files.' );
        }
    }

    Compiler.prototype.compile = function( sassFilePath ) {

        var exec = require('child_process').exec,
            path = require('path');

        var extension = path.extname(sassFilePath);
        var cssFileName = path.basename(sassFilePath).replace(extension, '.css');
        var cssFilePath = path.join(path.dirname(sassFilePath),cssFileName);

        fs.access(cssFilePath, fs.constants.F_OK, (err) => {
            console.log(err ? 'no access!' : 'can read/write');
        });

        var execString = 'sass ' + '"' + sassFilePath + '"' + ' ' + '"' + cssFilePath +  '"';

        exec( execString, function (error, stdout, stderr)
        {
            if ( error ) {
                atom.notifications.addError( 'Error while compiling:',{
                    detail: error.message,
                    dismissable: true
                });
            } else {
                atom.notifications.addSuccess( 'Successfuly compiled' );
            }
        });
    };

    return Compiler;
})();
<commit_msg>Update compiler.js<commit_after>var atomSassActivated = false;
const fs = require('fs');

module.exports = Compiler = (function() {
    function Compiler() {
        var _this = this;

        if (atomSassActivated === false)
        {
            atom.notifications.addSuccess( 'Now watching for Sass files.' );
            atomSassActivated = true;

            atom.project.observeBuffers(function( buffer )
            {
                var textBuffer = buffer;

                //  there was previously a check for the sass extension before watching a file
                //  that is possibly a bug a sa file could be saved to a different name.
                //  now watching all files and doing that check in onSaves call-back

                textBuffer.onDidChangeModified(function(){
                    textBuffer['atom-sass-view-modified'] = true;
                });
                textBuffer.onDidSave( function( e )
                {
                    var saveFilePath = e['path'];

                    if ( !textBuffer['atom-sass-view-modified'] ) {
                        return false;
                    }
                    textBuffer['atom-sass-view-modified'] = false;

                    var path = require('path');
                    var extension = path.extname(saveFilePath);
                    if ( extension === '.scss' || extension === '.sass' ) {
                        _this.compile( saveFilePath );
                    }
                });
            });
        } else
        {
            atom.notifications.addSuccess( 'Already watching for Sass files.' );
        }
    }

    Compiler.prototype.compile = function( sassFilePath ) {

        var exec = require('child_process').exec,
            path = require('path');

        var extension = path.extname(sassFilePath);
        var cssFileName = path.basename(sassFilePath).replace(extension, '.css');
        var cssFilePath = path.join(path.dirname(sassFilePath),cssFileName);

        fs.access(cssFilePath, fs.constants.F_OK, (err) => {
            console.log(err ? 'no access!' : 'can read/write');
        });

        var execString = 'sass ' + '"' + sassFilePath + '"' + ' ' + '"' + cssFilePath +  '"';

        exec( execString, function (error, stdout, stderr)
        {
            if ( error ) {
                atom.notifications.addError( 'Error while compiling:',{
                    detail: error.message,
                    dismissable: true
                });
            } else {
                atom.notifications.addSuccess( 'Successfuly compiled' );
            }
        });
    };

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


<commit_before>
var fs = require("fs")
var path = require("path")

var parser = require("./parser").generate(function(bi) {
		var main_rule = bi.main_rule, rule = bi.rule,
			or = bi.or, and = bi.and, rep = bi.rep,
			maybe = bi.maybe, join = bi.join,
			named = bi.named,
			mbs = maybe("space");
		rule("text", named("text", /^([^@#\$\{\}\\]+|\\[^])+/))
		rule("comment", /(^#\*([^\*]+|\*[^#])*\*#)|(^##.+\r?\n?)/)
		rule("space", /^(\s|(^#\*([^\*]+|\*[^#])*\*#)|(^##.+\n?))+/)
		rule("comma", and(mbs, /^,/, mbs))
		rule("name", named("name", /^[a-zA-Z_][a-zA-Z_0-9]*/))
		rule("number", named("number", /^\d+/))
		rule("string", named("string", and(/^"/, rep(or(
						named("text", /^([^@#\$"\\]+|\\[^])+/),
						"var", "directive", "comment"
					)), /^"/)))
		rule("array", named("array", and(/^\[/, mbs, maybe(join("value", "comma")), mbs, /^\]/)))
		rule("hash", named("hash", and(/^\{/, mbs, maybe(join("pair", "comma")), mbs, /^\}/)))
		rule("text_value", or("name", "number", "var", "string", "directive"))
		rule("value", or("name", "number", "var", "string", "directive", "array", "hash"))
		rule("pair", named("pair", and("text_value", mbs, /^:/ , mbs, "value")))
		rule("directive", named("directive", and(/^@/, "name", mbs, /^\(/, mbs, named("file_name", /^"([^"\\]|\\[^])+"/), mbs, /^\)/)))
		function arg_list(s, e) {
			return named("args", and(s, mbs, maybe(join(or("pair", "value"), "comma")), mbs, e))
		}
		rule("index", named("index", and(/^\[/, mbs, "text_value", mbs, /^\]/)))

		rule("filter", and(mbs, /^\|/, mbs, named("filter", named("var", and(or("name", "index"), rep(or(and(/^\./, "name"), and(mbs, "index"))))))))
		var _var = and(maybe("name"),
			rep(or(and(/^\./, "name"), and(mbs, "index"))),
			maybe(named("call", and(mbs, arg_list(/^\(/, /^\)/), maybe(and(mbs, "block"))))),
			rep("filter"));
		rule("var", named("var", and(/^\$/, _var)))
		rule("block", named("block", and(maybe(arg_list(/^\|/, /^\|/)), mbs, /^\{/, and(rep(or("text", "comment", "var", "directive")), /^\}/))))
		main_rule(rep(or("text", "comment", "var", "directive")))
	})

function parseString(file, string) {
	var r = {
			file: file,
			out: null,
			dependencies: [],
			includes: []
		},
		tree;
		try {
			tree = parser(string);
		} catch(e) {
			throw new Error(file + e.message)
		}
	function unescape(s) {
		return s.replace(/\\[^]/g, function(m) { return m.substring(1, 2) })
	}
	function compileItem(item) {
		var i, c, items, code,
			codeHead, codeTail,
			children = item.children;
		switch (item.name) {
		case "text":
			return JSON.stringify(unescape(item.value()))
		case "name":
		case "number":
			return JSON.stringify(item.value());
		case "string":
			items = []
			if (children) {
				for (i = 0; i < children.length; i++) {
					items.push(compileItem(children[i]))
				}
				return items.join(" + ");
			} else
				return "\"\""
		case "index":
			return compileItem(children[0])
		case "array":
			items = []
			for (i = 0; i < children.length; i++) {
				items.push(compileItem(children[i]))
			}
			return "[" + items.join(", ") + "]"
		case "hash":
			codeHead = "(function() { var r = {}; ",
			codeTail = "return r; })()"
			if (children) {
				for (i = 0; i < children.length; i++) {
					var pair = children[i],
						key = pair.children[0],
						value = pair.children[1];
					codeHead += "r[" + compileItem(key) + "] = " + compileItem(value) + "; ";
				}
			}
			return codeHead + codeTail;
		case "directive":
			var directive = children[0].value(),
				argument = unescape(children[1].value().replace(/^"|"$/g, "")),
				filePath = path.join(path.dirname(file), argument);
			switch (directive) {
			case "include":
				r.includes.push(filePath);
				return "includes[" + JSON.stringify(filePath) + "]"
			case "parse":
				r.dependencies.push(filePath);
				return "dependencies[" + JSON.stringify(filePath) + "]($ctx)"
			default:
				throw new Error("Unknown directive: " + JSON.stringify(directive))
			}
		case "block":
			codeHead = "(function(ctx) { return function($unused, $args) { var $ctx = context(ctx); "
			codeTail = "}})($ctx)"
			items = []
			for(i = 0; i < children.length; i++) {
				c = children[i];
				if(c.name=="args") {
					var al = c.children || []
					for(var j = 0; j < al.length; j++) {
						var argName, argValue;
						if(al[j].name=="pair") {
							argName = compileItem(al[j].children[0])
							argValue = compileItem(al[j].children[1])
						} else {
							argName = compileItem(al[j])
							argValue = "null"
						}
						codeHead += "$ctx[" + argName + "] = "
							+ "$args['" + j + "'] === undefined ? ("
							+ "$args[" + argName + "] === undefined ? "
							+ argValue + ": $args[" + argName + "]"
							+ ") : $args['" + j + "']; "
					}
				} else
					items.push(compileItem(c))
			}
			return codeHead + "return " + items.join(" + ") + "; " + codeTail;
		case "var":
			code = "$ctx"
			if(children) {
				for(i = 0; i < children.length; i++) {
					c = children[i];
					switch(c.name) {
					case "name":
					case "index":
						code = "varIndex(" + code + ", " + compileItem(c) + ")";
						break;
					case "call":
						codeHead = "(function() { var args = {}; ";
						codeTail = "return varCall(" + code + ", $ctx, args); })()";
						(function appendArguments() {
							for(var j = 0; j < c.children.length; j++) {
								var item = c.children[j]
								switch(item.name) {
								case "args":
									if(item.children) {
										for(var n = 0; n < item.children.length; n++) {
											var a = item.children[n];
											if(a.name === "pair") {
												codeHead += "args[" + compileItem(a.children[0]) + "] = " + compileItem(a.children[1]) + "; "
											} else
												codeHead += "args['" + n + "'] = " + compileItem(a) + "; "
										}
									}
									break
								case "block":
									codeHead += "args['yield'] = " + compileItem(item) + "; "
									break
								}
							}
						})()
						code = codeHead + codeTail;
						break;
					case "filter":
						code = "varCall(" + compileItem(c.children[0])
							+ ", $ctx, [" + code + "])"
						break;
					}
				}
			}
			return code;
		default:
			throw new Error("Unknown token \"" + item.name + "\"")
		}
	}
	var i, items = []
	for(i = 0; i < tree.length; i++)
		items.push(compileItem(tree[i]))
	r.out = "function($ctx) { return " + items.join(" + ") + "; }"
	return r;
}

function counter() {
	var v = 0,
		error = null,
		items = [];
	function callHandlers() {
		for(var i in items)
			items[i](error);
		items = []
	}
	return {
		inc: function() {
			if(!error)
				v++
		},
		dec: function() {
			if (!error) {
				v--
				if(v == 0)
					callHandlers()
			}
		},
		fail: function(e) {
			error = e
			v = 0
			callHandlers()
		},
		wait: function(callback) {
			if(v)
				items.push(callback)
			else
				callback(error)
		}
	}
}

function compiler(loader) {
	var compilerObject,
		plugins = {},
		dependencies = {},
		includes = {},
		error = null,
		cnt = counter();
	if(!loader) {
		loader = fileLoader();
	}
	function loadFile(name, callback) {
		cnt.inc()
		loader(name, function(err, content) {
			if (err) {
				cnt.fail(err)
			} else {
				callback(content)
				cnt.dec()
			}
		})
	}
	function getPluginsCode() {
		var i, out = "",
			pathSet = {};
		function createPath(path) {
			var i, ns, items = path.split(".");
			for(i = 1; i < items.length; i++) {
				ns = items.slice(0, i).join(".")
				if (!pathSet[ns]) {
					out += "$ctx['" + ns.replace(".", "']['") + "'] = {}; "
					pathSet[ns] = true
				}
			}
		}
		for (i in plugins) {
			createPath(i)
			out += "$ctx['" + i.replace(".", "']['") + "'] = " + plugins[i] + "; "
		}
		return out;
	}
	function getIncludesCode() {
		return "var includes = " + JSON.stringify(includes) + "; "
	}
	function getDependenciesCode() {
		var codeHead = "var dependencies = {",
			codeTail = "}; ",
			items = [];
		for(var i in dependencies)
			items.push(JSON.stringify(i) + ": " + dependencies[i])
		return codeHead + items.join(", ") + codeTail;
	}

	compilerObject = {
		loadPlugins: function() {
			(function loadPlugins(nameParts, dir) {
				cnt.inc()
				fs.readdir(dir, function(err, files) {
					if(err)
						cnt.fail(err)
					else {
						for(var i in files) {
							cnt.inc();
							(function() {
								var fullName = path.join(dir, files[i]),
									file = files[i];
								fs.stat(fullName, function(err, stat) {
									if(err)
										cnt.fail(err)
									else {
										cnt.dec()
										if(stat.isDirectory()) {
											loadPlugins(nameParts.concat([file]), fullName)
										} else {
											cnt.inc()
											fs.readFile(fullName, "UTF-8", function(err, data) {
												if(err) {
													cnt.fail(err)
												} else {
													plugins[nameParts.concat([file.replace(/\.js$/i, "")]).join(".")] = data
													cnt.dec()
												}
											});
										}
									}
								});
							})()
						}
						cnt.dec()
					}
				})
			})([], path.join(__dirname, "../plugins"))
		},
		plugin: function(name, fileName) {
			if(!plugins[name]) {
				plugins[name] = true
				loadFile(fileName, function(content) {
					plugins[name] = content
				})
			}
		},
		include: function(fileName) {
			if(!includes[fileName]) {
				includes[fileName] = true
				loadFile(fileName, function(content) {
					includes[fileName] = content
				})
			}
		},
		parse: function(fileName) {
			if(!dependencies[fileName]) {
				dependencies[fileName] = true
				loadFile(fileName, function(content) {
					var i, parsed = parseString(fileName, content);
					dependencies[fileName] = parsed.out
					for(i in parsed.includes) {
						compilerObject.include(parsed.includes[i])
					}
					for(i in parsed.dependencies) {
						compilerObject.parse(parsed.dependencies[i])
					}
				})
			}
		},
		getCode: function(callback) {
			cnt.wait(function(err) {
				if(err)
					callback(err, null);
				else {
					callback(null, "(function (fileName, ctx) { "
						+ "\"use strict\";"
						+ "function context() { if(arguments.length) { var rfn = function(){}; rfn.prototype = arguments[0]; return new rfn(); } else return {}; } "
						+ "function varIndex(v, i) { return v ? v[i] : null; } "
						+ "function varCall(v, ctx, args) { return (v && typeof v=='function') ? v(ctx, args) : \"#not_a_function#\"; } "
						+ "var $ctx = context(ctx); "
						+ getPluginsCode() + getIncludesCode() + getDependenciesCode()
						+ "if(dependencies[fileName]) return dependencies[fileName]($ctx); else throw new Error('File not found: \"' + fileName + '\"'); "
						+ "})");
				}
			});
		},
		getFunction: function(callback) {
			compilerObject.getCode(function(err, code) {
				if(err)
					callback(err, null)
				else
					callback(null, new Function("fileName", "ctx", "return " + code + "(fileName, ctx);"))
			})
		}
	}
	return compilerObject
}

function fileLoader(rootPath) {
	if(!rootPath)
		rootPath = "./"
	else if(!/\/$/.test(rootPath))
		root_path += "/"
	return function(fileName, callback) {
		fs.readFile(path.join(rootPath, fileName), "UTF-8", callback)
	}
}

exports.fileLoader = fileLoader
exports.compiler = compiler

<commit_msg>fileLoader fix<commit_after>
var fs = require("fs")
var path = require("path")

var parser = require("./parser").generate(function(bi) {
		var main_rule = bi.main_rule, rule = bi.rule,
			or = bi.or, and = bi.and, rep = bi.rep,
			maybe = bi.maybe, join = bi.join,
			named = bi.named,
			mbs = maybe("space");
		rule("text", named("text", /^([^@#\$\{\}\\]+|\\[^])+/))
		rule("comment", /(^#\*([^\*]+|\*[^#])*\*#)|(^##.+\r?\n?)/)
		rule("space", /^(\s|(^#\*([^\*]+|\*[^#])*\*#)|(^##.+\n?))+/)
		rule("comma", and(mbs, /^,/, mbs))
		rule("name", named("name", /^[a-zA-Z_][a-zA-Z_0-9]*/))
		rule("number", named("number", /^\d+/))
		rule("string", named("string", and(/^"/, rep(or(
						named("text", /^([^@#\$"\\]+|\\[^])+/),
						"var", "directive", "comment"
					)), /^"/)))
		rule("array", named("array", and(/^\[/, mbs, maybe(join("value", "comma")), mbs, /^\]/)))
		rule("hash", named("hash", and(/^\{/, mbs, maybe(join("pair", "comma")), mbs, /^\}/)))
		rule("text_value", or("name", "number", "var", "string", "directive"))
		rule("value", or("name", "number", "var", "string", "directive", "array", "hash"))
		rule("pair", named("pair", and("text_value", mbs, /^:/ , mbs, "value")))
		rule("directive", named("directive", and(/^@/, "name", mbs, /^\(/, mbs, named("file_name", /^"([^"\\]|\\[^])+"/), mbs, /^\)/)))
		function arg_list(s, e) {
			return named("args", and(s, mbs, maybe(join(or("pair", "value"), "comma")), mbs, e))
		}
		rule("index", named("index", and(/^\[/, mbs, "text_value", mbs, /^\]/)))

		rule("filter", and(mbs, /^\|/, mbs, named("filter", named("var", and(or("name", "index"), rep(or(and(/^\./, "name"), and(mbs, "index"))))))))
		var _var = and(maybe("name"),
			rep(or(and(/^\./, "name"), and(mbs, "index"))),
			maybe(named("call", and(mbs, arg_list(/^\(/, /^\)/), maybe(and(mbs, "block"))))),
			rep("filter"));
		rule("var", named("var", and(/^\$/, _var)))
		rule("block", named("block", and(maybe(arg_list(/^\|/, /^\|/)), mbs, /^\{/, and(rep(or("text", "comment", "var", "directive")), /^\}/))))
		main_rule(rep(or("text", "comment", "var", "directive")))
	})

function parseString(file, string) {
	var r = {
			file: file,
			out: null,
			dependencies: [],
			includes: []
		},
		tree;
		try {
			tree = parser(string);
		} catch(e) {
			throw new Error(file + e.message)
		}
	function unescape(s) {
		return s.replace(/\\[^]/g, function(m) { return m.substring(1, 2) })
	}
	function compileItem(item) {
		var i, c, items, code,
			codeHead, codeTail,
			children = item.children;
		switch (item.name) {
		case "text":
			return JSON.stringify(unescape(item.value()))
		case "name":
		case "number":
			return JSON.stringify(item.value());
		case "string":
			items = []
			if (children) {
				for (i = 0; i < children.length; i++) {
					items.push(compileItem(children[i]))
				}
				return items.join(" + ");
			} else
				return "\"\""
		case "index":
			return compileItem(children[0])
		case "array":
			items = []
			for (i = 0; i < children.length; i++) {
				items.push(compileItem(children[i]))
			}
			return "[" + items.join(", ") + "]"
		case "hash":
			codeHead = "(function() { var r = {}; ",
			codeTail = "return r; })()"
			if (children) {
				for (i = 0; i < children.length; i++) {
					var pair = children[i],
						key = pair.children[0],
						value = pair.children[1];
					codeHead += "r[" + compileItem(key) + "] = " + compileItem(value) + "; ";
				}
			}
			return codeHead + codeTail;
		case "directive":
			var directive = children[0].value(),
				argument = unescape(children[1].value().replace(/^"|"$/g, "")),
				filePath = path.join(path.dirname(file), argument);
			switch (directive) {
			case "include":
				r.includes.push(filePath);
				return "includes[" + JSON.stringify(filePath) + "]"
			case "parse":
				r.dependencies.push(filePath);
				return "dependencies[" + JSON.stringify(filePath) + "]($ctx)"
			default:
				throw new Error("Unknown directive: " + JSON.stringify(directive))
			}
		case "block":
			codeHead = "(function(ctx) { return function($unused, $args) { var $ctx = context(ctx); "
			codeTail = "}})($ctx)"
			items = []
			for(i = 0; i < children.length; i++) {
				c = children[i];
				if(c.name=="args") {
					var al = c.children || []
					for(var j = 0; j < al.length; j++) {
						var argName, argValue;
						if(al[j].name=="pair") {
							argName = compileItem(al[j].children[0])
							argValue = compileItem(al[j].children[1])
						} else {
							argName = compileItem(al[j])
							argValue = "null"
						}
						codeHead += "$ctx[" + argName + "] = "
							+ "$args['" + j + "'] === undefined ? ("
							+ "$args[" + argName + "] === undefined ? "
							+ argValue + ": $args[" + argName + "]"
							+ ") : $args['" + j + "']; "
					}
				} else
					items.push(compileItem(c))
			}
			return codeHead + "return " + items.join(" + ") + "; " + codeTail;
		case "var":
			code = "$ctx"
			if(children) {
				for(i = 0; i < children.length; i++) {
					c = children[i];
					switch(c.name) {
					case "name":
					case "index":
						code = "varIndex(" + code + ", " + compileItem(c) + ")";
						break;
					case "call":
						codeHead = "(function() { var args = {}; ";
						codeTail = "return varCall(" + code + ", $ctx, args); })()";
						(function appendArguments() {
							for(var j = 0; j < c.children.length; j++) {
								var item = c.children[j]
								switch(item.name) {
								case "args":
									if(item.children) {
										for(var n = 0; n < item.children.length; n++) {
											var a = item.children[n];
											if(a.name === "pair") {
												codeHead += "args[" + compileItem(a.children[0]) + "] = " + compileItem(a.children[1]) + "; "
											} else
												codeHead += "args['" + n + "'] = " + compileItem(a) + "; "
										}
									}
									break
								case "block":
									codeHead += "args['yield'] = " + compileItem(item) + "; "
									break
								}
							}
						})()
						code = codeHead + codeTail;
						break;
					case "filter":
						code = "varCall(" + compileItem(c.children[0])
							+ ", $ctx, [" + code + "])"
						break;
					}
				}
			}
			return code;
		default:
			throw new Error("Unknown token \"" + item.name + "\"")
		}
	}
	var i, items = []
	for(i = 0; i < tree.length; i++)
		items.push(compileItem(tree[i]))
	r.out = "function($ctx) { return " + items.join(" + ") + "; }"
	return r;
}

function counter() {
	var v = 0,
		error = null,
		items = [];
	function callHandlers() {
		for(var i in items)
			items[i](error);
		items = []
	}
	return {
		inc: function() {
			if(!error)
				v++
		},
		dec: function() {
			if (!error) {
				v--
				if(v == 0)
					callHandlers()
			}
		},
		fail: function(e) {
			error = e
			v = 0
			callHandlers()
		},
		wait: function(callback) {
			if(v)
				items.push(callback)
			else
				callback(error)
		}
	}
}

function compiler(loader) {
	var compilerObject,
		plugins = {},
		dependencies = {},
		includes = {},
		error = null,
		cnt = counter();
	if(!loader) {
		loader = fileLoader();
	}
	function loadFile(name, callback) {
		cnt.inc()
		loader(name, function(err, content) {
			if (err) {
				cnt.fail(err)
			} else {
				callback(content)
				cnt.dec()
			}
		})
	}
	function getPluginsCode() {
		var i, out = "",
			pathSet = {};
		function createPath(path) {
			var i, ns, items = path.split(".");
			for(i = 1; i < items.length; i++) {
				ns = items.slice(0, i).join(".")
				if (!pathSet[ns]) {
					out += "$ctx['" + ns.replace(".", "']['") + "'] = {}; "
					pathSet[ns] = true
				}
			}
		}
		for (i in plugins) {
			createPath(i)
			out += "$ctx['" + i.replace(".", "']['") + "'] = " + plugins[i] + "; "
		}
		return out;
	}
	function getIncludesCode() {
		return "var includes = " + JSON.stringify(includes) + "; "
	}
	function getDependenciesCode() {
		var codeHead = "var dependencies = {",
			codeTail = "}; ",
			items = [];
		for(var i in dependencies)
			items.push(JSON.stringify(i) + ": " + dependencies[i])
		return codeHead + items.join(", ") + codeTail;
	}

	compilerObject = {
		loadPlugins: function() {
			(function loadPlugins(nameParts, dir) {
				cnt.inc()
				fs.readdir(dir, function(err, files) {
					if(err)
						cnt.fail(err)
					else {
						for(var i in files) {
							cnt.inc();
							(function() {
								var fullName = path.join(dir, files[i]),
									file = files[i];
								fs.stat(fullName, function(err, stat) {
									if(err)
										cnt.fail(err)
									else {
										cnt.dec()
										if(stat.isDirectory()) {
											loadPlugins(nameParts.concat([file]), fullName)
										} else {
											cnt.inc()
											fs.readFile(fullName, "UTF-8", function(err, data) {
												if(err) {
													cnt.fail(err)
												} else {
													plugins[nameParts.concat([file.replace(/\.js$/i, "")]).join(".")] = data
													cnt.dec()
												}
											});
										}
									}
								});
							})()
						}
						cnt.dec()
					}
				})
			})([], path.join(__dirname, "../plugins"))
		},
		plugin: function(name, fileName) {
			if(!plugins[name]) {
				plugins[name] = true
				loadFile(fileName, function(content) {
					plugins[name] = content
				})
			}
		},
		include: function(fileName) {
			if(!includes[fileName]) {
				includes[fileName] = true
				loadFile(fileName, function(content) {
					includes[fileName] = content
				})
			}
		},
		parse: function(fileName) {
			if(!dependencies[fileName]) {
				dependencies[fileName] = true
				loadFile(fileName, function(content) {
					var i, parsed = parseString(fileName, content);
					dependencies[fileName] = parsed.out
					for(i in parsed.includes) {
						compilerObject.include(parsed.includes[i])
					}
					for(i in parsed.dependencies) {
						compilerObject.parse(parsed.dependencies[i])
					}
				})
			}
		},
		getCode: function(callback) {
			cnt.wait(function(err) {
				if(err)
					callback(err, null);
				else {
					callback(null, "(function (fileName, ctx) { "
						+ "\"use strict\";"
						+ "function context() { if(arguments.length) { var rfn = function(){}; rfn.prototype = arguments[0]; return new rfn(); } else return {}; } "
						+ "function varIndex(v, i) { return v ? v[i] : null; } "
						+ "function varCall(v, ctx, args) { return (v && typeof v=='function') ? v(ctx, args) : \"#not_a_function#\"; } "
						+ "var $ctx = context(ctx); "
						+ getPluginsCode() + getIncludesCode() + getDependenciesCode()
						+ "if(dependencies[fileName]) return dependencies[fileName]($ctx); else throw new Error('File not found: \"' + fileName + '\"'); "
						+ "})");
				}
			});
		},
		getFunction: function(callback) {
			compilerObject.getCode(function(err, code) {
				if(err)
					callback(err, null)
				else
					callback(null, new Function("fileName", "ctx", "return " + code + "(fileName, ctx);"))
			})
		}
	}
	return compilerObject
}

function fileLoader(rootPath) {
	if(!rootPath)
		rootPath = "./"
	else if(!/\/$/.test(rootPath))
		rootPath += "/"
	return function(fileName, callback) {
		fs.readFile(path.join(rootPath, fileName), "UTF-8", callback)
	}
}

exports.fileLoader = fileLoader
exports.compiler = compiler

<|endoftext|>


<commit_before>module.exports = function(config) {
	var configuration = {
		basePath: __dirname + '/..',
		frameworks: ['browserify', 'jasmine'],
		files: [
			'node_modules/angular/angular.js',
			'node_modules/angular-mocks/angular-mocks.js',
			'bower_components/br-validations/releases/br-validations.js',
			'config/test-utils.js',
			'src/**/*.test.js',
		],
		port: 9876,
		reporters: ['progress', 'coverage'],
		preprocessors: {
			'src/**/*.test.js': [ 'browserify' ],
			'src/**/*!(test|spec).js': ['coverage']
		},
		browserify: {
			debug: true,
			transform: [require('browserify-istanbul')({
				ignore: '*.test.js'
			})]
		},
		coverageReporter: {
			dir: 'coverage',
			reporters: [{
				type: 'lcov',
				subdir: 'report-lcov'
			}, {
				type: 'html',
				subdir: 'report-html'
			}, {
				type: 'text',
			}, {
				type: 'text-summary',
			}]
		},
		colors: true,
		autoWatch: false,
		singleRun: false,
		browsers: ['Chrome'],
		customLaunchers: {
			Chrome_travis_ci: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},
	};

	if(process.env.TRAVIS){
		configuration.browsers = ['Chrome_travis_ci'];

		configuration.reporters.push('coveralls');
	}

	config.set(configuration);
};
<commit_msg>chore(coverage): exclude test files from coverage report<commit_after>module.exports = function(config) {
	var configuration = {
		basePath: __dirname + '/..',
		frameworks: ['browserify', 'jasmine'],
		files: [
			'node_modules/angular/angular.js',
			'node_modules/angular-mocks/angular-mocks.js',
			'bower_components/br-validations/releases/br-validations.js',
			'config/test-utils.js',
			'src/**/*.test.js',
		],
		port: 9876,
		reporters: ['progress', 'coverage'],
		preprocessors: {
			'src/**/*.test.js': [ 'browserify' ],
			'src/**/!(*test).js': ['coverage']
		},
		browserify: {
			debug: true,
			transform: [require('browserify-istanbul')({
				ignore: '**/*.test.js'
			})]
		},
		coverageReporter: {
			dir: 'coverage',
			reporters: [{
				type: 'lcov',
				subdir: 'report-lcov'
			}, {
				type: 'html',
				subdir: 'report-html'
			}, {
				type: 'text',
			}, {
				type: 'text-summary',
			}]
		},
		colors: true,
		autoWatch: false,
		singleRun: false,
		browsers: ['Chrome'],
		customLaunchers: {
			Chrome_travis_ci: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},
	};

	if(process.env.TRAVIS){
		configuration.browsers = ['Chrome_travis_ci'];

		configuration.reporters.push('coveralls');
	}

	config.set(configuration);
};
<|endoftext|>


<commit_before>var env       = process.env.NODE_ENV || 'development';
var CONSTANT = require(__dirname + '/../config/config.json')[env];
var nodemailer = require('nodemailer');

var transport = nodemailer.createTransport({
  service: 'Gmail',
  auth: {
    user: CONSTANT.emailUsername,
    pass: CONSTANT.emailPassword
  }
});

function sendWelcomeEmail(email, username) {
  var mailOptions = {
    to: email,
    subject: "Welcome to Football Pools",
    text: 'Welcome ' + username + ' to football pools!'
  };

  sendMail(mailOptions);

}

function sendUpdateEmail(email) {
  var mailOptions = {
    to: email,
    subject: "Football Pools Profile Update",
    text: 'This is an email from Football Pool to let you know that you have updated your account information.'
  };

  sendMail(mailOptions);
}

function sendAdminEmail(username, email) {
  var mailOptions = {
    to: email,
    subject: "Football Pool Admin",
    text: 'Congrats ' + username +"! You have been added as an admin to Football Pool. You should be able to see tha admin veiw on your page soon!"
  };

  sendMail(mailOptions);
}

function sendMail(mailOptions) {
  transport.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    console.log('Message sent: ' + info.response);
  });
}

function sendEveryoneEmail(mailOptions) {
  sendMail(mailOptions);
}

module.exports = {
  sendWelcomeEmail: sendWelcomeEmail,
  sendUpdateEmail: sendUpdateEmail,
  sendAdminEmail: sendAdminEmail,
  sendEveryoneEmail: sendEveryoneEmail
};
<commit_msg>adding code to see if I can get output?<commit_after>var env       = process.env.NODE_ENV || 'development';
console.log("I am the env ", env);
var CONSTANT = require(__dirname + '/../config/config.json')[env];
var nodemailer = require('nodemailer');

var transport = nodemailer.createTransport({
  service: 'Gmail',
  auth: {
    user: CONSTANT.emailUsername,
    pass: CONSTANT.emailPassword
  }
});

function sendWelcomeEmail(email, username) {
  var mailOptions = {
    to: email,
    subject: "Welcome to Football Pools",
    text: 'Welcome ' + username + ' to football pools!'
  };

  sendMail(mailOptions);

}

function sendUpdateEmail(email) {
  var mailOptions = {
    to: email,
    subject: "Football Pools Profile Update",
    text: 'This is an email from Football Pool to let you know that you have updated your account information.'
  };

  sendMail(mailOptions);
}

function sendAdminEmail(username, email) {
  var mailOptions = {
    to: email,
    subject: "Football Pool Admin",
    text: 'Congrats ' + username +"! You have been added as an admin to Football Pool. You should be able to see tha admin veiw on your page soon!"
  };

  sendMail(mailOptions);
}

function sendMail(mailOptions) {
  transport.sendMail(mailOptions, function(error, info){
    if(error){
      return console.log(error);
    }
    console.log('Message sent: ' + info.response);
  });
}

function sendEveryoneEmail(mailOptions) {
  sendMail(mailOptions);
}

module.exports = {
  sendWelcomeEmail: sendWelcomeEmail,
  sendUpdateEmail: sendUpdateEmail,
  sendAdminEmail: sendAdminEmail,
  sendEveryoneEmail: sendEveryoneEmail
};
<|endoftext|>