<commit_before>/* Copyright 2011 Ask Bjørn Hansen, see LICENSE */
"use strict";

var https = require('https');
var querystring = require('querystring');

function setup_response_handler(req, callback) {
    if (typeof callback !== "function") {
        //console.log("missing callback");
        return;
    }
    req.on('response',
        function(res) {
            var response = '';
            res.setEncoding('utf8');
            res.on('data',
                function(chunk) {
                    response += chunk;
            });
            res.on('end',
                function() {
                    var err = null;
                    try {
                        response = JSON.parse(response);
                        if(200 != res.statusCode) {
                            err = new Error(response.error.message);
                            err.name = response.error.type;
                            response = null;
                        }
                    }
                    catch(e) {
                        err = new Error("Invalid JSON from stripe.com");
                        response = null;
                    }
                    callback(err, response);
            });
        });
}

module.exports = function (api_key, options) {
    var defaults = options || {};

    var auth = 'Basic ' + new Buffer(api_key + ":").toString('base64');

    function _request(method, path, data, callback) {

        //console.log("data", typeof data, data);

        // convert first level of deep data structures to foo[bar]=baz syntax
        Object.keys(data).forEach(function(key) {
            if (typeof data[key] === 'object' && data[key] !== null) {
                var o = data[key];
                delete data[key];
                Object.keys(o).forEach(function(k) {
                    var new_key = key + "[" + k + "]";
                    data[new_key] = o[k];
                });
            }
        });

        var request_data = querystring.stringify(data);

        //console.log(method, "request for", path);
        //console.log("http request", request_data);

        var request_options = {
              host: 'api.stripe.com',
              port: '443',
              path: path,
              method: method,
              headers: {
                  'Authorization': auth,
                  'Accept': 'application/json',
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'Content-Length': request_data.length
              }
          };

        var req = https.request(request_options);
        setup_response_handler(req, callback);
        req.write(request_data);
        req.end();
    }

    function post(path, data, callback) {
        _request('POST', path, data, callback);
    }

    function get(path, data, callback) {
        _request('GET', path, data, callback);
    }

    function del(path, data, callback) {
        _request('DELETE', path, data, callback);
    }

    return {
        charges: {
            create: function (data, cb) {
                post("/v1/charges", data, cb);
            },
            retrieve: function(charge_id, cb) {
                if(!(charge_id && typeof charge_id === 'string')) {
                    cb("charge_id required");
                }
                get("/v1/charges/" + charge_id, {}, cb);
            },
            refund: function(charge_id, amount, cb) {
                var requestParams = {};
                if(!(charge_id && typeof charge_id === 'string')) {
                    cb("charge_id required");
                }
                if (typeof amount === 'function') {
                    cb = amount;
                    amount = null;
                }
                if (amount) {
                    requestParams.amount = amount;
                }
                post("/v1/charges/" + charge_id + "/refund", requestParams, cb);
            },
            list: function(data, cb) {
                get("/v1/charges", data, cb);
            },
        },
        customers: {
            create: function (data, cb) {
                post("/v1/customers", data, cb);
            },
            retrieve: function(customer_id, cb) {
                if (!(customer_id && typeof customer_id === 'string')) {
                    return cb("customer_id required");
                }
                get("/v1/customers/" + customer_id, {}, cb);
            },
            update: function(customer_id, data, cb) {
                post("/v1/customers/" + customer_id, data, cb);
            },
            del: function(customer_id, cb) {
                del("/v1/customers/" + customer_id, {}, cb);
            },
            list: function(count, offset, cb) {
                get("/v1/customers", { count: count, offset: offset}, cb );
            },
            update_subscription: function(customer_id, data, cb) {
                post("/v1/customers/" + customer_id + '/subscription', data, cb);
            },
            cancel_subscription: function(customer_id, at_period_end, cb) {
                del("/v1/customers/" + customer_id + '/subscription', { at_period_end: at_period_end }, cb);
            }
        },
        plans: {
            create: function (data, cb) {
                post("/v1/plans", data, cb);
            },
            retrieve: function(plan_id, cb) {
                if (!(plan_id && typeof plan_id === 'string')) {
                    return cb("plan_id required");
                }
                get("/v1/plans/" + plan_id, {}, cb);
            },
            del: function(plan_id, cb) {
                del("/v1/plans/" + plan_id, {}, cb);
            },
            list: function(count, offset, cb) {
                get("/v1/plans", { count: count, offset: offset}, cb );
            },
            update: function (plan_id, data, cb) {
                post("/v1/plans/" + plan_id, data, cb);
            }
        },
        invoices: {
            retrieve: function(invoice_id, cb) {
                get("/v1/invoices/" + invoice_id, {}, cb);
            },
            list: function(data, cb) {
                get("/v1/invoices", data, cb);
            },
            upcoming: function(customer_id, cb) {
                get("/v1/invoices/upcoming", { customer: customer_id }, cb);
            },
        },
        invoice_items: {
            create: function(data, cb) {
                post("/v1/invoiceitems", data, cb);
            },
            retrieve: function(invoice_item_id, cb) {
                if (!(invoice_item_id && typeof invoice_item_id === 'string')) {
                    return cb("invoice_item_id required");
                }
                get("/v1/invoiceitems/" + invoice_item_id, {}, cb);
            },
            update: function(invoice_item_id, data, cb) {
                post("/v1/invoiceitems/" + invoice_item_id, data, cb);
            },
            del: function(invoice_item_id, cb) {
                del("/v1/invoiceitems/" + invoice_item_id, {}, cb);
            },
            list: function(customer_id, count, offset, cb) {
                get("/v1/invoiceitems", { customer: customer_id, count: count, offset: offset}, cb );
            }
        },
        coupons: {
            create: function (data, cb) {
                post("/v1/coupons", data, cb);
            },
            retrieve: function(coupon_id, cb) {
                if (!(coupon_id && typeof coupon_id === 'string')) {
                    cb("coupon_id required");
                }
                get("/v1/coupons/" + coupon_id, {}, cb);
            },
            del: function(coupon_id, cb) {
                del("/v1/coupons/" + coupon_id, {}, cb);
            },
            list: function(count, offset, cb) {
                get("/v1/coupons", { count: count, offset: offset}, cb );
            }
        },
        token: {
            create: function (data, cb) {
                post("/v1/tokens", data, cb)
            },
            retrieve: function (token_id, cb) {
                get("/v1/tokens/" + token_id, {}, cb)
            }
        },
        events: {
            retrieve: function (token_id, cb) {
                get("/v1/events/" + token_id, {}, cb)
            },
            list: function (cb) {
                get("/v1/events/", {}, cb)
            }
        },
    };
}
<commit_msg>list methods should all support object as an argument<commit_after>/* Copyright 2011 Ask Bjørn Hansen, see LICENSE */
"use strict";

var https = require('https');
var querystring = require('querystring');

function setup_response_handler(req, callback) {
    if (typeof callback !== "function") {
        //console.log("missing callback");
        return;
    }
    req.on('response',
        function(res) {
            var response = '';
            res.setEncoding('utf8');
            res.on('data',
                function(chunk) {
                    response += chunk;
            });
            res.on('end',
                function() {
                    var err = null;
                    try {
                        response = JSON.parse(response);
                        if(200 != res.statusCode) {
                            err = new Error(response.error.message);
                            err.name = response.error.type;
                            response = null;
                        }
                    }
                    catch(e) {
                        err = new Error("Invalid JSON from stripe.com");
                        response = null;
                    }
                    callback(err, response);
            });
        });
}

module.exports = function (api_key, options) {
    var defaults = options || {};

    var auth = 'Basic ' + new Buffer(api_key + ":").toString('base64');

    function _request(method, path, data, callback) {

        //console.log("data", typeof data, data);

        // convert first level of deep data structures to foo[bar]=baz syntax
        Object.keys(data).forEach(function(key) {
            if (typeof data[key] === 'object' && data[key] !== null) {
                var o = data[key];
                delete data[key];
                Object.keys(o).forEach(function(k) {
                    var new_key = key + "[" + k + "]";
                    data[new_key] = o[k];
                });
            }
        });

        var request_data = querystring.stringify(data);

        //console.log(method, "request for", path);
        //console.log("http request", request_data);

        var request_options = {
              host: 'api.stripe.com',
              port: '443',
              path: path,
              method: method,
              headers: {
                  'Authorization': auth,
                  'Accept': 'application/json',
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'Content-Length': request_data.length
              }
          };

        var req = https.request(request_options);
        setup_response_handler(req, callback);
        req.write(request_data);
        req.end();
    }

    function post(path, data, callback) {
        _request('POST', path, data, callback);
    }

    function get(path, data, callback) {
        _request('GET', path, data, callback);
    }

    function del(path, data, callback) {
        _request('DELETE', path, data, callback);
    }

    return {
        charges: {
            create: function (data, cb) {
                post("/v1/charges", data, cb);
            },
            retrieve: function(charge_id, cb) {
                if(!(charge_id && typeof charge_id === 'string')) {
                    cb("charge_id required");
                }
                get("/v1/charges/" + charge_id, {}, cb);
            },
            refund: function(charge_id, amount, cb) {
                var requestParams = {};
                if(!(charge_id && typeof charge_id === 'string')) {
                    cb("charge_id required");
                }
                if (typeof amount === 'function') {
                    cb = amount;
                    amount = null;
                }
                if (amount) {
                    requestParams.amount = amount;
                }
                post("/v1/charges/" + charge_id + "/refund", requestParams, cb);
            },
            list: function(data, cb) {
                get("/v1/charges", data, cb);
            },
        },
        customers: {
            create: function (data, cb) {
                post("/v1/customers", data, cb);
            },
            retrieve: function(customer_id, cb) {
                if (!(customer_id && typeof customer_id === 'string')) {
                    return cb("customer_id required");
                }
                get("/v1/customers/" + customer_id, {}, cb);
            },
            update: function(customer_id, data, cb) {
                post("/v1/customers/" + customer_id, data, cb);
            },
            del: function(customer_id, cb) {
                del("/v1/customers/" + customer_id, {}, cb);
            },
            list: function(count, offset, cb) {
                if(typeof count == 'object' && typeof offset == 'function' && !cb)
                  cb = offset && offset = count.object && count = count.count;
                get("/v1/customers", { count: count, offset: offset}, cb );
            },
            update_subscription: function(customer_id, data, cb) {
                post("/v1/customers/" + customer_id + '/subscription', data, cb);
            },
            cancel_subscription: function(customer_id, at_period_end, cb) {
                del("/v1/customers/" + customer_id + '/subscription', { at_period_end: at_period_end }, cb);
            }
        },
        plans: {
            create: function (data, cb) {
                post("/v1/plans", data, cb);
            },
            retrieve: function(plan_id, cb) {
                if (!(plan_id && typeof plan_id === 'string')) {
                    return cb("plan_id required");
                }
                get("/v1/plans/" + plan_id, {}, cb);
            },
            del: function(plan_id, cb) {
                del("/v1/plans/" + plan_id, {}, cb);
            },
            list: function(count, offset, cb) {
                get("/v1/plans", { count: count, offset: offset}, cb );
            },
            update: function (plan_id, data, cb) {
                post("/v1/plans/" + plan_id, data, cb);
            }
        },
        invoices: {
            retrieve: function(invoice_id, cb) {
                get("/v1/invoices/" + invoice_id, {}, cb);
            },
            list: function(data, cb) {
                get("/v1/invoices", data, cb);
            },
            upcoming: function(customer_id, cb) {
                get("/v1/invoices/upcoming", { customer: customer_id }, cb);
            },
        },
        invoice_items: {
            create: function(data, cb) {
                post("/v1/invoiceitems", data, cb);
            },
            retrieve: function(invoice_item_id, cb) {
                if (!(invoice_item_id && typeof invoice_item_id === 'string')) {
                    return cb("invoice_item_id required");
                }
                get("/v1/invoiceitems/" + invoice_item_id, {}, cb);
            },
            update: function(invoice_item_id, data, cb) {
                post("/v1/invoiceitems/" + invoice_item_id, data, cb);
            },
            del: function(invoice_item_id, cb) {
                del("/v1/invoiceitems/" + invoice_item_id, {}, cb);
            },
            list: function(customer_id, count, offset, cb) {
                get("/v1/invoiceitems", { customer: customer_id, count: count, offset: offset}, cb );
            }
        },
        coupons: {
            create: function (data, cb) {
                post("/v1/coupons", data, cb);
            },
            retrieve: function(coupon_id, cb) {
                if (!(coupon_id && typeof coupon_id === 'string')) {
                    cb("coupon_id required");
                }
                get("/v1/coupons/" + coupon_id, {}, cb);
            },
            del: function(coupon_id, cb) {
                del("/v1/coupons/" + coupon_id, {}, cb);
            },
            list: function(count, offset, cb) {
                if(typeof count == 'object' && typeof offset == 'function' && !cb)
                  cb = offset && offset = count.object && count = count.count;
                get("/v1/coupons", { count: count, offset: offset}, cb );
            }
        },
        token: {
            create: function (data, cb) {
                post("/v1/tokens", data, cb)
            },
            retrieve: function (token_id, cb) {
                get("/v1/tokens/" + token_id, {}, cb)
            }
        },
        events: {
            retrieve: function (token_id, cb) {
                get("/v1/events/" + token_id, {}, cb)
            },
            list: function (cb) {
                get("/v1/events/", {}, cb)
            }
        },
    };
}
<|endoftext|>


<commit_before>var ipc = require('ipc');
const app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  if (process.platform != 'darwin')
    app.quit();
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  var entryBasePath = process.env.WEBPACK_DEV_SERVER ? 'http://localhost:8080' : ('file://' + __dirname);
  mainWindow.loadUrl(entryBasePath + '/static/index.html');

  // Open the devtools.
  mainWindow.openDevTools();

  // Allow close the app by shortcut
  ipc.on('quit-app', function() {
    app.quit();
  });

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});
<commit_msg>Convert main to ES6<commit_after>import ipc from 'ipc';
import app from 'app';
import BrowserWindow from 'browser-window';

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
let mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', ()  => {
  if (process.platform !== 'darwin') { app.quit(); }
});

// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  });

  // and load the index.html of the app.
  const entryBasePath = process.env.WEBPACK_DEV_SERVER ? 'http://localhost:8080' : ('file://' + __dirname);
  mainWindow.loadUrl(entryBasePath + '/static/index.html');

  // Open the devtools.
  mainWindow.openDevTools();

  // Allow close the app by shortcut
  ipc.on('quit-app', () => app.quit());

  // Emitted when the window is closed.
  mainWindow.on('closed', () => mainWindow = null);
});
<|endoftext|>


<commit_before>var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var simple_prefs = require("sdk/simple-prefs");
var ui = require("sdk/ui");
var { env } = require('sdk/system/environment');
const {Cc,Ci} = require("chrome");
var { Hotkey } = require("sdk/hotkeys");
var contextMenu = require("sdk/context-menu");

function play_video(url) {
	var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
	file.initWithPath(simple_prefs.prefs.player);

	// create an nsIProcess
	var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
	process.init(file);

	var args = simple_prefs.prefs.params.split(" ")
	args.push(url)

	// process.run(false, args, args.length);
	process.runAsync(args, args.length);
}

var menuItem = contextMenu.Item({
  label: "Watch with MPV",
  context: contextMenu.SelectorContext("[href]"),
  contentScript: 'self.on("click", function(node,data){self.postMessage(node.href);})',
  accessKey: "e",
  image: data.url("icon_button.png"),
  onMessage: function (url) {
    play_video(url);
  }
});

var action_button = ui.ActionButton({
  id: "my-button",
  label: "Action Button!",
  icon: data.url("icon_button.png"),
  onClick: function(state) {
	play_video(tabs.activeTab.url);
  }
});

var showHotKey = Hotkey({
  combo: simple_prefs.prefs.hotkey,
  onPress: function() {
    play_video(tabs.activeTab.url);
  }
});
<commit_msg>Fix label.<commit_after>var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var simple_prefs = require("sdk/simple-prefs");
var ui = require("sdk/ui");
var { env } = require('sdk/system/environment');
const {Cc,Ci} = require("chrome");
var { Hotkey } = require("sdk/hotkeys");
var contextMenu = require("sdk/context-menu");

function play_video(url) {
	var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
	file.initWithPath(simple_prefs.prefs.player);

	// create an nsIProcess
	var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
	process.init(file);

	var args = simple_prefs.prefs.params.split(" ")
	args.push(url)

	// process.run(false, args, args.length);
	process.runAsync(args, args.length);
}

var menuItem = contextMenu.Item({
  label: "Watch with MPV",
  context: contextMenu.SelectorContext("[href]"),
  contentScript: 'self.on("click", function(node,data){self.postMessage(node.href);})',
  accessKey: "e",
  image: data.url("icon_button.png"),
  onMessage: function (url) {
    play_video(url);
  }
});

var action_button = ui.ActionButton({
  id: "my-button",
  label: "Play with MPV",
  icon: data.url("icon_button.png"),
  onClick: function(state) {
	play_video(tabs.activeTab.url);
  }
});

var showHotKey = Hotkey({
  combo: simple_prefs.prefs.hotkey,
  onPress: function() {
    play_video(tabs.activeTab.url);
  }
});
<|endoftext|>


<commit_before>
'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
var fs = require('fs');
var uuid = require('uuid');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;

// Hardcoded dependencies hate this
var FsUnit = 'FsUnit ~> 1.3.1';
var NUnitRunners = 'NUnit.Runners ~> 2.6.4';
var FAKE = 'FAKE';

var FSharpGenerator = yeoman.generators.Base.extend({
    ACTION_CREATE_STANDALONE_PROJECT: 1,

    constructor: function() {
        yeoman.generators.Base.apply(this, arguments);
        this.templatedata = {};
    },

    init: function() {
        this.log('Welcome to the FSharp kata generator!');
    },

    askFor: function() {
        var done = this.async();
        var prompts = [{
            name: 'applicationName',
            message: 'What\'s the name of your kata?',
            default: this.type
        }];

        this.prompt(prompts, function(props) {
            this.action = this.ACTION_CREATE_STANDALONE_PROJECT;
            this.templatedata.namespace = props.applicationName;
            this.templatedata.applicationname = props.applicationName;
            this.templatedata.guid = uuid.v4();
            this.templatedata.packagesPath = "packages"
            this.templatedata.paketPath = ".paket"
            this.applicationName = props.applicationName;
            this.type = "classlib";
            this.paket = true;
            this.fake = true;
            done();
        }.bind(this));
    },

    writing: function() {
        this._copy_template();

        if(this.paket) {
            this._copy_paket();
        }

        if(this.fake) {
            this._copy_fake();
        }
    },

    install: function() {
        var done = this.async();
        var generator = this;

        this._make_build_sh_executable();

        var bpath = this._paket_bootstrap_path();

        var bootstrapper = this._execManaged(bpath, [], {});

        bootstrapper.stdout.on('data', function (data) {
            generator.log(data.toString());
        });

        bootstrapper.on('close', function (code) {
            var paket_path;
            var dest_path;

            paket_path = path.join(generator.destinationRoot(), generator.applicationName, ".paket", "paket.exe" );
            dest_path = path.join(generator.destinationRoot(), generator.applicationName);

            try{
                generator.log(dest_path);

                var paket = generator._execManaged(paket_path, ['convert-from-nuget','-f'], {cwd: dest_path});

                paket.stdout.on('data', function (data) {
                    generator.log(data.toString());
                });

                paket.stdout.on('close', function (data) {
                    var simplifiy = generator._execManaged(paket_path, ['simplify'], {cwd: dest_path});

                    simplifiy.stdout.on('data', function (data) {
                        generator.log(data.toString());
                    });

                    simplifiy.stdout.on('close', function (data) {
                        generator.log("Adding FAKE dependency...");
                        var addFake = generator._execManaged(paket_path, ['add', 'nuget', FAKE], {cwd: dest_path});

                        addFake.stdout.on('close', function(data) {
                            generator.log("Adding FsUnit dependency...");
                            var addFsUnit = generator._execManaged(paket_path, ['add', 'nuget', FsUnit], {cwd: dest_path});

                            addFsUnit.stdout.on('close', function(data) {
                                generator.log("Adding Nunit.Runners dependency...");
                                var addNUnit_Runners = generator._execManaged(paket_path, ['add', 'nuget', NUnitRunners], {cwd: dest_path});

                                addNUnit_Runners.stdout.on('close', function(data) {
                                    done();
                                })
                            })
                        })
                    });
                });
            }
            catch(ex)
            {
                log(ex);
            }
        });
    },

    end: function() {
        this.log('\r\n');
        this.log('Your project is now created');
        this.log('\r\n');
    },

    _copy_template: function() {
        var p = path.join(this.templatePath(), this.type);
        this._copy(p, this.applicationName);
    },

    _copy_paket: function() {
        var bpath = this._paket_bootstrap_path();

        var p = path.join(this.templatePath(), ".paket", "paket.bootstrapper.exe");

        this.copy(p, bpath);
    },

    _copy_fake: function() {
        var fakeSource = path.join(this.templatePath(), ".fake");
        this._copy(fakeSource, this.applicationName);
    },

    _make_build_sh_executable: function() {
        var dest = this.destinationRoot();

        if (!this._isOnWindows()) {
            var buildShPath = path.join(dest, this.applicationName, 'build.sh');
            var chmodProc = spawnSync('chmod', ['+x', buildShPath], {cwd: dest});
        }
    },

    _paket_bootstrap_path: function() {
        return path.join(this.applicationName, ".paket", "paket.bootstrapper.exe" );
    },

    _copy: function(dirPath, targetDirPath){
        var files = fs.readdirSync(dirPath);
        for(var i in files)
        {
            var f = files[i];
            var fp = path.join(dirPath, f);
            this.log(f);
            if(fs.statSync(fp).isDirectory()) {
                 var newTargetPath = path.join(targetDirPath, f);
                 this._copy(fp, newTargetPath);
            }
            else {
                var fn = path.join(targetDirPath.replace('ApplicationName', this.applicationName), f.replace('ApplicationName', this.applicationName));
                this.template(fp,fn, this.templatedata);
            }
        }
    },

    _execManaged : function(file, args, options) {
        if(this._isOnWindows()){
            return spawn(file, args, options);
        }
        else {
            var monoArgs = [file];
            monoArgs = monoArgs.concat(args);
            return spawn('mono', monoArgs, options);
        }
    },

    _isOnWindows : function() {
        return /^win/.test(process.platform);
    },
});

module.exports = FSharpGenerator;<commit_msg>Rename generator to FSharpKataGenerator<commit_after>
'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
var fs = require('fs');
var uuid = require('uuid');
var spawn = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;

// Hardcoded dependencies hate this
var FsUnit = 'FsUnit ~> 1.3.1';
var NUnitRunners = 'NUnit.Runners ~> 2.6.4';
var FAKE = 'FAKE';

var FSharpKataGenerator = yeoman.generators.Base.extend({
    constructor: function() {
        yeoman.generators.Base.apply(this, arguments);
        this.templatedata = {};
    },

    init: function() {
        this.log('Welcome to the FSharp kata generator!');
    },

    askFor: function() {
        var done = this.async();
        var prompts = [{
            name: 'applicationName',
            message: 'What\'s the name of your kata?',
            default: this.type
        }];

        this.prompt(prompts, function(props) {
            this.templatedata.namespace = props.applicationName;
            this.templatedata.applicationname = props.applicationName;
            this.templatedata.guid = uuid.v4();
            this.templatedata.packagesPath = "packages"
            this.templatedata.paketPath = ".paket"
            this.applicationName = props.applicationName;
            this.type = "classlib";
            this.paket = true;
            this.fake = true;
            done();
        }.bind(this));
    },

    writing: function() {
        this._copy_template();

        if(this.paket) {
            this._copy_paket();
        }

        if(this.fake) {
            this._copy_fake();
        }
    },

    install: function() {
        var done = this.async();
        var generator = this;

        this._make_build_sh_executable();

        var bpath = this._paket_bootstrap_path();

        var bootstrapper = this._execManaged(bpath, [], {});

        bootstrapper.stdout.on('data', function (data) {
            generator.log(data.toString());
        });

        bootstrapper.on('close', function (code) {
            var paket_path = path.join(generator.destinationRoot(), generator.applicationName, ".paket", "paket.exe" );
            var dest_path = path.join(generator.destinationRoot(), generator.applicationName);

            try{
                generator.log(dest_path);

                var paket = generator._execManaged(paket_path, ['convert-from-nuget','-f'], {cwd: dest_path});

                paket.stdout.on('data', function (data) {
                    generator.log(data.toString());
                });

                paket.stdout.on('close', function (data) {
                    var simplifiy = generator._execManaged(paket_path, ['simplify'], {cwd: dest_path});

                    simplifiy.stdout.on('data', function (data) {
                        generator.log(data.toString());
                    });

                    simplifiy.stdout.on('close', function (data) {
                        generator.log("Adding FAKE dependency...");
                        var addFake = generator._execManaged(paket_path, ['add', 'nuget', FAKE], {cwd: dest_path});

                        addFake.stdout.on('close', function(data) {
                            generator.log("Adding FsUnit dependency...");
                            var addFsUnit = generator._execManaged(paket_path, ['add', 'nuget', FsUnit], {cwd: dest_path});

                            addFsUnit.stdout.on('close', function(data) {
                                generator.log("Adding Nunit.Runners dependency...");
                                var addNUnit_Runners = generator._execManaged(paket_path, ['add', 'nuget', NUnitRunners], {cwd: dest_path});

                                addNUnit_Runners.stdout.on('close', function(data) {
                                    done();
                                })
                            })
                        })
                    });
                });
            }
            catch(ex)
            {
                log(ex);
            }
        });
    },

    end: function() {
        this.log('\r\n');
        this.log('Your project is now created');
        this.log('\r\n');
    },

    _copy_template: function() {
        var p = path.join(this.templatePath(), this.type);
        this._copy(p, this.applicationName);
    },

    _copy_paket: function() {
        var bpath = this._paket_bootstrap_path();

        var p = path.join(this.templatePath(), ".paket", "paket.bootstrapper.exe");

        this.copy(p, bpath);
    },

    _copy_fake: function() {
        var fakeSource = path.join(this.templatePath(), ".fake");
        this._copy(fakeSource, this.applicationName);
    },

    _make_build_sh_executable: function() {
        var dest = this.destinationRoot();

        if (!this._isOnWindows()) {
            var buildShPath = path.join(dest, this.applicationName, 'build.sh');
            var chmodProc = spawnSync('chmod', ['+x', buildShPath], {cwd: dest});
        }
    },

    _paket_bootstrap_path: function() {
        return path.join(this.applicationName, ".paket", "paket.bootstrapper.exe" );
    },

    _copy: function(dirPath, targetDirPath){
        var files = fs.readdirSync(dirPath);
        for(var i in files)
        {
            var f = files[i];
            var fp = path.join(dirPath, f);
            this.log(f);
            if(fs.statSync(fp).isDirectory()) {
                 var newTargetPath = path.join(targetDirPath, f);
                 this._copy(fp, newTargetPath);
            }
            else {
                var fn = path.join(targetDirPath.replace('ApplicationName', this.applicationName), f.replace('ApplicationName', this.applicationName));
                this.template(fp,fn, this.templatedata);
            }
        }
    },

    _execManaged : function(file, args, options) {
        if(this._isOnWindows()){
            return spawn(file, args, options);
        }
        else {
            var monoArgs = [file];
            monoArgs = monoArgs.concat(args);
            return spawn('mono', monoArgs, options);
        }
    },

    _isOnWindows : function() {
        return /^win/.test(process.platform);
    },
});

module.exports = FSharpKataGenerator;<|endoftext|>


<commit_before>"use strict";

const childProcess = require("child_process"),
    message = require("./logger.js").buildMessage;

function local(write, command, options, escape, inline, follow) {
    return new Promise((resolve, reject) => {
        let messages = [{
            "color": "mint",
            "message": command
        }];

        if (options === undefined) {
            options = {};
        }

        if (inline !== true) {
            message(write, messages);
        }

        const subProcess = childProcess.exec(command, options, (error, stdout, stderr) => {
            if (error) {
                if (stderr === "") {
                    stderr = "no error message retrieve";
                }

                if (inline === true) {
                    messages.push({
                        color: "white",
                        message: "→"
                    });

                    messages.push({
                        color: "red",
                        message: "stderr"
                    });

                    message(write, messages);
                }

                return reject(stderr);
            }

            let response = stdout.toString();

            if (response !== "") {
                if (escape === undefined || escape === true) {
                    response = response.replace("\n", "");
                }

                if (inline === true) {
                    messages.push({
                        color: "white",
                        message: "→"
                    });

                    messages.push({
                        color: "green",
                        message: response
                    });
                } else if (follow === undefined || follow === false) {
                    messages = [{
                        color: "green",
                        message: response
                    }];
                } else {
                    messages = [];
                }

                if (messages.length !== 0) {
                    message(write, messages);
                }
            }

            resolve(response);
        });

        if (follow === true) {
            subProcess.stdout.on('data', function(data) {
                message(write, [{
                    message: data.toString(),
                    color: "green"
                }]);
            });

            subProcess.stderr.on('data', function(data) {
                message(write, [{
                    message: data.toString(),
                    color: "orange"
                }]);
            });
        }
    });
}

module.exports.local = local;

module.exports.remote = function(write, server, command, escape, inline) {
    return local(
        write,
        `ssh -o StrictHostKeyChecking=no -p ${server.port} ${server.user}@${server.host} '${command}'`,
        {},
        escape,
        inline
    );
};
<commit_msg>FIX: use string instead of variable<commit_after>"use strict";

const childProcess = require("child_process"),
    message = require("./logger.js").buildMessage;

function local(write, command, options, escape, inline, follow) {
    return new Promise((resolve, reject) => {
        let messages = [{
            "color": "mint",
            "message": command
        }];

        if (options === undefined) {
            options = {};
        }

        if (inline !== true) {
            message(write, messages);
        }

        const subProcess = childProcess.exec(command, options, (error, stdout, stderr) => {
            if (error) {
                if (stderr === "") {
                    stderr = "no error message retrieve";
                }

                if (inline === true) {
                    messages.push({
                        color: "white",
                        message: "→"
                    });

                    messages.push({
                        color: "red",
                        message: stderr
                    });

                    message(write, messages);
                }

                return reject(stderr);
            }

            let response = stdout.toString();

            if (response !== "") {
                if (escape === undefined || escape === true) {
                    response = response.replace("\n", "");
                }

                if (inline === true) {
                    messages.push({
                        color: "white",
                        message: "→"
                    });

                    messages.push({
                        color: "green",
                        message: response
                    });
                } else if (follow === undefined || follow === false) {
                    messages = [{
                        color: "green",
                        message: response
                    }];
                } else {
                    messages = [];
                }

                if (messages.length !== 0) {
                    message(write, messages);
                }
            }

            resolve(response);
        });

        if (follow === true) {
            subProcess.stdout.on('data', function(data) {
                message(write, [{
                    message: data.toString(),
                    color: "green"
                }]);
            });

            subProcess.stderr.on('data', function(data) {
                message(write, [{
                    message: data.toString(),
                    color: "orange"
                }]);
            });
        }
    });
}

module.exports.local = local;

module.exports.remote = function(write, server, command, escape, inline) {
    return local(
        write,
        `ssh -o StrictHostKeyChecking=no -p ${server.port} ${server.user}@${server.host} '${command}'`,
        {},
        escape,
        inline
    );
};
<|endoftext|>


<commit_before>var GITHUB_USER_DATA = {
  name: "Steve Marsh",
  username: "stevenjmarsh",
  image: "https://avatars0.githubusercontent.com/u/6202447?v=3&s=140"
};

var React = require("react");
var ReactDOM = require("react-dom");

var ProfilePic = React.createClass({
  render: function () {
    return (

    );
  }
});

var ProfileLink = React.createClass({
  render: function () {
    return (

        {this.props.username}

    );
  }
});

var ProfileName = React.createClass({
  render: function () {
    return (

{this.props.name}

    );
  }
});

var Avatar = React.createClass({
  render: function () {
    return (

        <ProfilePic imageUrl={this.props.user.image} />
        <ProfileName name={this.props.user.name}/>
        <ProfileLink username={this.props.user.username}/>

    );
  }
});

ReactDOM.render(<Avatar user={GITHUB_USER_DATA}/>, document.getElementById("app"));
<commit_msg>adding custom link component<commit_after>var GITHUB_USER_DATA = {
  name: "Steve Marsh",
  username: "stevenjmarsh",
  image: "https://avatars0.githubusercontent.com/u/6202447?v=3&s=140"
};

var React = require("react");
var ReactDOM = require("react-dom");

var ProfilePic = React.createClass({
  render: function () {
    return (

    );
  }
});

var Link = React.createClass({
  changeURL: function () {
    window.location.replace(this.props.href);
  },

  render: function () {
    return (

        {this.props.children}

    );
  }
});

var ProfileLink = React.createClass({
  render: function () {
    return (

        <Link href={"https://www.github.com/" + this.props.username}>
          {this.props.username}
        </Link>

    );
  }
});

var ProfileName = React.createClass({
  render: function () {
    return (

{this.props.name}

    );
  }
});

var Avatar = React.createClass({
  render: function () {
    return (

        <ProfilePic imageUrl={this.props.user.image} />
        <ProfileName name={this.props.user.name}/>
        <ProfileLink username={this.props.user.username}/>

    );
  }
});

ReactDOM.render(<Avatar user={GITHUB_USER_DATA}/>, document.getElementById("app"));
<|endoftext|>


<commit_before>
/*
	jCheck is a quick and dumn property testing framework for JavaScript / Node.

*/

const colourise = {
	red    : function (x) {return x},
	yellow : function (x) {return x}
}

const fromStream = ( function () {

	var self = {}

	/*
		-------------------------------- Generators --------------------------------

	*/

	// -------------------------------- numeric --------------------------------

	self.number = function (len) {
		// uniform random number of a given order 'len'.

		const  sign = Math.random() > 0.5? +1: -1
		return sign * Math.random() * Math.pow(10, len)
	}
	self.integer = function (len) {
		// uniform random integer of a given order 'len'.

		return Math.round(self.number(len))
	}

	self.nan    = function (len) {
		return NaN
	}

	// -------------------------------- character --------------------------------

	self.alphabetical = (function () {
		// uppercase and lowecase letters in a string of length 'len'.

		const charset =
			'abcdefghijklmnopqrstuvwxyz' +
			'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

		return function (len) {

			var out = ''

			for (var ith = 0; ith < len; ith++) {
				out += charset.charAt(Math.random * charset.length)
			}

			return out
		}

	})()

	/*
		-------------------------------- Sampler --------------------------------

	*/

	return function (len) {
		// return a random generator.

		const generators = Object.keys(self)
		const ith        = generators[Math.floor(Math.random() * generators.length)]

		return self[ith](len)
	}

} )()

const restOf = function (coll) {

	var out = []

	for (var ith = 0; ith < coll.length; ith++) {
		if (ith !== 0) {
			out = out.concat( coll[ith] )
		}
	}

	return out
}

/*
	The core testing function.
*/

const runTest = function (test, groups, state, testcase, info) {

	for (var groupIth = 0; groupIth < groups.length; groupIth++) {

		var group = groups[groupIth]

		var groupPred  = groups[0]
		var groupProps = restOf(groups)

		var isMatch = groupPred.apply(null, testcase)

		state.casesExamined += 1

		if (!isMatch) {
			continue
		}

		state.testsRun += 1

		/*
			the predicate for this group was true; test each associated
			property.
		*/

		for (var propIth = 0; propIth < groupProps.length; propIth++) {

			var prop    = groupProps[propIth]
			var hasProp = tester(prop, testcase)

			// the result of the predicate was non-boolean.
			if (hasProp !== true && hasProp !== false) {
				var message =
					info + '\n' +
					colourise.red('Failed!') +
					' the property returned a non-logical result\n' +
					'For the test-case '

				throw message
			}

			if (!hasProp) {

				// note the earliest fail.
				state.failsAfter =
					Math.min(state.failsAfter, state.testsRun)

				// store the failed cases.
				state.failsFor =
					state.failsFor.concat([testcase])

				// store the index of the failed properties.

				var failedIndex = {
					group    : groupIth,
					property : propIth,
					summary  : groupIth + ', ' + propIth
				}

				state.failedIndices =
					[state.failedIndices, [failedIndex]]

			}

		}

	}

	return state
}

/*

*/

const yieldCase = function (params) {

	return params.map(function (param) {
		return fromStream()
	})

}

const propertyError = function (testData, state) {

}

const exhaustionWarning = function (testData, state, info) {

	const run      = state.testsRun
	const examined = state.casesExamined

	const message =
		info + colourise.yellow(" Failed!\n") +
		"all " + examined + " test cases were rejected."

	throw message
}

const successMessage = function (states, info) {
	/*

	*/

	const message =
		'passed!'

	console.log(message)
}

const whenTest = function (prop, testcase) {
	// simply call the predicate with the testcase.

	return prop.apply(null, testcase)
}

const stopwatch = function (seconds) {
	/*
		takes a number of seconds, and
		returns a function that returns true if
		called within that timespan after creation.
	*/

	const posixTime = function () {

		return Math.round((new Date).getTime() / 1000.0)
	}

	const genesis = posixTime()

	return function () {

		const lifespan  = posixTime() - genesis
		return lifespan < seconds

	}
}

const validateTest = function (test) {
	/*
		ensure that the test being passed to run
		can be executed properly.
	*/

	// throw an error if any fields are missing.
	;['info', 'params', 'time'].forEach(function (key) {

		if (!test.hasOwnProperty(key)) {
			var message =
				"the property '" + key + "' was missing from the test object."

			throw colourise.red(message)
		}
	})

	// time mustn't be NaN
	if (test.time !== test.time) {

		var message =
			'time must not be NaN.'

		throw colourise.red(message)
	}

	// time definitely mustn't be Infinite
	if (!isFinite(test.time)) {

		var message =
			'time must not be infinite.'

		throw colourise.red(message)
	}

	// time must be positive
	if (test.time < 0) {
		var message =
			'time must be positive.'

		throw colourise.red(message)
	}

	return true
}

/*
	The backend wrapper in which the test is executed.
*/

const executeTest = function (test) {

	validateTest(test)

	// attach the test data to the local environment.

	const info         = test.info
	const params       = test.params
	const time         = test.time
	const whenProperty = test.whenProperty

	const initialState = function () {
		return {
			casesExamined : 0,
			testsRun      : 0,
			failsFor      : [],
			failsAfter    : Infinity,
			failedIndices : []
		}
	}

	// each test subtype has its own state, tester and property group.

	var states       = [initialState()]
	const groupTypes = [whenProperty]
	const testers    = [whenTest]

	var timeLeft = stopwatch(time)

	/*
		execute the tests and collect statistics on the failures.
	*/

	while (timeLeft()) {

		var testcase = yieldCase(params)

		for (var ith = 0; ith < states.length; ith++) {

			var test  = testers[ith]
			var group = groupTypes[ith]
			var state = states[ith]

			runTest(test, group, state, testcase, info)
		}

	}

	// additional data needed to report success or failure.

	const testData = {
		info: info,
		time: time
	}

	/*
		Check that the correct number of tests were run, and
		that none of the tests fail.
	*/

	for (var ith = 0; ith < states.length; ith++) {

		var group = groupTypes[ith]
		var state = states[ith]

		if (group.length > 0 && state.testsRun === 0) {
			/*
				No tests were run for a particular test group.
				Warn the user about this fact.
			*/
			exhaustionWarning(testData, state, info)
		}

		if (state.failsFor.length > 0) {
			/*
				Throw errors for this particular group.
			*/

			propertyError
		}

	}

	successMessage(states, info)
}

/*
	-------------------------------- Grammar --------------------------------

	describe(string)            add a description to a property group. Concatanative property.

	over([string])              the parametres to bind random variables to.
	                            Overriding property.

	over_(string_)              the parametres to bind random variables to.
	                            Overriding property.

	when(Function, [Function])  when a predicate is true, assert that several other
	                            predicates are also true. Concatanative property.

	when_(Function_)            when a predicate is true, assert that several other
	                            predicates are also true. Concatanative property.

	run(number)                 triggers the start of a test, specifies how long the test runs for.
*/

const describe = function (info) {

	var self  = joinTest(this, {
		info : info,
		type : 'describe'
	})

	return self
}

/*
	Bind random variables to test over.

	@param {[string]} strs. An array of strings.
*/

const over = function (strs) {

	var self  = joinTest(this, {
		params 	: strs,
		type   	: 'over'
	})

	return self
}

/*

*/

const over_ = function () {

	const args = Array.prototype.slice.call(arguments)

	var self  = joinTest(this, {
		params 	: args,
		type   	: 'over'
	})

	return self
}

/*
	When a predicate is true of a test-case, ensure several other predicates are true too.

	@param {Function}   pred:  a predicate function. This function tests if a test-case
	    is suitable to be given to a set of properties.

	@param {[Function]} preds: an array of predicate functions. These functions are
	    properties that must hold true for an test-case that matches `pred`.

	@return {object}
*/

const when = function (pred, preds) {

	var self  = joinTest(this, {
		whenProperty : [pred].concat(preds),
		type         : 'when'
	})

	return self
}

/*

*/

const when_ = function () {

	const args = Array.prototype.slice.call(arguments)

	var self  = joinTest(this, {
		whenProperty : args,
		type         : 'when'
	})

	return self
}

/*
	Run a test.

	@param {number} num. The number of seconds testing should continue for.
*/

const run = function (num) {

	var self  = joinTest(this, {
		time : num,
		type : 'run'
	})

	return self
}

const _forallProto = {
	run      : run,

	over     : over,
	over_    : over_,

	when     : when,
	when_    : when_,

	describe : describe
}

/*
	Test if an object is the global 'this' object.
*/

const isGlobalThis = function (obj) {
	return obj.GLOBAL || obj.window
}

/*
	JoinTest

	JoinTest takes the 'this' passed to a grammar method, and some
	new data as its right argument. It then updates i
*/

const joinTest = function (acc, right) {

	if (isGlobalThis(acc)) {
		var acc = Object.create(_forallProto)
	}

	const override = function (key) {
		return function () {

			acc[key] = right[key]
			return acc

		}
	}

	const join = function (key) {
		return function () {

			if (acc[key]) {
				acc[key] = acc[key].concat( [right[key]] )
			} else {
				acc[key] = right[key]
			}

			return acc
		}
	}

	const responses = {
		describe : join('info'),
		over     : override('params'),
		when     : join('whenProperty'),
		run      : function () {

			acc.time = right.time

			executeTest(acc)
		}
	}

	for (type in responses) {

		if (right.type === type) {
			return responses[type]()
		}
	}

}

over_('a', 'b') .

describe('addition is commutative') .
when_(
	function (a, b) {
		return typeof(a) === 'number' && a === a &&
		typeof(b) === 'number' && b === b
	},
	function (a, b) {
		return a + b === b + a
	}
) .

run(1)
<commit_msg>fixed several small bugs.<commit_after>
/*
	jCheck is a quick and dumn property testing framework for JavaScript / Node.

*/

const colourise = {
	red    : function (x) {return x},
	yellow : function (x) {return x}
}

const fromStream = ( function () {

	var self = {}

	/*
		-------------------------------- Generators --------------------------------

	*/

	// -------------------------------- numeric --------------------------------

	self.number = function (len) {
		// uniform random number of a given order 'len'.

		const  sign = Math.random() > 0.5? +1: -1
		return sign * Math.random() * Math.pow(10, len)
	}
	self.integer = function (len) {
		// uniform random integer of a given order 'len'.

		return Math.round(self.number(len))
	}

	self.nan    = function (len) {
		return NaN
	}

	// -------------------------------- character --------------------------------

	self.alphabetical = (function () {
		// uppercase and lowecase letters in a string of length 'len'.

		const charset =
			'abcdefghijklmnopqrstuvwxyz' +
			'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

		return function (len) {

			var out = ''

			for (var ith = 0; ith < len; ith++) {
				out += charset.charAt(Math.random * charset.length)
			}

			return out
		}

	})()

	/*
		-------------------------------- Sampler --------------------------------

	*/

	return function (len) {
		// return a random generator.

		const generators = Object.keys(self)
		const ith        = generators[Math.floor(Math.random() * generators.length)]

		return self[ith](len)
	}

} )()

const restOf = function (coll) {

	var out = []

	for (var ith = 0; ith < coll.length; ith++) {
		if (ith !== 0) {
			out = out.concat( coll[ith] )
		}
	}

	return out
}

/*
	The core testing function.
*/

const runTest = function (test, groups, state, testcase, info) {

	for (var groupIth = 0; groupIth < groups.length; groupIth++) {

		var group = groups[groupIth]

		var groupPred  = groups[0]
		var groupProps = restOf(groups)

		var isMatch = groupPred.apply(null, testcase)

		state.casesExamined += 1

		if (!isMatch) {
			continue
		}

		state.testsRun += 1

		/*
			the predicate for this group was true; test each associated
			property.
		*/

		for (var propIth = 0; propIth < groupProps.length; propIth++) {

			var prop    = groupProps[propIth]
			var hasProp = tester(prop, testcase)

			// the result of the predicate was non-boolean.
			if (hasProp !== true && hasProp !== false) {
				var message =
					info + '\n' +
					colourise.red('Failed!') +
					' the property returned a non-logical result\n' +
					'For the test-case '

				throw message
			}

			if (!hasProp) {

				// note the earliest fail.
				state.failsAfter =
					Math.min(state.failsAfter, state.testsRun)

				// store the failed cases.
				state.failsFor =
					state.failsFor.concat([testcase])

				// store the index of the failed properties.

				var failedIndex = {
					group    : groupIth,
					property : propIth,
					summary  : groupIth + ', ' + propIth
				}

				state.failedIndices =
					[state.failedIndices, [failedIndex]]

			}

		}

	}

	return state
}

/*

*/

const yieldCase = function (params) {

	return params.map(function (param) {
		return fromStream()
	})

}

const propertyError = function (testData, state) {

}

const exhaustionWarning = function (testData, state, info) {

	const run      = state.testsRun
	const examined = state.casesExamined

	const message =
		info + colourise.yellow(" Failed!\n") +
		"all " + examined + " test cases were rejected."

	throw message
}

const successMessage = function (states, info) {
	/*

	*/

	const message =
		'passed!'

	console.log(message)
}

const whenTest = function (prop, testcase) {
	// simply call the predicate with the testcase.

	return prop.apply(null, testcase)
}

const stopwatch = function (seconds) {
	/*
		takes a number of seconds, and
		returns a function that returns true if
		called within that timespan after creation.
	*/

	const posixTime = function () {

		return Math.round((new Date).getTime() / 1000.0)
	}

	const genesis = posixTime()

	return function () {

		const lifespan  = posixTime() - genesis
		return lifespan < seconds

	}
}

const validateTest = function (test) {
	/*
		ensure that the test being passed to run
		can be executed properly.
	*/

	// throw an error if any fields are missing.
	;['info', 'params', 'time'].forEach(function (key) {

		if (!test.hasOwnProperty(key)) {
			var message =
				"the property '" + key + "' was missing from the test object."

			throw colourise.red(message)
		}
	})

	// time mustn't be NaN
	if (test.time !== test.time) {

		var message =
			'time must not be NaN.'

		throw colourise.red(message)
	}

	// time definitely mustn't be Infinite
	if (!isFinite(test.time)) {

		var message =
			'time must not be infinite.'

		throw colourise.red(message)
	}

	// time must be positive
	if (test.time < 0) {
		var message =
			'time must be positive.'

		throw colourise.red(message)
	}

	return true
}

/*
	The backend wrapper in which the test is executed.
*/

const executeTest = function (test) {

	validateTest(test)

	// attach the test data to the local environment.

	const info         = test.info
	const params       = test.params
	const time         = test.time
	const whenProperty = test.whenProperty

	const initialState = function () {
		return {
			casesExamined : 0,
			testsRun      : 0,
			failsFor      : [],
			failsAfter    : Infinity,
			failedIndices : []
		}
	}

	// each test subtype has its own state, tester and property group.

	var states       = [initialState()]
	const groupTypes = [whenProperty]
	const testers    = [whenTest]

	var timeLeft = stopwatch(time)

	/*
		execute the tests and collect statistics on the failures.
	*/

	while (timeLeft()) {

		var testcase = yieldCase(params)

		for (var ith = 0; ith < states.length; ith++) {

			var test  = testers[ith]
			var group = groupTypes[ith]
			var state = states[ith]

			runTest(test, group, state, testcase, info)
		}

	}

	// additional data needed to report success or failure.

	const testData = {
		info: info,
		time: time
	}

	/*
		Check that the correct number of tests were run, and
		that none of the tests fail.
	*/

	for (var ith = 0; ith < states.length; ith++) {

		var group = groupTypes[ith]
		var state = states[ith]

		if (group.length > 0 && state.testsRun === 0) {
			/*
				No tests were run for a particular test group.
				Warn the user about this fact.
			*/
			exhaustionWarning(testData, state, info)
		}

		if (state.failsFor.length > 0) {
			/*
				Throw errors for this particular group.
			*/

			propertyError
		}

	}

	successMessage(states, info)
}

/*
	-------------------------------- Grammar --------------------------------

	describe(string)            add a description to a property group. Concatanative property.

	over([string])              the parametres to bind random variables to.
	                            Overriding property.

	over_(string_)              the parametres to bind random variables to.
	                            Overriding property.

	when(Function, [Function])  when a predicate is true, assert that several other
	                            predicates are also true. Concatanative property.

	when_(Function_)            when a predicate is true, assert that several other
	                            predicates are also true. Concatanative property.

	run(number)                 triggers the start of a test, specifies how long the test runs for.
*/

const describe = function (info) {

	var self  = joinTest(this, {
		info : info,
		type : 'describe'
	})

	return self
}

/*
	Bind random variables to test over.

	@param {[string]} strs. An array of strings.
*/

const over = function (strs) {

	var self  = joinTest(this, {
		params 	: strs,
		type   	: 'over'
	})

	return self
}

/*

*/

const over_ = function () {

	const args = Array.prototype.slice.call(arguments)

	var self  = joinTest(this, {
		params 	: args,
		type   	: 'over'
	})

	return self
}

/*
	When a predicate is true of a test-case, ensure several other predicates are true too.

	@param {Function}   pred:  a predicate function. This function tests if a test-case
	    is suitable to be given to a set of properties.

	@param {[Function]} preds: an array of predicate functions. These functions are
	    properties that must hold true for an test-case that matches `pred`.

	@return {object}
*/

const when = function (pred, preds) {

	var self  = joinTest(this, {
		whenProperty : [pred].concat(preds),
		type         : 'when'
	})

	return self
}

/*

*/

const when_ = function () {

	const args = Array.prototype.slice.call(arguments)

	var self  = joinTest(this, {
		whenProperty : args,
		type         : 'when'
	})

	return self
}

/*
	Run a test.

	@param {number} num. The number of seconds testing should continue for.
*/

const run = function (num) {

	var self  = joinTest(this, {
		time : num,
		type : 'run'
	})

	return self
}

const _forallProto = {
	run      : run,

	over     : over,
	over_    : over_,

	when     : when,
	when_    : when_,

	describe : describe
}

/*
	Test if an object is the global 'this' object.
*/

const isGlobalThis = function (obj) {
	return obj.GLOBAL || obj.window
}

/*
	JoinTest

	JoinTest takes the 'this' passed to a grammar method, and some
	new data as its right argument. It then updates i
*/

const joinTest = function (acc, right) {

	if (isGlobalThis(acc)) {
		var acc = Object.create(_forallProto)
	}

	const override = function (key) {
		return function () {

			acc[key] = right[key]
			return acc

		}
	}

	const join = function (key) {
		return function () {

			if (acc[key]) {
				acc[key] = acc[key].concat( [right[key]] )
			} else {
				acc[key] = right[key]
			}

			return acc
		}
	}

	const responses = {
		describe : join('info'),
		over     : override('params'),
		when     : join('whenProperty'),
		run      : function () {

			acc.time = right.time

			executeTest(acc)
		}
	}

	for (type in responses) {

		if (right.type === type) {
			return responses[type]()
		}
	}

}

over_('a', 'b') .

describe('addition is commutative') .
when_(
	function (a, b) {
		return typeof a === 'number' && a === a &&
		typeof b === 'number' && b === b
	},
	function (a, b) {
		return a + b === b + a
	}
) .

run(1)
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const path = require('path')
const yosay = require('yosay')
const superb = require('superb')
const mkdirp = require('mkdirp')
const ghUser = require('gh-user')
const finepack = require('finepack')
const askName = require('inquirer-npm-name')
const Generator = require('yeoman-generator')

const { capitalizeName, setupDependenciesVersions } = require('./helpers')

const CONST = {
  LINTERS: {
    choose: ['jscs', 'jshint', 'standard']
  },

  TESTING: {
    choose: ['ava', 'jest', 'mocha', 'should', 'tap', 'tape']
  },

  TRANSPILERS: {
    choose: ['coffee-script']
  }
}

module.exports = class extends Generator {
  initializing () {
    this.licenseYear = new Date().getFullYear()
  }

  projectName () {
    this.log(yosay(`Initializing ${superb()} Project`))
    const cb = this.async()

    const promise = askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: str => str.length > 0
    }, this)

    promise
      .then(answer => {
        const name = answer.name
        this.appName = name
        this.camelAppName = _.camelCase(name)
        this.capitalizeName = capitalizeName(this.appName)
        cb()
      })
  }

  setupPath () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        `Your generator must be inside a folder named ${this.appName}\n
        I'll automatically create this folder.`
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  }

  questions () {
    const cb = this.async()

    const promise = this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }])

    promise.then(props => {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      cb()
    })
  }

  userInfo () {
    const cb = this.async()
    const promise = ghUser(this.userLogin)

    promise.then(user => {
      this.userName = user.name
      this.userEmail = user.email
      this.userBlog = user.blog
      this.userUrl = user.html_url
      cb()
    })
  }

  transpilers () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS.choose
    }])

    promise.then(props => {
      CONST.TRANSPILERS.choose
        .forEach(choice => (this[choice] = _.includes(props.transpilers, choice)))
      cb()
    })
  }

  linters () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'linter',
      message: 'Select the linter:',
      choices: CONST.LINTERS.choose
    }])

    promise.then(props => {
      CONST.LINTERS.choose
        .forEach(choice => (this[choice] = _.includes(props.linter, choice)))
      cb()
    })
  }

  testing () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING.choose
    }])

    promise.then(props => {
      CONST.TESTING.choose
        .forEach(choice => (this[choice] = _.includes(props.testing, choice)))
      cb()
    })
  }

  setup () {
    this.fs.copy(
      this.templatePath('_editorconfig'),
      this.destinationPath('.editorconfig')
    )
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    )
    this.fs.copy(
      this.templatePath('_gitattributes'),
      this.destinationPath('.gitattributes')
    )
    this.fs.copy(
      this.templatePath('_npmignore'),
      this.destinationPath('.npmignore')
    )
    this.fs.copy(
      this.templatePath('_npmrc'),
      this.destinationPath('.npmrc')
    )
    this.fs.copy(
      this.templatePath('_travis.yml'),
      this.destinationPath('.travis.yml')
    )
    this.fs.copyTpl(
      this.templatePath('_LICENSE'),
      this.destinationPath('LICENSE'),
      this
    )

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      let cliPackage = this.fs.read(this.templatePath('package/cli.json'))
      cliPackage = _.template(cliPackage)(this)
      cliPackage = JSON.parse(cliPackage)

      this.package = Object.assign({}, this.package, cliPackage)
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.fs.copyTpl(
        this.templatePath('bin/_help.txt'),
        this.destinationPath('bin/help.txt'),
        this
      )
      this.fs.copy(
        this.templatePath('bin/_index.js'),
        this.destinationPath('bin/index.js')
      )
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    this.fs.copy(
      this.templatePath('_bumpedrc'),
      this.destinationPath('.bumpedrc')
    )

    /* TRANSPILERS */

    CONST.TRANSPILERS.choose.forEach(transpiler =>
      (this[transpiler]) && (this.package.dependencies[transpiler] = 'latest'))

    /* TESTING */

    CONST.TESTING.choose.forEach(testing =>
      (this[testing]) && (this.package.devDependencies[testing] = 'latest'))

    let testScript = 'mocha'
    if (this.mocha) {
      this.fs.copy(
        this.templatePath('test/_mocha.opts'),
        this.destinationPath('test/mocha.opts')
      )
    }
    if (this.ava) testScript = 'ava'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test += testScript

    if (this.jest) {
      delete this.package.devDependencies.nyc // nyc is not needed anymore!
      this.package.scripts.coveralls = 'cat ./coverage/lcov.info | coveralls'
      this.package.scripts.test = 'jest --coverage'
      this.package.scripts['test:watch'] = 'jest --watch'
      const jestConfig = this.fs.readJSON(this.templatePath('package/jest.json'))
      this.package = Object.assign({}, this.package, jestConfig)
    }

    /* LINTERS */

    let lintScript = ''

    CONST.LINTERS.choose.forEach(linter => {
      if (this[linter]) {
        this.package.devDependencies[linter] = 'latest'
        lintScript += lintScript === '' ? linter : ' && ' + linter
      }
    })

    if (this.jshint) {
      this.fs.copy(
        this.templatePath('_jshintrc'),
        this.destinationPath('.jshintrc')
      )
    }
    if (this.jscs) {
      this.fs.copy(
        this.templatePath('_jscsrc'),
        this.destinationPath('.jscsrc')
      )
    }

    this.package.scripts.lint = lintScript

    if (this.standard) {
      this.package.devDependencies['prettier-standard'] = 'latest'
      this.package.devDependencies['standard-markdown'] = 'latest'
      this.package.scripts.prelint = 'npm run pretty'
      this.package.scripts.pretty = 'prettier-standard index.js src/**/*.js test/**/*.js bin/**/*.js'

      lintScript = `standard-markdown && ${lintScript}`

      if (this.mocha || this.jest) {
        this.package.standard = { env: [this.mocha ? 'mocha' : 'jest'] }
      }
    }

    this.package.scripts.lint = lintScript

    /* INDEX.JS */

    const indexExtension = this['coffee-script'] ? 'coffee' : 'js'
    this.fs.copy(
      this.templatePath(`_index.${indexExtension}`),
      this.destinationPath('index.js')
    )

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  }

  dependenciesVersion () {
    const cb = this.async()

    setupDependenciesVersions(this.package)
      .then(newPkg => {
        this.package = newPkg
        cb()
      })
  }

  writePackage () {
    const cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, (err, packageFormated) => {
      if (err) cb(err)
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    })
  }

  install () {
    this.installDependencies({ bower: false })
  }
}
<commit_msg>Better pretty command<commit_after>'use strict'

const _ = require('lodash')
const path = require('path')
const yosay = require('yosay')
const superb = require('superb')
const mkdirp = require('mkdirp')
const ghUser = require('gh-user')
const finepack = require('finepack')
const askName = require('inquirer-npm-name')
const Generator = require('yeoman-generator')

const { capitalizeName, setupDependenciesVersions } = require('./helpers')

const CONST = {
  LINTERS: {
    choose: ['jscs', 'jshint', 'standard']
  },

  TESTING: {
    choose: ['ava', 'jest', 'mocha', 'should', 'tap', 'tape']
  },

  TRANSPILERS: {
    choose: ['coffee-script']
  }
}

module.exports = class extends Generator {
  initializing () {
    this.licenseYear = new Date().getFullYear()
  }

  projectName () {
    this.log(yosay(`Initializing ${superb()} Project`))
    const cb = this.async()

    const promise = askName({
      name: 'name',
      message: 'Your project name',
      default: _.kebabCase(path.basename(process.cwd())),
      filter: _.kebabCase,
      validate: str => str.length > 0
    }, this)

    promise
      .then(answer => {
        const name = answer.name
        this.appName = name
        this.camelAppName = _.camelCase(name)
        this.capitalizeName = capitalizeName(this.appName)
        cb()
      })
  }

  setupPath () {
    if (path.basename(this.destinationPath()) !== this.appName) {
      this.log(
        `Your generator must be inside a folder named ${this.appName}\n
        I'll automatically create this folder.`
      )
      mkdirp(this.appName)
      this.destinationRoot(this.destinationPath(this.appName))
    }

    this.readme = this.fs.read(this.templatePath('README/header.md'))
    this.package = this.fs.read(this.templatePath('package/base.json'))
  }

  questions () {
    const cb = this.async()

    const promise = this.prompt([{
      name: 'appDescription',
      message: 'A short description of your project',
      default: "I'm a lazy"
    }, {
      name: 'userLogin',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someone'
    }, {
      name: 'cli',
      message: 'Do you need a CLI ?',
      type: 'confirm',
      default: false
    }])

    promise.then(props => {
      this.appDescription = props.appDescription
      this.userLogin = props.userLogin
      this.cli = props.cli
      cb()
    })
  }

  userInfo () {
    const cb = this.async()
    const promise = ghUser(this.userLogin)

    promise.then(user => {
      this.userName = user.name
      this.userEmail = user.email
      this.userBlog = user.blog
      this.userUrl = user.html_url
      cb()
    })
  }

  transpilers () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'transpilers',
      message: 'Select transpilers:',
      choices: CONST.TRANSPILERS.choose
    }])

    promise.then(props => {
      CONST.TRANSPILERS.choose
        .forEach(choice => (this[choice] = _.includes(props.transpilers, choice)))
      cb()
    })
  }

  linters () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'linter',
      message: 'Select the linter:',
      choices: CONST.LINTERS.choose
    }])

    promise.then(props => {
      CONST.LINTERS.choose
        .forEach(choice => (this[choice] = _.includes(props.linter, choice)))
      cb()
    })
  }

  testing () {
    const cb = this.async()

    const promise = this.prompt([{
      type: 'checkbox',
      name: 'testing',
      message: 'Select testing tools:',
      choices: CONST.TESTING.choose
    }])

    promise.then(props => {
      CONST.TESTING.choose
        .forEach(choice => (this[choice] = _.includes(props.testing, choice)))
      cb()
    })
  }

  setup () {
    this.fs.copy(
      this.templatePath('_editorconfig'),
      this.destinationPath('.editorconfig')
    )
    this.fs.copy(
      this.templatePath('_gitignore'),
      this.destinationPath('.gitignore')
    )
    this.fs.copy(
      this.templatePath('_gitattributes'),
      this.destinationPath('.gitattributes')
    )
    this.fs.copy(
      this.templatePath('_npmignore'),
      this.destinationPath('.npmignore')
    )
    this.fs.copy(
      this.templatePath('_npmrc'),
      this.destinationPath('.npmrc')
    )
    this.fs.copy(
      this.templatePath('_travis.yml'),
      this.destinationPath('.travis.yml')
    )
    this.fs.copyTpl(
      this.templatePath('_LICENSE'),
      this.destinationPath('LICENSE'),
      this
    )

    this.package = _.template(this.package)(this)
    this.package = JSON.parse(this.package)

    if (this.cli) {
      let cliPackage = this.fs.read(this.templatePath('package/cli.json'))
      cliPackage = _.template(cliPackage)(this)
      cliPackage = JSON.parse(cliPackage)

      this.package = Object.assign({}, this.package, cliPackage)
      this.readme += this.fs.read(this.templatePath('README/install/cli.md'))

      this.fs.copyTpl(
        this.templatePath('bin/_help.txt'),
        this.destinationPath('bin/help.txt'),
        this
      )
      this.fs.copy(
        this.templatePath('bin/_index.js'),
        this.destinationPath('bin/index.js')
      )
    } else {
      this.readme += this.fs.read(this.templatePath('README/install/normal.md'))
    }

    this.fs.copy(
      this.templatePath('_bumpedrc'),
      this.destinationPath('.bumpedrc')
    )

    /* TRANSPILERS */

    CONST.TRANSPILERS.choose.forEach(transpiler =>
      (this[transpiler]) && (this.package.dependencies[transpiler] = 'latest'))

    /* TESTING */

    CONST.TESTING.choose.forEach(testing =>
      (this[testing]) && (this.package.devDependencies[testing] = 'latest'))

    let testScript = 'mocha'
    if (this.mocha) {
      this.fs.copy(
        this.templatePath('test/_mocha.opts'),
        this.destinationPath('test/mocha.opts')
      )
    }
    if (this.ava) testScript = 'ava'
    if (this.tape && !this.mocha) testScript = 'tape'
    this.package.scripts.test += testScript

    if (this.jest) {
      delete this.package.devDependencies.nyc // nyc is not needed anymore!
      this.package.scripts.coveralls = 'cat ./coverage/lcov.info | coveralls'
      this.package.scripts.test = 'jest --coverage'
      this.package.scripts['test:watch'] = 'jest --watch'
      const jestConfig = this.fs.readJSON(this.templatePath('package/jest.json'))
      this.package = Object.assign({}, this.package, jestConfig)
    }

    /* LINTERS */

    let lintScript = ''

    CONST.LINTERS.choose.forEach(linter => {
      if (this[linter]) {
        this.package.devDependencies[linter] = 'latest'
        lintScript += lintScript === '' ? linter : ' && ' + linter
      }
    })

    if (this.jshint) {
      this.fs.copy(
        this.templatePath('_jshintrc'),
        this.destinationPath('.jshintrc')
      )
    }
    if (this.jscs) {
      this.fs.copy(
        this.templatePath('_jscsrc'),
        this.destinationPath('.jscsrc')
      )
    }

    this.package.scripts.lint = lintScript

    if (this.standard) {
      this.package.devDependencies['prettier-standard'] = 'latest'
      this.package.devDependencies['standard-markdown'] = 'latest'
      this.package.scripts.prelint = 'npm run pretty'
      this.package.scripts.pretty = 'prettier-standard {core,test,bin}/**/*.js'

      lintScript = `standard-markdown && ${lintScript}`

      if (this.mocha || this.jest) {
        this.package.standard = { env: [this.mocha ? 'mocha' : 'jest'] }
      }
    }

    this.package.scripts.lint = lintScript

    /* INDEX.JS */

    const indexExtension = this['coffee-script'] ? 'coffee' : 'js'
    this.fs.copy(
      this.templatePath(`_index.${indexExtension}`),
      this.destinationPath('index.js')
    )

    /* README */

    this.readme += this.fs.read(this.templatePath('README/body.md'))
    this.readme = _.template(this.readme)(this)
    this.fs.write(this.destinationPath('README.md'), this.readme)
  }

  dependenciesVersion () {
    const cb = this.async()

    setupDependenciesVersions(this.package)
      .then(newPkg => {
        this.package = newPkg
        cb()
      })
  }

  writePackage () {
    const cb = this.async()

    finepack(this.package, {
      validate: false,
      color: false
    }, (err, packageFormated) => {
      if (err) cb(err)
      this.fs.writeJSON(this.destinationPath('package.json'), packageFormated)
      cb()
    })
  }

  install () {
    this.installDependencies({ bower: false })
  }
}
<|endoftext|>


<commit_before>const { CompositeDisposable, Disposable } = require('atom')
const { config } = require('./config')

module.exports = {
	config,

	activate (state) {
		this.disposables = new CompositeDisposable()

		let resolveActivation, rejectActivation
		this.activationPromise = new Promise((resolve, reject) => {
			resolveActivation = resolve
			rejectActivation = reject
		})

		// speedup activation by async initializing
		setImmediate(() => {
			try {
				// actual initialization after atom has loaded
				const SyncSettings = require('./sync-settings')
				this.syncSettings = new SyncSettings(state)

				if (this.busySignal) {
					this.syncSettings.useBusySignal(this.busySignal)
				}
				if (this.locationService) {
					this.syncSettings.useLocationService(this.locationService)
				}

				this.disposables.add(
					atom.commands.add('atom-workspace', 'sync-settings:check-backup', () => this.syncSettings.checkBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:create-backup', () => this.syncSettings.createBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:fork', () => this.syncSettings.fork()),
					atom.commands.add('atom-workspace', 'sync-settings:delete-backup', () => this.syncSettings.deleteBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:backup', () => this.syncSettings.backup()),
					atom.commands.add('atom-workspace', 'sync-settings:restore', () => this.syncSettings.restore()),
					atom.commands.add('atom-workspace', 'sync-settings:view-backup', () => this.syncSettings.viewBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:view-diff', () => this.syncSettings.viewDiff()),
				)
				resolveActivation()
			} catch (err) {
				rejectActivation(err)
			}
		})

		return this.activationPromise
	},

	deactivate () {
		this.disposables.dispose()
	},

	serialize () {},

	busySignalService (busySignal) {
		if (this.syncSettings) {
			this.syncSettings.useBusySignal(busySignal)
		}
		this.busySignal = busySignal
		return new Disposable(() => {
			if (this.syncSettings) {
				this.syncSettings.disposeBusySignal()
			}
			this.busySignal = null
		})
	},

	syncSettingslocationService (locationService) {
		if (this.locationService) {
			require('./utils/notify').multipleLocationServices()
			throw new Error('Sync-Settings: Multiple Location Services')
		}
		if (this.syncSettings) {
			this.syncSettings.useLocationService(locationService)
		}
		this.locationService = locationService
		return new Disposable(() => {
			if (this.syncSettings) {
				this.syncSettings.disposeLocationService()
			}
			this.locationService = null
		})
	},
}
<commit_msg>fix: don't throw on multiple location services<commit_after>const { CompositeDisposable, Disposable } = require('atom')
const { config } = require('./config')

module.exports = {
	config,

	activate (state) {
		this.disposables = new CompositeDisposable()

		let resolveActivation, rejectActivation
		this.activationPromise = new Promise((resolve, reject) => {
			resolveActivation = resolve
			rejectActivation = reject
		})

		// speedup activation by async initializing
		setImmediate(() => {
			try {
				// actual initialization after atom has loaded
				const SyncSettings = require('./sync-settings')
				this.syncSettings = new SyncSettings(state)

				if (this.busySignal) {
					this.syncSettings.useBusySignal(this.busySignal)
				}
				if (this.locationService) {
					this.syncSettings.useLocationService(this.locationService)
				}

				this.disposables.add(
					atom.commands.add('atom-workspace', 'sync-settings:check-backup', () => this.syncSettings.checkBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:create-backup', () => this.syncSettings.createBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:fork', () => this.syncSettings.fork()),
					atom.commands.add('atom-workspace', 'sync-settings:delete-backup', () => this.syncSettings.deleteBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:backup', () => this.syncSettings.backup()),
					atom.commands.add('atom-workspace', 'sync-settings:restore', () => this.syncSettings.restore()),
					atom.commands.add('atom-workspace', 'sync-settings:view-backup', () => this.syncSettings.viewBackup()),
					atom.commands.add('atom-workspace', 'sync-settings:view-diff', () => this.syncSettings.viewDiff()),
				)
				resolveActivation()
			} catch (err) {
				rejectActivation(err)
			}
		})

		return this.activationPromise
	},

	deactivate () {
		this.disposables.dispose()
	},

	serialize () {},

	busySignalService (busySignal) {
		if (this.syncSettings) {
			this.syncSettings.useBusySignal(busySignal)
		}
		this.busySignal = busySignal
		return new Disposable(() => {
			if (this.syncSettings) {
				this.syncSettings.disposeBusySignal()
			}
			this.busySignal = null
		})
	},

	syncSettingslocationService (locationService) {
		if (this.locationService) {
			require('./utils/notify').multipleLocationServices()
			console.error(new Error('Sync-Settings: Multiple Location Services'))
		}
		if (this.syncSettings) {
			this.syncSettings.useLocationService(locationService)
		}
		this.locationService = locationService
		return new Disposable(() => {
			if (this.syncSettings) {
				this.syncSettings.disposeLocationService()
			}
			this.locationService = null
		})
	},
}
<|endoftext|>