<commit_before>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? yes or no:");
        if (system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }
        OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.message)
    {
        print(options.message)
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.1.2");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.2.1", {
    noupdate : true,
    message : "Update Narwhal to 0.2.1 by running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.1.1", {
    optional : true,
    message : "Rebuild narwhal-jsc by changing to the narwhal-jsc package directory and running \"make webkit\"."
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_DIR, $CONFIGURATION, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

function serializedENV()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length)
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + p; }).join(" ");

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function throwIfNotRequireError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment: " + e);
        throw e;
    }
}

function setupEnvironment()
{
    // TODO: deprecate these globals
    try {
        var OBJECTIVE_J_JAKE = require("objective-j/jake");

        global.app = OBJECTIVE_J_JAKE.app;
        global.bundle = OBJECTIVE_J_JAKE.bundle;
        global.framework = OBJECTIVE_J_JAKE.framework;

        global.BundleTask = OBJECTIVE_J_JAKE.BundleTask;
    } catch (e) {
        throwIfNotRequireError(e);
    }

    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        throwIfNotRequireError(e);
    }

    try {
        var CAPPUCCINO_JAKE = require("cappuccino/jake");
        if (CAPPUCCINO_JAKE.blend)
            global.blend = CAPPUCCINO_JAKE.blend;
        //else
        //    print("no blend!")
    }
    catch (e) {
        throwIfNotRequireError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var returnCode = OS.system("cd " + aDirectory + " && " + serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ aFileName)
{
    return SYSTEM.env["PATH"].split(':').some(function(/*String*/ aPath)
    {
        return FILE.exists(FILE.join(aPath, aFileName));
    });
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<commit_msg>Only log errors in setupEnvironment.<commit_after>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? yes or no:");
        if (system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }
        OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.message)
    {
        print(options.message)
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.1.2");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.2.1", {
    noupdate : true,
    message : "Update Narwhal to 0.2.1 by running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.1.1", {
    optional : true,
    message : "Rebuild narwhal-jsc by changing to the narwhal-jsc package directory and running \"make webkit\"."
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_DIR, $CONFIGURATION, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

function serializedENV()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length)
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + p; }).join(" ");

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function handleSetupEnvironmentError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment: " + e);
        //throw e;
    }
}

function setupEnvironment()
{
    // TODO: deprecate these globals
    try {
        var OBJECTIVE_J_JAKE = require("objective-j/jake");

        global.app = OBJECTIVE_J_JAKE.app;
        global.bundle = OBJECTIVE_J_JAKE.bundle;
        global.framework = OBJECTIVE_J_JAKE.framework;

        global.BundleTask = OBJECTIVE_J_JAKE.BundleTask;
    } catch (e) {
        handleSetupEnvironmentError(e);
    }

    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        handleSetupEnvironmentError(e);
    }

    try {
        var CAPPUCCINO_JAKE = require("cappuccino/jake");
        if (CAPPUCCINO_JAKE.blend)
            global.blend = CAPPUCCINO_JAKE.blend;
        //else
        //    print("no blend!")
    }
    catch (e) {
        handleSetupEnvironmentError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var returnCode = OS.system("cd " + aDirectory + " && " + serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ aFileName)
{
    return SYSTEM.env["PATH"].split(':').some(function(/*String*/ aPath)
    {
        return FILE.exists(FILE.join(aPath, aFileName));
    });
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
var subcommand = require('subcommand')
var encoding = require('dat-encoding')
var debug = require('debug')('dat')
var usage = require('../src/usage')

process.title = 'dat'

// Check node version to make sure we support
var NODE_VERSION_SUPPORTED = 4
var nodeMajorVer = process.version.match(/^v([0-9]+)\./)[1]
var invalidNode = nodeMajorVer < NODE_VERSION_SUPPORTED
if (invalidNode) exitInvalidNode()

var isDebug = debug.enabled || !!process.env.DEBUG

var config = {
  defaults: [
    { name: 'dir', abbr: 'd', help: 'set the directory for Dat' },
    { name: 'logspeed', default: 400 },
    { name: 'port', default: 3282, help: 'port to use for connections' },
    { name: 'utp', default: true, boolean: true, help: 'use utp for discovery' },
    { name: 'quiet', default: isDebug, boolean: true }, // neat-log uses quiet for debug right now
  ],
  root: {
    options: [
      {
        name: 'version',
        boolean: true,
        default: false,
        abbr: 'v'
      }
    ],
    command: usage
  },
  none: syncShorthand,
  commands: [
    require('../src/commands/clone'),
    require('../src/commands/create'),
    require('../src/commands/doctor'),
    require('../src/commands/publish'),
    require('../src/commands/pull'),
    require('../src/commands/share'),
    require('../src/commands/status'),
    require('../src/commands/sync'),
    require('../src/commands/auth/register'),
    require('../src/commands/auth/whoami'),
    require('../src/commands/auth/logout'),
    require('../src/commands/auth/login')
  ],
  usage: {
    command: usage,
    option: {
      name: 'help',
      abbr: 'h'
    }
  },
  aliases: {
    'init': 'create'
  }
}

var match = subcommand(config)
match(alias(process.argv.slice(2)))

function alias (argv) {
  var cmd = argv[0]
  if (!config.aliases[cmd]) return argv
  argv[0] = config.aliases[cmd]
  return argv
}

function syncShorthand (opts) {
  if (!opts._.length) return usage(opts)
  debug('Sync shortcut command')

  // Check if first argument is a key, if not assume dir
  try {
    opts.key = encoding.toStr(opts._[0])
  } catch (err) {
    if (err && err.message !== 'Invalid key') {
      // catch non-key errors
      console.error(err)
      process.exit(1)
    }
  }

  if (opts._.length > 1 || opts.key) {
    // dat <link> [dir] - clone/resume <link> in [dir]
    debug('Clone sync')
    opts.dir = opts._[1] || process.cwd()
    opts.exit = false
    require('../src/commands/clone').command(opts)
  } else {
    // dat {dir} - sync existing dat in {dir}
    debug('Share sync')
    opts.dir = opts._[0]
    fs.stat(opts.dir, function (err, stat) {
      if (err || !stat.isDirectory()) return usage(opts)

      // Set default opts. TODO: use default opts in sync
      opts.watch = opts.watch || true
      opts.import = opts.import || true
      require('../src/commands/sync').command(opts)
    })
  }
}

function exitInvalidNode () {
  console.error('Node Version:', process.version)
  console.error('Unfortunately, we only support Node >= v4. Please upgrade to use Dat.')
  console.error('You can find the latest version at https://nodejs.org/')
  process.exit(1)
}
<commit_msg>standard<commit_after>#!/usr/bin/env node

var fs = require('fs')
var subcommand = require('subcommand')
var encoding = require('dat-encoding')
var debug = require('debug')('dat')
var usage = require('../src/usage')

process.title = 'dat'

// Check node version to make sure we support
var NODE_VERSION_SUPPORTED = 4
var nodeMajorVer = process.version.match(/^v([0-9]+)\./)[1]
var invalidNode = nodeMajorVer < NODE_VERSION_SUPPORTED
if (invalidNode) exitInvalidNode()

var isDebug = debug.enabled || !!process.env.DEBUG

var config = {
  defaults: [
    { name: 'dir', abbr: 'd', help: 'set the directory for Dat' },
    { name: 'logspeed', default: 400 },
    { name: 'port', default: 3282, help: 'port to use for connections' },
    { name: 'utp', default: true, boolean: true, help: 'use utp for discovery' },
    { name: 'quiet', default: isDebug, boolean: true } // neat-log uses quiet for debug right now
  ],
  root: {
    options: [
      {
        name: 'version',
        boolean: true,
        default: false,
        abbr: 'v'
      }
    ],
    command: usage
  },
  none: syncShorthand,
  commands: [
    require('../src/commands/clone'),
    require('../src/commands/create'),
    require('../src/commands/doctor'),
    require('../src/commands/publish'),
    require('../src/commands/pull'),
    require('../src/commands/share'),
    require('../src/commands/status'),
    require('../src/commands/sync'),
    require('../src/commands/auth/register'),
    require('../src/commands/auth/whoami'),
    require('../src/commands/auth/logout'),
    require('../src/commands/auth/login')
  ],
  usage: {
    command: usage,
    option: {
      name: 'help',
      abbr: 'h'
    }
  },
  aliases: {
    'init': 'create'
  }
}

var match = subcommand(config)
match(alias(process.argv.slice(2)))

function alias (argv) {
  var cmd = argv[0]
  if (!config.aliases[cmd]) return argv
  argv[0] = config.aliases[cmd]
  return argv
}

function syncShorthand (opts) {
  if (!opts._.length) return usage(opts)
  debug('Sync shortcut command')

  // Check if first argument is a key, if not assume dir
  try {
    opts.key = encoding.toStr(opts._[0])
  } catch (err) {
    if (err && err.message !== 'Invalid key') {
      // catch non-key errors
      console.error(err)
      process.exit(1)
    }
  }

  if (opts._.length > 1 || opts.key) {
    // dat <link> [dir] - clone/resume <link> in [dir]
    debug('Clone sync')
    opts.dir = opts._[1] || process.cwd()
    opts.exit = false
    require('../src/commands/clone').command(opts)
  } else {
    // dat {dir} - sync existing dat in {dir}
    debug('Share sync')
    opts.dir = opts._[0]
    fs.stat(opts.dir, function (err, stat) {
      if (err || !stat.isDirectory()) return usage(opts)

      // Set default opts. TODO: use default opts in sync
      opts.watch = opts.watch || true
      opts.import = opts.import || true
      require('../src/commands/sync').command(opts)
    })
  }
}

function exitInvalidNode () {
  console.error('Node Version:', process.version)
  console.error('Unfortunately, we only support Node >= v4. Please upgrade to use Dat.')
  console.error('You can find the latest version at https://nodejs.org/')
  process.exit(1)
}
<|endoftext|>


<commit_before>// read lib dependencies
//   -- from comments in the source?
//   -- or an external file?
// grab the addresses and ABIs of lib dependencies
// generate abstract libs from ABIs
// compile the source code
// link the binaries<commit_msg>parsing live-lib 'imports' and grabbing address/abi data<commit_after>var liveLibsContract = require('./lib/live-libs');

var fs = require('fs');

function parseLiveLibData(source) {
  var libData = {};

  // read lib dependencies from comments in the source
  var matchData = /\/\/\s*live\-libs\:\s*(.*)\s*/.exec(source);

  if (matchData) {
    var liveLibsString = matchData[1];
    var liveLibsNames = liveLibsString.split(/[ ,]+/);

    liveLibsNames.forEach(function(liveLibsName) {
      // grab the addresses and ABIs of lib dependencies
      var data = liveLibsContract().data(liveLibsName);
      var address = data[0];
      var abi = data[1];
      if (address == '0x0000000000000000000000000000000000000000') {
        console.error('There is no live-lib registered as "'+liveLibsName+'"');
        process.exit(1);
      }
      libData[liveLibsName] = {address: address, abi: abi};
    });
  }
  return libData;
}

var solFile = process.argv[2];
var source = fs.readFileSync(solFile, 'utf8');

var libData = parseLiveLibData(source);
console.log(libData);
// generate abstract libs from ABIs
// compile the source code
// link the binaries<|endoftext|>


<commit_before>"use strict";
/**
 * XCSS compiler
 */

var BaseCompiler      = require('css-stringify/lib/compiler');
var recast            = require('recast');
var util              = require('util');
var toCamelCase       = require('to-camel-case');
var flatMap           = require('flatmap');
var parse             = require('./parser');
var utils             = require('./utils');
var compileExpression = require('./expression-compiler');

var b = recast.types.builders;

function Compiler(options) {
  options = options || {};
  BaseCompiler.call(this, options);
  this.visit = this.visit.bind(this);

  this.options.xcssModulePath = this.options.xcssModulePath || 'xcss';

  this.moduleParameters = null;
  this.localDeclarations = [makeDeclaration('vars', b.objectExpression([]))];
  this.globalDeclarations = [makeRequire('xcss', this.options.xcssModulePath)];
  this.scope = {};
  this.counter = 0;
}
util.inherits(Compiler, BaseCompiler);

Compiler.prototype.uniqueName = function(prefix) {
  return prefix + '$' + (this.counter++);
}

Compiler.prototype.compile = function(node){
  var stylesheet = this.stylesheet(node);

  if (this.moduleParameters) {

    stylesheet = makeModule(
      this.moduleParameters,
      this.localDeclarations.concat(b.returnStatement(stylesheet)));

    return utils.print(this.globalDeclarations) + '\n\n' +
      'module.exports = ' +
      utils.print(stylesheet);

  } else {

    return utils.print(this.globalDeclarations) + '\n' +
      utils.print(this.localDeclarations) + '\n\n' +
      'module.exports = ' +
      utils.print(stylesheet);
  }
};

/**
 * Compile stylesheet.
 */
Compiler.prototype.stylesheet = function(node){
  var rules = node.stylesheet.rules.map(this.visit).filter(Boolean);

  return b.callExpression(
    b.identifier('xcss.om.stylesheet'),
    [b.identifier('vars')].concat(rules));
};

/**
 * Compile comment.
 */
Compiler.prototype.comment = function(node) {
  // TODO: emit comments as well
  return false;
};

/**
 * Compile @require.
 */
Compiler.prototype.require = function(node) {
  this.globalDeclarations.push(makeRequire(node.id, node.path));
  this.scope[node.id] = true;
  return false;
};

/**
 * Compile @module.
 */
Compiler.prototype.module = function(node){
  this.moduleParameters = node.module.split(',').map(function(a) { return a.trim() });
  return false;
}

/**
 * Compile CSS rule.
 */
Compiler.prototype.rule = function(node){
  var declarations = node.declarations;

  // probably a call in rule position
  if (node.selectors.length === 1 && node.selectors[0].indexOf(' ') === -1) {
    var name = toCamelCase(node.selectors[0]);
    if (this.scope[utils.getIdentifier(name)]) {
      return b.callExpression(
        b.identifier(name),
        declarations.map(this.visit));
    } else if (name === ':root') {
      declarations = declarations.filter(function(decl) {
        if (/^var\-/.exec(decl.property)) {
          this.localDeclarations.push(makeVar(decl.property.slice(4), decl.value));
          return false;
        }
        return true;
      }, this);
    }
  }

  var selectors = node.selectors.map(b.literal);
  return b.callExpression(
    b.identifier('xcss.om.rule'),
    selectors.concat(declarations.map(this.visit)));
};

/**
 * Compile CSS declaration.
 */
Compiler.prototype.declaration = function(node) {
  var name = toCamelCase(node.property);
  var value = compileExpression(node.value, this.scope);
  var identifier = utils.getIdentifier(name);

  if (this.scope[identifier]) {
    return b.callExpression(
      b.identifier(name),
      [value]);
  } else if (identifier === 'extend') {
    return b.callExpression(
      b.identifier('xcss.om.extend'),
      [value]);
  } else {
    return b.objectExpression([
      b.property(
        'init',
        b.literal(node.property),
        value)]);
  }
};

/**
 * Compile @import
 */
Compiler.prototype.import = function(node) {
  var m = /^"([^"]+)"( +with +(.+))?/.exec(node.import);
  var value = m[1];
  var args = m[3];

  var ast = b.callExpression(
    b.identifier('require'),
    [b.literal(value)]);

  if (args) {
    args = '(' + args + ')';
    args = utils.parseExpression(args);
    args = args.expressions ? args.expressions : [args];
    ast = b.callExpression(ast, args);
  }

  var name = this.uniqueName('import');

  this.localDeclarations.push(makeDeclaration(name, ast));
  this.localDeclarations.push(makeVarMerge([name]));

  return b.callExpression(
    b.identifier('xcss.om.import'),
    [b.identifier(name)]);
};

// xcss.om.module(function($params ...) { $stmts ... })
function makeModule(params, stmts) {
  stmts.splice(1, 0, makeVarMerge(params));
  params = params.map(b.identifier);
  var factory = b.functionExpression(null, params, b.blockStatement(stmts));
  return b.callExpression(b.identifier('xcss.om.module'), [factory]);
}

// var $id = require($path)
function makeRequire(id, path) {
  var expr = b.callExpression(b.identifier('require'), [b.literal(path)]);
  return makeDeclaration(id, expr);
}

// vars.$id = $value
function makeVar(id, value) {
  return b.assignmentExpression('=',
    b.memberExpression(b.identifier('vars'), b.literal(id), true),
    b.literal(value));
}

// xcss.runtime.merge(vars, $name.vars)
function makeVarMerge(names) {
  names = names.map(function(name) {
    return b.memberExpression(b.identifier(name), b.identifier('vars'), false);
  });
  var expr = b.callExpression(
    b.identifier('xcss.runtime.merge'),
    [b.identifier('vars')].concat(names));
  return b.expressionStatement(expr);
}

// var $id = $value
function makeDeclaration(id, expr) {
  return b.variableDeclaration('var', [b.variableDeclarator(b.identifier(id), expr)]);
}

module.exports = function(src, options) {
  var stylesheet = parse(src);
  return new Compiler(options).compile(stylesheet);
}
<commit_msg>Compile var expressions<commit_after>"use strict";
/**
 * XCSS compiler
 */

var BaseCompiler      = require('css-stringify/lib/compiler');
var recast            = require('recast');
var util              = require('util');
var toCamelCase       = require('to-camel-case');
var flatMap           = require('flatmap');
var parse             = require('./parser');
var utils             = require('./utils');
var compileExpression = require('./expression-compiler');

var b = recast.types.builders;

function Compiler(options) {
  options = options || {};
  BaseCompiler.call(this, options);
  this.visit = this.visit.bind(this);

  this.options.xcssModulePath = this.options.xcssModulePath || 'xcss';

  this.moduleParameters = null;
  this.localDeclarations = [makeDeclaration('vars', b.objectExpression([]))];
  this.globalDeclarations = [makeRequire('xcss', this.options.xcssModulePath)];
  this.scope = {};
  this.counter = 0;
}
util.inherits(Compiler, BaseCompiler);

Compiler.prototype.uniqueName = function(prefix) {
  return prefix + '$' + (this.counter++);
}

Compiler.prototype.compile = function(node){
  var stylesheet = this.stylesheet(node);

  if (this.moduleParameters) {

    stylesheet = makeModule(
      this.moduleParameters,
      this.localDeclarations.concat(b.returnStatement(stylesheet)));

    return utils.print(this.globalDeclarations) + '\n\n' +
      'module.exports = ' +
      utils.print(stylesheet);

  } else {

    return utils.print(this.globalDeclarations) + '\n' +
      utils.print(this.localDeclarations) + '\n\n' +
      'module.exports = ' +
      utils.print(stylesheet);
  }
};

/**
 * Compile stylesheet.
 */
Compiler.prototype.stylesheet = function(node){
  var rules = node.stylesheet.rules.map(this.visit).filter(Boolean);

  return b.callExpression(
    b.identifier('xcss.om.stylesheet'),
    [b.identifier('vars')].concat(rules));
};

/**
 * Compile comment.
 */
Compiler.prototype.comment = function(node) {
  // TODO: emit comments as well
  return false;
};

/**
 * Compile @require.
 */
Compiler.prototype.require = function(node) {
  this.globalDeclarations.push(makeRequire(node.id, node.path));
  this.scope[node.id] = true;
  return false;
};

/**
 * Compile @module.
 */
Compiler.prototype.module = function(node){
  this.moduleParameters = node.module.split(',').map(function(a) { return a.trim() });
  return false;
}

/**
 * Compile CSS rule.
 */
Compiler.prototype.rule = function(node){
  var declarations = node.declarations;

  // probably a call in rule position
  if (node.selectors.length === 1 && node.selectors[0].indexOf(' ') === -1) {
    var name = toCamelCase(node.selectors[0]);
    if (this.scope[utils.getIdentifier(name)]) {
      return b.callExpression(
        b.identifier(name),
        declarations.map(this.visit));
    } else if (name === ':root') {
      declarations = declarations.filter(function(decl) {
        if (/^var\-/.exec(decl.property)) {
          this.localDeclarations.push(makeVar(
            decl.property.slice(4),
            compileExpression(decl.value, this.scope)));
          return false;
        }
        return true;
      }, this);
    }
  }

  var selectors = node.selectors.map(b.literal);
  return b.callExpression(
    b.identifier('xcss.om.rule'),
    selectors.concat(declarations.map(this.visit)));
};

/**
 * Compile CSS declaration.
 */
Compiler.prototype.declaration = function(node) {
  var name = toCamelCase(node.property);
  var value = compileExpression(node.value, this.scope);
  var identifier = utils.getIdentifier(name);

  if (this.scope[identifier]) {
    return b.callExpression(
      b.identifier(name),
      [value]);
  } else if (identifier === 'extend') {
    return b.callExpression(
      b.identifier('xcss.om.extend'),
      [value]);
  } else {
    return b.objectExpression([
      b.property(
        'init',
        b.literal(node.property),
        value)]);
  }
};

/**
 * Compile @import
 */
Compiler.prototype.import = function(node) {
  var m = /^"([^"]+)"( +with +(.+))?/.exec(node.import);
  var value = m[1];
  var args = m[3];

  var ast = b.callExpression(
    b.identifier('require'),
    [b.literal(value)]);

  if (args) {
    args = '(' + args + ')';
    args = utils.parseExpression(args);
    args = args.expressions ? args.expressions : [args];
    ast = b.callExpression(ast, args);
  }

  var name = this.uniqueName('import');

  this.localDeclarations.push(makeDeclaration(name, ast));
  this.localDeclarations.push(makeVarMerge([name]));

  return b.callExpression(
    b.identifier('xcss.om.import'),
    [b.identifier(name)]);
};

// xcss.om.module(function($params ...) { $stmts ... })
function makeModule(params, stmts) {
  stmts.splice(1, 0, makeVarMerge(params));
  params = params.map(b.identifier);
  var factory = b.functionExpression(null, params, b.blockStatement(stmts));
  return b.callExpression(b.identifier('xcss.om.module'), [factory]);
}

// var $id = require($path)
function makeRequire(id, path) {
  var expr = b.callExpression(b.identifier('require'), [b.literal(path)]);
  return makeDeclaration(id, expr);
}

// vars.$id = $value
function makeVar(id, expr) {
  return b.assignmentExpression('=',
    b.memberExpression(b.identifier('vars'), b.literal(id), true),
    expr);
}

// xcss.runtime.merge(vars, $name.vars)
function makeVarMerge(names) {
  names = names.map(function(name) {
    return b.memberExpression(b.identifier(name), b.identifier('vars'), false);
  });
  var expr = b.callExpression(
    b.identifier('xcss.runtime.merge'),
    [b.identifier('vars')].concat(names));
  return b.expressionStatement(expr);
}

// var $id = $value
function makeDeclaration(id, expr) {
  return b.variableDeclaration('var', [b.variableDeclarator(b.identifier(id), expr)]);
}

module.exports = function(src, options) {
  var stylesheet = parse(src);
  return new Compiler(options).compile(stylesheet);
}
<|endoftext|>


<commit_before>/**
 * https://github.com/Aequiternus/node-jsin
 * v 0.1.5
 *
 * Copyright © 2014 Maksim Krylosov <Aequiternus@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var compiled = {};
var directory = '';

exports.compile = compile;
exports.compiled = compiled;
exports.setDirectory = setDirectory;

var fs = require('fs');

function setDirectory(dir) {
    directory = dir;
}

function compile(template, callback) {
    template = template.replace(/\.jsin$/, '');

    if (compiled[template]) {
        callback();
    } else {
        var templatePath = template + '.jsin';
        if (directory) {
            templatePath = directory + '/' + templatePath;
        }
        fs.readFile(templatePath, function(err, res) {
            try {
                if (err) throw err;
                compiled[template] = compileCode(res.toString());
                callback();
            } catch (err) {
                compiled[template] = err;
                callback(err);
            }
        });
    }
}

function compileCode(tpl) {
    var p,
        code = [];

    code.push("with(this){with(__data){\n");

    while (-1 !== (p = tpl.indexOf('<?'))) {
        if ('=' === tpl[p + 2]) {
            addOutput(code, tpl.substr(0, p));
            code.push("print(");
            tpl = closeTag(code, tpl.substr(p + 3));
            code.push(");\n");
        } else if ('js' === tpl.substr(p + 2, 2)) {
            addOutput(code, tpl.substr(0, p).replace(/ *$/, '')); // eat leading space
            tpl = closeTag(code, tpl.substr(p + 4), true);
            code.push(";\n");
        } else {
            addOutput(code, tpl.substr(0, p + 2));
            tpl = tpl.substr(p + 2);
        }
    }
    if (tpl) {
        addOutput(code, tpl);
    }
    code.push("}}");

//    console.log(code.join(''));
    return new Function(code.join(''));
}

function addOutput(code, string) {
    if ('' !== string) {
        code.push(
            "print(\""
            + string
                .replace(/\\/g, '\\\\')
                .replace(/\n/g, '\\n')
                .replace(/\r/g, '\\r')
                .replace(/"/g, '\\"')
            + "\");\n"
        );
    }
}

function closeTag(code, tpl, eatNewLine) {
    var p;

    while (-1 !== (p = tpl.search(/('|"|\?\>)/))) {
        code.push(tpl.substr(0, p).trim());
        var q = tpl[p];
        tpl = tpl.substr(p + 1);
        if (
            "'" === q ||
            '"' === q
        ) {
            code.push(q);
            while (-1 !== (p = tpl.indexOf(q))) {
                code.push(tpl.substr(0, p + 1).trim());
                var s = tpl[p - 1];
                tpl = tpl.substr(p + 1);
                if ('\\' !== s) {
                    break;
                }
            }
            if (-1 === p) {
                throw new Error(
                    'Syntax error, unexpected end, closing quote not found near "'
                    + tpl.substr(0, 20) + '"'
                );
            }
        } else {
            if (eatNewLine && "\n" === tpl[1]) {
                tpl = tpl.substr(2);
            } else {
                tpl = tpl.substr(1);
            }
            break;
        }
    }
    if (-1 === p) {
        code.push(tpl.trim());
        tpl = '';
    }

    return tpl;
}
<commit_msg>ignore directory if path starts from / or ./<commit_after>/**
 * https://github.com/Aequiternus/node-jsin
 * v 0.1.5
 *
 * Copyright © 2014 Maksim Krylosov <Aequiternus@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var compiled = {};
var directory = '';

exports.compile = compile;
exports.compiled = compiled;
exports.setDirectory = setDirectory;

var fs = require('fs');

function setDirectory(dir) {
    directory = dir;
}

function compile(template, callback) {
    template = template.replace(/\.jsin$/, '');

    if (compiled[template]) {
        callback();
    } else {
        var templatePath = template + '.jsin';
        if (directory && !template.match(/^\.?\//)) {
            templatePath = directory + '/' + templatePath;
        }
        fs.readFile(templatePath, function(err, res) {
            try {
                if (err) throw err;
                compiled[template] = compileCode(res.toString());
                callback();
            } catch (err) {
                compiled[template] = err;
                callback(err);
            }
        });
    }
}

function compileCode(tpl) {
    var p,
        code = [];

    code.push("with(this){with(__data){\n");

    while (-1 !== (p = tpl.indexOf('<?'))) {
        if ('=' === tpl[p + 2]) {
            addOutput(code, tpl.substr(0, p));
            code.push("print(");
            tpl = closeTag(code, tpl.substr(p + 3));
            code.push(");\n");
        } else if ('js' === tpl.substr(p + 2, 2)) {
            addOutput(code, tpl.substr(0, p).replace(/ *$/, '')); // eat leading space
            tpl = closeTag(code, tpl.substr(p + 4), true);
            code.push(";\n");
        } else {
            addOutput(code, tpl.substr(0, p + 2));
            tpl = tpl.substr(p + 2);
        }
    }
    if (tpl) {
        addOutput(code, tpl);
    }
    code.push("}}");

//    console.log(code.join(''));
    return new Function(code.join(''));
}

function addOutput(code, string) {
    if ('' !== string) {
        code.push(
            "print(\""
            + string
                .replace(/\\/g, '\\\\')
                .replace(/\n/g, '\\n')
                .replace(/\r/g, '\\r')
                .replace(/"/g, '\\"')
            + "\");\n"
        );
    }
}

function closeTag(code, tpl, eatNewLine) {
    var p;

    while (-1 !== (p = tpl.search(/('|"|\?\>)/))) {
        code.push(tpl.substr(0, p).trim());
        var q = tpl[p];
        tpl = tpl.substr(p + 1);
        if (
            "'" === q ||
            '"' === q
        ) {
            code.push(q);
            while (-1 !== (p = tpl.indexOf(q))) {
                code.push(tpl.substr(0, p + 1).trim());
                var s = tpl[p - 1];
                tpl = tpl.substr(p + 1);
                if ('\\' !== s) {
                    break;
                }
            }
            if (-1 === p) {
                throw new Error(
                    'Syntax error, unexpected end, closing quote not found near "'
                    + tpl.substr(0, 20) + '"'
                );
            }
        } else {
            if (eatNewLine && "\n" === tpl[1]) {
                tpl = tpl.substr(2);
            } else {
                tpl = tpl.substr(1);
            }
            break;
        }
    }
    if (-1 === p) {
        code.push(tpl.trim());
        tpl = '';
    }

    return tpl;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var minimist = require('minimist')
var standard = require('../')

var argv = minimist(process.argv.slice(2), {
  alias: {
    help: 'h',
    verbose: 'v'
  boolean: [
    'help',
    'stdin',
    'verbose',
    'version'
  ],
  default: {
    stdin: !process.stdin.isTTY
  }
})

if (argv.help) {
  console.log(function () {
  /*
  Usage:
      standard <flags>

  Flags:
      -v, --verbose    Show error codes (so you can ignore specific rules)
          --stdin      Force processing input from stdin
          --version    Display the current version
      -h, --help       Display the help and usage details

  Report bugs:  https://github.com/feross/standard/issues

  */
  }.toString().split(/\n/).slice(2, -2).join('\n'))
  process.exit(0)
}

if (argv.version) {
  console.log(require('../package.json').version)
  process.exit(0)
}

standard({
  cwd: process.cwd(),
  files: argv._,
  stdin: argv.stdin,
  verbose: argv.verbose
})
<commit_msg>syntax<commit_after>#!/usr/bin/env node

var minimist = require('minimist')
var standard = require('../')

var argv = minimist(process.argv.slice(2), {
  alias: {
    help: 'h',
    verbose: 'v'
  },
  boolean: [
    'help',
    'stdin',
    'verbose',
    'version'
  ],
  default: {
    stdin: !process.stdin.isTTY
  }
})

if (argv.help) {
  console.log(function () {
  /*
  Usage:
      standard <flags>

  Flags:
      -v, --verbose    Show error codes (so you can ignore specific rules)
          --stdin      Force processing input from stdin
          --version    Display the current version
      -h, --help       Display the help and usage details

  Report bugs:  https://github.com/feross/standard/issues

  */
  }.toString().split(/\n/).slice(2, -2).join('\n'))
  process.exit(0)
}

if (argv.version) {
  console.log(require('../package.json').version)
  process.exit(0)
}

standard({
  cwd: process.cwd(),
  files: argv._,
  stdin: argv.stdin,
  verbose: argv.verbose
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var clivas = require('clivas')
var cp = require('child_process')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var path = require('path')
var prettysize = require('prettysize')
var WebTorrent = require('../')

process.title = 'WebTorrent'

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    i: 'index',
    n: 'no-quit',
    r: 'remove',
    o: 'out',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'vlc',
    'mplayer',
    'mpv',
    'airplay',
    'chromecast',
    'xbmc',
    'list',
    'no-quit',
    'remove',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 9000
  }
})

if (argv.version) {
  console.log(require('../package.json').version)
  process.exit(0)
}

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*
  Usage:
      webtorrent <options> <torrent>

      Download the torrent, given as:
          * magnet uri
          * http url to .torrent file
          * filesystem path to .torrent file
          * info hash (hex string)

  Streaming options:
      --airplay               stream to Apple TV (AirPlay)
      --chromecast            stream to Chromecast
      --mplayer               stream to MPlayer
      --mpv                   stream to MPV
      --omx [jack]            stream to omx (jack=local|hdmi)
      --vlc                   stream to VLC
      --xbmc                  stream to XBMC

  Options:
      -p, --port [number]     change the http port [default: 9000]
      -b, --blocklist [path]  use the specified blocklist
      -t, --subtitles [file]  load subtitles file
      -l, --list              list available files in torrent (with indexes)
      -i, --index             stream a particular file from torrnet (by index)
      -n, --no-quit           do not quit webtorrent on vlc exit
      -r, --remove            remove downloaded files on exit
      -o, --out [path]        overrides the default tmp directory
      -q, --quiet             silence stdout
      -h, --help              display this help message
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  process.exit(0)
}

if (process.env.DEBUG) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  blocklist: argv.blocklist
})
.on('error', errorAndExit)

if (argv.remove) {
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove (cb) {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)
  client.destroy(cb)
}

var torrent = client.add(torrentId, (argv.out ? { tmp: argv.out } : {}))

torrent.on('infoHash', function () {
  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }

  if (!argv.quiet && !argv.list) {
    torrent.swarm.on('wire', updateMetadata)
    torrent.on('metadata', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
    updateMetadata()
  }
})

var filename, swarm, wires, server

if (argv.list) torrent.once('ready', onReady)
else {
  server = torrent.createServer()
  server.listen(argv.port, function () {
    if (torrent.ready) onReady()
    else torrent.once('ready', onReady)
  })
}

function onReady () {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  // if no index specified, use largest file
  var index = (typeof argv.index === 'number')
    ? argv.index
    : torrent.files.indexOf(torrent.files.reduce(function (a, b) {
      return a.length > b.length ? a : b
    }))
  torrent.files[index].select()

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:' + i + '} : {magenta:' + file.name + '}')
    })
    process.exit(0)
  }

  torrent.on('verifying', function (data) {
    if (argv.quiet) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line('torrent downloaded {green:successfully} from {bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }

    if (argv.remove) {
      remove(maybeExit)
    } else {
      maybeExit()
    }

    function maybeExit () {
      if (!server) {
        process.exit(0)
      }
    }
  })

  var cmd, player
  var href = 'http://' + networkAddress() + ':' + argv.port + '/' + index
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      cp.execFile(vlcPath, VLC_ARGS, errorAndExit)
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + href + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + href + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + href + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + href
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + href
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + href
  }

  if (cmd) {
    player = cp.exec(cmd, errorAndExit)
      .on('exit', function () {
        if (!argv['no-quit']) process.exit(0)
      })
  }

  if (argv.airplay) {
    var airplay = require('airplay-js')
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    var chromecast = require('chromecast-js')
    new chromecast.Browser()
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    var xbmc = require('nodebmc')
    new xbmc.Browser()
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function bytes (num) {
    return prettysize(num)
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (server)
      clivas.line('{green:server running at} {bold:' + href + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + bytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + bytes(swarm.downloaded) + '}' +
      '/{bold:' + bytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + bytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    wires.every(function (wire) {
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      clivas.line(
        '{25+magenta:' + wire.remoteAddress + '} {10:'+bytes(wire.downloaded)+'} ' +
        '{10+cyan:' + bytes(wire.downloadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<commit_msg>improve help message<commit_after>#!/usr/bin/env node

var clivas = require('clivas')
var cp = require('child_process')
var fs = require('fs')
var minimist = require('minimist')
var moment = require('moment')
var networkAddress = require('network-address')
var path = require('path')
var prettysize = require('prettysize')
var WebTorrent = require('../')

process.title = 'WebTorrent'

process.on('exit', function (code) {
  if (code !== 0) {
    clivas.line('{red:ERROR:} If you think this is a bug in webtorrent, report it!')
    console.log('=====>                                               <=====')
    console.log('=====>  https://github.com/feross/webtorrent/issues  <=====')
    console.log('=====>                                               <=====')
  }
})

var argv = minimist(process.argv.slice(2), {
  alias: {
    p: 'port',
    b: 'blocklist',
    t: 'subtitles',
    l: 'list',
    i: 'index',
    n: 'no-quit',
    r: 'remove',
    o: 'out',
    q: 'quiet',
    h: 'help',
    v: 'version'
  },
  boolean: [ // options that are always boolean
    'airplay',
    'chromecast',
    'mplayer',
    'mpv',
    'vlc',
    'xbmc',
    'list',
    'no-quit',
    'remove',
    'quiet',
    'help',
    'version'
  ],
  default: {
    port: 9000
  }
})

if (argv.version) {
  console.log(require('../package.json').version)
  process.exit(0)
}

var torrentId = argv._[0]

if (argv.help || !torrentId) {
  fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
    .split('\n')
    .forEach(function (line) {
      clivas.line('{bold:' + line.substring(0, 20) + '}{red:' + line.substring(20) + '}')
    })

  console.log(function () {/*
  Usage:
      webtorrent <options> <torrent-uri>

      Download the torrent from:
          * magnet uri
          * http url to .torrent file
          * filesystem path to .torrent file
          * info hash (hex string)

  Streaming options:
      --airplay               Apple TV
      --chromecast            Chromecast
      --mplayer               MPlayer
      --mpv                   MPV
      --omx [jack]            omx [default: hdmi]
      --vlc                   VLC
      --xbmc                  XBMC

  Options:
      -o, --out [path]        set download destination [default: /tmp/webtorrent]
      -l, --list              list files in torrent (with indexes)
      -i, --index [index]     stream a particular file from torrent (by index)

      -p, --port [number]     change the http port [default: 9000]
      -b, --blocklist [path]  use the specified blocklist
      -t, --subtitles [file]  load subtitles file
      -n, --no-quit           do not quit webtorrent on vlc exit
      -r, --remove            remove downloaded files on exit

      -q, --quiet             print nothing to stdout
      -v, --version           print the current version

  Please report bugs!  https://github.com/feross/webtorrent/issues

    */}.toString().split(/\n/).slice(1, -1).join('\n'))
  process.exit(0)
}

if (process.env.DEBUG) {
  argv.quiet = argv.q = true
}

var VLC_ARGS = process.env.DEBUG
  ? '-q --play-and-exit'
  : '--play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0'
var MPV_EXEC = 'mpv --ontop --really-quiet --loop=no'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx
  : 'hdmi'

if (argv.subtitles) {
  VLC_ARGS += ' --sub-file=' + argv.subtitles
  MPLAYER_EXEC += ' -sub ' + argv.subtitles
  MPV_EXEC += ' --sub-file=' + argv.subtitles
  OMX_EXEC += ' --subtitles ' + argv.subtitles
}

function error (err) {
  clivas.line('{red:ERROR:} ' + (err.message || err))
}

function errorAndExit (err) {
  error(err)
  process.exit(1)
}

var started = Date.now()
function getRuntime () {
  return Math.floor((Date.now() - started) / 1000)
}

var client = new WebTorrent({
  blocklist: argv.blocklist
})
.on('error', errorAndExit)

if (argv.remove) {
  process.on('SIGINT', remove)
  process.on('SIGTERM', remove)
}

function remove (cb) {
  process.removeListener('SIGINT', remove)
  process.removeListener('SIGTERM', remove)
  client.destroy(cb)
}

var torrent = client.add(torrentId, (argv.out ? { tmp: argv.out } : {}))

torrent.on('infoHash', function () {
  function updateMetadata () {
    var numPeers = torrent.swarm.numPeers
    clivas.clear()
    clivas.line('{green:fetching torrent metadata from} {bold:'+numPeers+'} {green:peers}')
  }

  if (!argv.quiet && !argv.list) {
    torrent.swarm.on('wire', updateMetadata)
    torrent.on('metadata', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
    updateMetadata()
  }
})

var filename, swarm, wires, server

if (argv.list) torrent.once('ready', onReady)
else {
  server = torrent.createServer()
  server.listen(argv.port, function () {
    if (torrent.ready) onReady()
    else torrent.once('ready', onReady)
  })
}

function onReady () {
  filename = torrent.name
  swarm = torrent.swarm
  wires = torrent.swarm.wires

  // if no index specified, use largest file
  var index = (typeof argv.index === 'number')
    ? argv.index
    : torrent.files.indexOf(torrent.files.reduce(function (a, b) {
      return a.length > b.length ? a : b
    }))
  torrent.files[index].select()

  if (argv.list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:' + i + '} : {magenta:' + file.name + '}')
    })
    process.exit(0)
  }

  torrent.on('verifying', function (data) {
    if (argv.quiet) return
    clivas.clear()
    clivas.line(
      '{green:verifying existing torrent} {bold:'+Math.floor(data.percentDone)+'%} ' +
      '({bold:'+Math.floor(data.percentVerified)+'%} {green:passed verification})'
    )
  })

  torrent.on('done', function () {
    if (!argv.quiet) {
      // TODO: expose this data from bittorrent-swarm
      var numActiveWires = torrent.swarm.wires.reduce(function (num, wire) {
        return num + (wire.downloaded > 0)
      }, 0)
      clivas.line('torrent downloaded {green:successfully} from {bold:'+numActiveWires+'/'+torrent.swarm.wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }

    if (argv.remove) {
      remove(maybeExit)
    } else {
      maybeExit()
    }

    function maybeExit () {
      if (!server) {
        process.exit(0)
      }
    }
  })

  var cmd, player
  var href = 'http://' + networkAddress() + ':' + argv.port + '/' + index
  var playerName = argv.airplay ? 'Airplay'
    : argv.chromecast ? 'Chromecast'
    : argv.xbmc ? 'XBMC'
    : argv.vlc ? 'VLC'
    : argv.mplayer ? 'MPlayer'
    : argv.mpv ? 'mpv'
    : argv.omx ? 'OMXPlayer'
    : null

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key.InstallDir.value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      cp.execFile(vlcPath, VLC_ARGS, errorAndExit)
    }
  } else if (argv.vlc) {
    var root = '/Applications/VLC.app/Contents/MacOS/VLC'
    var home = (process.env.HOME || '') + root
    cmd = 'vlc ' + href + ' ' + VLC_ARGS + ' || ' +
      root + ' ' + href + ' ' + VLC_ARGS + ' || ' +
      home + ' ' + href + ' ' + VLC_ARGS
  } else if (argv.mplayer) {
    cmd = MPLAYER_EXEC + ' ' + href
  } else if (argv.mpv) {
    cmd = MPV_EXEC + ' ' + href
  } else if (argv.omx) {
    cmd = OMX_EXEC + ' ' + href
  }

  if (cmd) {
    player = cp.exec(cmd, errorAndExit)
      .on('exit', function () {
        if (!argv['no-quit']) process.exit(0)
      })
  }

  if (argv.airplay) {
    var airplay = require('airplay-js')
    airplay.createBrowser()
      .on('deviceOn', function (device) {
        device.play(href, 0, function () {})
      })
      .start()
    // TODO: handle case where user closes airplay. do same thing as when VLC is closed
  }

  if (argv.chromecast) {
    var chromecast = require('chromecast-js')
    new chromecast.Browser()
      .on('deviceOn', function (device) {
        device.connect()
        device.on('connected', function () {
          device.play(href)
        })
      })
  }

  if (argv.xbmc) {
    var xbmc = require('nodebmc')
    new xbmc.Browser()
      .on('deviceOn', function (device) {
          device.play(href, function () {})
      })
  }

  var hotswaps = 0
  torrent.on('hotswap', function () {
    hotswaps += 1
  })

  if (!argv.quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')) // clear for drawing

    setInterval(draw, 500)
  }

  function active (wire) {
    return !wire.peerChoking
  }

  function bytes (num) {
    return prettysize(num)
  }

  function draw () {
    var unchoked = wires.filter(active)
    var linesremaining = clivas.height
    var peerslisted = 0
    var speed = swarm.downloadSpeed()
    var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
    var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

    clivas.clear()

    if (playerName)
      clivas.line('{green:Streaming to} {bold:' + playerName + '}')
    if (server)
      clivas.line('{green:server running at} {bold:' + href + '}')

    clivas.line('')
    clivas.line('{green:downloading:} {bold:' + filename + '}')
    clivas.line(
      '{green:speed: }{bold:' + bytes(speed) + '/s}  ' +
      '{green:downloaded:} {bold:' + bytes(swarm.downloaded) + '}' +
      '/{bold:' + bytes(torrent.length) + '}  ' +
      '{green:uploaded:} {bold:' + bytes(swarm.uploaded) + '}  ' +
      '{green:peers:} {bold:' + unchoked.length + '/' + wires.length + '}  ' +
      '{green:hotswaps:} {bold:' + hotswaps + '}'
    )
    clivas.line(
      '{green:time remaining:} {bold:' + estimate + ' remaining}  ' +
      '{green:total time:} {bold:' + getRuntime() + 's}  ' +
      '{green:queued peers:} {bold:' + swarm.numQueued + '}  ' +
      '{green:blocked:} {bold:' + torrent.numBlockedPeers + '}'
    )
    clivas.line('{80:}')
    linesremaining -= 8

    wires.every(function (wire) {
      var tags = []
      if (wire.peerChoking) tags.push('choked')
      clivas.line(
        '{25+magenta:' + wire.remoteAddress + '} {10:'+bytes(wire.downloaded)+'} ' +
        '{10+cyan:' + bytes(wire.downloadSpeed()) + '/s} ' +
        '{15+grey:' + tags.join(', ') + '}'
      )
      peerslisted++
      return linesremaining - peerslisted > 4
    })
    linesremaining -= peerslisted

    if (wires.length > peerslisted) {
      clivas.line('{80:}')
      clivas.line('... and '+(wires.length - peerslisted)+' more')
    }

    clivas.line('{80:}')
    clivas.flush(true)
  }
}
<|endoftext|>


<commit_before>module.exports = function override(config, env) {
    // const fs = require('fs')
    // const _ = require('lodash')
    // const flat = require('flat')
    // const locales = fs.readdirSync('src/locale').filter((name) => /^[^\\.]/.test(name))
    // const messages = {}
    //
    // locales.map((locale) =>
    //     messages[locale] = require(`locale/${locale}/translations.json`)
    // )
    //
    // _.chain(locales)
    //     .map((locale) => require(`locale/${locale}/translations.json`))
    //     .map((messages) =>
    //         _.chain(flat.flatten(messages))
    //             .pickBy(_.identity)
    //             .keys()
    //             .value())
    //     .tap(console.log)
    //     .intersectionBy()
    //     .tap(console.log)
    //     .value()

    configureCssModuleLoader(config.module.rules)
    return config;

    function configureImportsLoaders(importsLoaders) {
        Object.keys(importsLoaders).forEach(path =>
            config.module.rules = (config.module.rules || []).concat({
                test: require.resolve(path),
                enforce: 'pre',
                use: 'imports-loader?' + importsLoaders[path]
            })
        )
    }

    /**
     * Find the /\.css$/ matching rule with a css-loader.
     * Exclude /\.module\.css$/.
     * Clone it to match /\.module\.css$/, and enable module support.
     */
    function configureCssModuleLoader(o) {
        if (o instanceof Array)
            return o.find((item, i) => {
                if (item instanceof Object && 'test' in item && String(item.test) === '/\\.css$/') {
                    const cssLoader = findCssLoader(item)
                    if (cssLoader) {
                        const loaders = o
                        const globalCssConfig = item
                        const moduleCssConfig = JSON.parse(JSON.stringify(globalCssConfig))

                        globalCssConfig.exclude = /\.module\.css$/
                        moduleCssConfig.test = /\.module\.css$/
                        loaders.splice(i, 0, moduleCssConfig)

                        const cssModuleLoader = findCssLoader(moduleCssConfig)
                        cssModuleLoader.options.modules = true
                        cssModuleLoader.options.localIdentName = '[name]__[local]___[hash:base64:5]'
                        return globalCssConfig
                    } else
                        return null
                } else
                    configureCssModuleLoader(item)
            })
        else if (o instanceof Object)
            return Object.keys(o).find((key) => configureCssModuleLoader(o[key]))
        else
            return null
    }

    function findCssLoader(o) {
        if (o instanceof Array) {
            return o
                .map((item) => findCssLoader(item))
                .filter((item) => item)
                .find((item) => item)
        } else if (o instanceof Object) {
            if ('loader' in o && o.loader.indexOf('/css-loader/') > -1)
                return o
            else
                return Object.keys(o).map((key) => findCssLoader(o[key]))
                    .filter((item) => item)
                    .find((item) => item)
        } else
            return null
    }

}

<commit_msg>validate all translations exist<commit_after>module.exports = function override(config, env) {
    // const fs = require('fs')
    // const _ = require('lodash')
    // const flat = require('flat')
    // const locales = fs.readdirSync('src/locale').filter((name) => /^[^\\.]/.test(name))
    // const messages = {}
    //
    // locales.map((locale) =>
    //     messages[locale] = require(`locale/${locale}/translations.json`)
    // )
    //
    // _.chain(locales)
    //     .map((locale) => require(`locale/${locale}/translations.json`))
    //     .map((messages) =>
    //         _.chain(flat.flatten(messages))
    //             .pickBy(_.identity)
    //             .keys()
    //             .value())
    //     .tap(console.log)
    //     .intersectionBy()
    //     .tap(console.log)
    //     .value()

    const fs = require('fs')
    const _ = require('lodash')
    const flat = require('flat')
    const locales = fs.readdirSync('src/locale').filter((name) => /^[^\\.]/.test(name))

    const keys = _.chain(locales)
        .map((locale) => require(`./src/locale/${locale}/translations`))
        .map((messages) =>
            _.chain(flat.flatten(messages))
                .pickBy(_.identity)
                .keys()
                .value())
        .value()

    const incompleteKeys = _.difference(_.union(...keys), _.intersection(...keys))
    if (incompleteKeys)
        throw `Missing translations: \n${incompleteKeys.join('\n')}`

    configureCssModuleLoader(config.module.rules)
    return config

    function configureImportsLoaders(importsLoaders) {
        Object.keys(importsLoaders).forEach(path =>
            config.module.rules = (config.module.rules || []).concat({
                test: require.resolve(path),
                enforce: 'pre',
                use: 'imports-loader?' + importsLoaders[path]
            })
        )
    }

    /**
     * Find the /\.css$/ matching rule with a css-loader.
     * Exclude /\.module\.css$/.
     * Clone it to match /\.module\.css$/, and enable module support.
     */
    function configureCssModuleLoader(o) {
        if (o instanceof Array)
            return o.find((item, i) => {
                if (item instanceof Object && 'test' in item && String(item.test) === '/\\.css$/') {
                    const cssLoader = findCssLoader(item)
                    if (cssLoader) {
                        const loaders = o
                        const globalCssConfig = item
                        const moduleCssConfig = JSON.parse(JSON.stringify(globalCssConfig))

                        globalCssConfig.exclude = /\.module\.css$/
                        moduleCssConfig.test = /\.module\.css$/
                        loaders.splice(i, 0, moduleCssConfig)

                        const cssModuleLoader = findCssLoader(moduleCssConfig)
                        cssModuleLoader.options.modules = true
                        cssModuleLoader.options.localIdentName = '[name]__[local]___[hash:base64:5]'
                        return globalCssConfig
                    } else
                        return null
                } else
                    configureCssModuleLoader(item)
            })
        else if (o instanceof Object)
            return Object.keys(o).find((key) => configureCssModuleLoader(o[key]))
        else
            return null
    }

    function findCssLoader(o) {
        if (o instanceof Array) {
            return o
                .map((item) => findCssLoader(item))
                .filter((item) => item)
                .find((item) => item)
        } else if (o instanceof Object) {
            if ('loader' in o && o.loader.indexOf('/css-loader/') > -1)
                return o
            else
                return Object.keys(o).map((key) => findCssLoader(o[key]))
                    .filter((item) => item)
                    .find((item) => item)
        } else
            return null
    }

}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

function Bitcoin(settings, user, password) {
	this.settings = {host: null, port: null, auth: null, url: null, account: null};

	this.prepareURL = function() {
		var url = "http://";

		url += this.settings.host;

		if(this.settings.port) {
			url += ":" + this.settings.port;
		}

		return url;
	}

	this.prepareAuth = function(user, password) {
		return "Basic " + jQuery.base64_encode(user + ":" + password);
	}

	this.RPC = function(method, params, callback, context) {
		var request;
		var auth = this.settings.auth;

		if(params != null) {
			request = {method: method, params: params};
		} else {
			request = {method: method};
		}

		jQuery.ajax({url: this.settings.url, dataType: 'json', type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(request),
					timeout: 5000,
					beforeSend: function(req){
                		req.setRequestHeader("Authorization", auth);
					},
					success:
						 function(data) {
							callback(data.result, data.error, context);
						},
					error:
						 function(req, textStatus, error) {
							var data;
							try  {
								if (!req.responseText)
									throw "no responseText";

								data = jQuery.parseJSON(req.responseText);
							} catch (err) {
								data = {result: null, error: {code: req.status}};

								if (data.error.code === 0 && !req.status)
									data.error.message = "RPC not found";
								else {
									if (req.statusText)
										data.error.message = req.statusText;
									else
										data.error.message = data.error.code.toString();
								}
							}

							callback(data.result, data.error, context);
						}
					});
	}

	this.listAccounts = function(callback, context) {
		this.RPC("listaccounts", null, callback, context);
	}

	this.listTransactions = function(callback, context) {
		this.RPC("listtransactions", [this.settings.account, 999999], callback, context);
	}

	this.validateAddress = function(callback, address, context) {
		this.RPC("validateaddress", [address], callback, context);
	}

	this.sendBTC = function(callback, address, amount, context) {
		this.RPC("sendfrom", [this.settings.account, address, amount], callback, context);
	}

	this.getAddress = function(callback, context) {
		this.RPC("getaccountaddress", [this.settings.account], callback, context);
	}

	this.getBalance = function(callback, context) {
		this.RPC("getbalance", [this.settings.account], callback, context);
	}

	this.getInfo = function(callback, context) {
		this.RPC("getinfo", null, callback, context);
	}

	this.selectAccount = function(account) {
		if (account != undefined)
			this.settings.account = account;
		else
			this.settings.account = "";
	}

	this.init = function(settings, user, password) {
		this.settings = settings;

		if (!this.settings.url)
			this.settings.url = this.prepareURL();

		if (!this.settings.auth && user && password)
			this.settings.auth = this.prepareAuth(user, password);

		this.selectAccount(settings.account);
	}

	this.init(settings, user, password);
}
<commit_msg>increased RPC timeout to 15s<commit_after>/*
 * Copyright (c) 2010 Nils Schneider
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

function Bitcoin(settings, user, password) {
	this.settings = {host: null, port: null, auth: null, url: null, account: null};

	this.prepareURL = function() {
		var url = "http://";

		url += this.settings.host;

		if(this.settings.port) {
			url += ":" + this.settings.port;
		}

		return url;
	}

	this.prepareAuth = function(user, password) {
		return "Basic " + jQuery.base64_encode(user + ":" + password);
	}

	this.RPC = function(method, params, callback, context) {
		var request;
		var auth = this.settings.auth;

		if(params != null) {
			request = {method: method, params: params};
		} else {
			request = {method: method};
		}

		jQuery.ajax({url: this.settings.url, dataType: 'json', type: 'POST',
					contentType: 'application/json',
					data: JSON.stringify(request),
					timeout: 15000,
					beforeSend: function(req){
                		req.setRequestHeader("Authorization", auth);
					},
					success:
						 function(data) {
							callback(data.result, data.error, context);
						},
					error:
						 function(req, textStatus, error) {
							var data;
							try  {
								if (!req.responseText)
									throw "no responseText";

								data = jQuery.parseJSON(req.responseText);
							} catch (err) {
								data = {result: null, error: {code: req.status}};

								if (data.error.code === 0 && !req.status)
									data.error.message = "RPC not found";
								else {
									if (req.statusText)
										data.error.message = req.statusText;
									else
										data.error.message = data.error.code.toString();
								}
							}

							callback(data.result, data.error, context);
						}
					});
	}

	this.listAccounts = function(callback, context) {
		this.RPC("listaccounts", null, callback, context);
	}

	this.listTransactions = function(callback, context) {
		this.RPC("listtransactions", [this.settings.account, 999999], callback, context);
	}

	this.validateAddress = function(callback, address, context) {
		this.RPC("validateaddress", [address], callback, context);
	}

	this.sendBTC = function(callback, address, amount, context) {
		this.RPC("sendfrom", [this.settings.account, address, amount], callback, context);
	}

	this.getAddress = function(callback, context) {
		this.RPC("getaccountaddress", [this.settings.account], callback, context);
	}

	this.getBalance = function(callback, context) {
		this.RPC("getbalance", [this.settings.account], callback, context);
	}

	this.getInfo = function(callback, context) {
		this.RPC("getinfo", null, callback, context);
	}

	this.selectAccount = function(account) {
		if (account != undefined)
			this.settings.account = account;
		else
			this.settings.account = "";
	}

	this.init = function(settings, user, password) {
		this.settings = settings;

		if (!this.settings.url)
			this.settings.url = this.prepareURL();

		if (!this.settings.auth && user && password)
			this.settings.auth = this.prepareAuth(user, password);

		this.selectAccount(settings.account);
	}

	this.init(settings, user, password);
}
<|endoftext|>


<commit_before>
module.exports = function(five) {
  var
	continents = {};

	this.init = function() {
		// Define the pins the LEDs are connected to.
		continents.NA = new five.Led({pin: 3});
		continents.SA = new five.Led({pin: 5});
		continents.EU = new five.Led({pin: 6});
		continents.AS = new five.Led({pin: 9});
		continents.OC = new five.Led({pin: 10});
	};

	this.blink = function(name) {
		if (continents.hasOwnProperty(name)) {
			continents[name].fadeIn(200,10);
			setTimeout(function(){
				continents[name].fadeOut(0, 500);
			},500);
		}
	};

	this.init();
};
<commit_msg>Added little test routine, we now light up all leds before displaying data.<commit_after>
module.exports = function(five) {
  var
	continents = {},
	ready = false;

	this.init = function() {
		// Define the pins the LEDs are connected to.
		continents.NA = new five.Led({pin: 3});
		continents.SA = new five.Led({pin: 5});
		continents.EU = new five.Led({pin: 6});
		continents.AS = new five.Led({pin: 9});
		continents.OC = new five.Led({pin: 10});

		// Test routine
		for (var key in continents) {
			continents[key].on();
		}

		setTimeout(function(){
			for (var c in continents) {
				continents[c].off();
			}
			ready = true;
		}, 1000);
	};

	this.blink = function(name) {
		if (ready && continents.hasOwnProperty(name)) {
			continents[name].fadeIn(200,10);
			setTimeout(function(){
				continents[name].fadeOut(0, 500);
			},500);
		}
	};

	this.init();
};
<|endoftext|>


<commit_before>(function() {

  angular
    .module('mdColorMenu', ['ngAria', 'ngAnimate', 'ngMaterial'])
    .factory('mdPickerColors', mdPickerColors)
    .directive('mdColorMenu', mdColorMenuDirective);

  function mdPickerColors($mdColorPalette) {
    var colors = [];

    angular.forEach($mdColorPalette, function(swatch, swatchName) {
      var swatchColors = [];
      angular.forEach(swatch, function(color, colorName) {
        if (isAccentColors(colorName) || isBlack(colorName))
          return;
        var foregroundColor = list2rgbString(color.contrast);
        var backgroundColor = list2rgbString(color.value);
        var name = swatchName + ' ' + colorName;
        swatchColors.push({name: name, style: {'color': foregroundColor, 'background-color': backgroundColor}});
      });
      colors.push(swatchColors);
    });

    return colors;

    function isAccentColors(colorName) {
      return colorName[0] === 'A';
    }

    function isBlack(colorName) {
      return colorName === '1000';
    }

    function list2rgbString(rgbList) {
      if (rgbList.length === 4) {
        return 'rgba(' + rgbList.join(',') + ')';
      }
      return 'rgb(' + rgbList.join(',') + ')';
    }
  }

  function mdColorMenuDirective() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      controller: mdColorMenuController,
      controllerAs: 'vm',
      bindToController: {
        color: '='
      },
      template: [
        '<md-menu md-position-mode="target-right target">',
        '

',
        '  <md-menu-content class="md-cm">',
        '

',
        '
',
        '
',
        '
',
        '          ✔',
        '          <md-tooltip>{{color.name}}</md-tooltip>',
        '
',
        '
',
        '
',
        '  </md-menu-content>',
        '</md-menu>'
      ].join('')
    }
  }

  function mdColorMenuController(mdPickerColors) {
    var vm = this;

    vm.openMenu = openMenu;
    vm.colors = mdPickerColors;
    vm.selectColor = selectColor;

    function openMenu($mdOpenMenu, $event) {
      $mdOpenMenu($event);
    }

    function selectColor(color) {
      vm.color = color;
    }
  }

})();
<commit_msg>expose hex code of selected color, closes #1<commit_after>(function() {

  angular
    .module('mdColorMenu', ['ngAria', 'ngAnimate', 'ngMaterial'])
    .factory('mdPickerColors', mdPickerColors)
    .directive('mdColorMenu', mdColorMenuDirective);

  function mdPickerColors($mdColorPalette) {
    var colors = [];

    angular.forEach($mdColorPalette, function(swatch, swatchName) {
      var swatchColors = [];
      angular.forEach(swatch, function(color, colorName) {
        if (isAccentColors(colorName) || isBlack(colorName))
          return;
        var foregroundColor = listToRgbString(color.contrast);
        var backgroundColor = listToRgbString(color.value);
        var name = swatchName + ' ' + colorName;
        var hex = listToHexString(color.value);
        swatchColors.push({name: name, hex: hex, style: {'color': foregroundColor, 'background-color': backgroundColor}});
      });
      colors.push(swatchColors);
    });

    return colors;

    function isAccentColors(colorName) {
      return colorName[0] === 'A';
    }

    function isBlack(colorName) {
      return colorName === '1000';
    }

    function listToRgbString(rgbList) {
      if (rgbList.length === 4) {
        return 'rgba(' + rgbList.join(',') + ')';
      }
      return 'rgb(' + rgbList.join(',') + ')';
    }

    function listToHexString(rgbList) {
      return '#' + rgbList.map(toHex).join('');
    }

    function toHex(number) {
      return number.toString(16);
    }
  }

  function mdColorMenuDirective() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {},
      controller: mdColorMenuController,
      controllerAs: 'vm',
      bindToController: {
        color: '='
      },
      template: [
        '<md-menu md-position-mode="target-right target">',
        '

',
        '  <md-menu-content class="md-cm">',
        '

',
        '
',
        '
',
        '
',
        '          ✔',
        '          <md-tooltip>{{color.name}}</md-tooltip>',
        '
',
        '
',
        '
',
        '  </md-menu-content>',
        '</md-menu>'
      ].join('')
    }
  }

  function mdColorMenuController(mdPickerColors) {
    var vm = this;

    vm.openMenu = openMenu;
    vm.colors = mdPickerColors;
    vm.selectColor = selectColor;

    function openMenu($mdOpenMenu, $event) {
      $mdOpenMenu($event);
    }

    function selectColor(color) {
      vm.color = color;
    }
  }

})();
<|endoftext|>