<commit_before>(function(module) {
	"use strict";

	var User = module.parent.require('./user'),
		db = module.parent.require('../src/database'),
		meta = module.parent.require('./meta'),
		passport = module.parent.require('passport'),
  		passportGithub = require('passport-github').Strategy,
  		fs = module.parent.require('fs'),
  		path = module.parent.require('path');

	var constants = Object.freeze({
		'name': "GitHub",
		'admin': {
			'icon': 'fa-github'
		}
	});

	var GitHub = {};

	GitHub.getStrategy = function(strategies, callback) {
		if (meta.config['social:github:id'] && meta.config['social:github:secret']) {
			passport.use(new passportGithub({
				clientID: meta.config['social:github:id'],
				clientSecret: meta.config['social:github:secret'],
				callbackURL: module.parent.require('nconf').get('url') + 'auth/github/callback'
			}, function(token, tokenSecret, profile, done) {
				GitHub.login(profile.id, profile.username, profile.emails[0].value, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'github',
				url: '/auth/github',
				callbackURL: '/auth/github/callback',
				icon: 'github',
				scope: 'user:email'
			});

			callback(null, strategies);
		}
	};

	GitHub.login = function(githubID, username, email, callback) {
		if (!email) {
			email = username + '@users.noreply.github.com';
		}

		GitHub.getUidByGitHubID(githubID, function(err, uid) {
			if (err) {
				return callback(err);
			}

			if (uid) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				var success = function(uid) {
					User.setUserField(uid, 'githubid', githubID);
					db.setObjectField('githubid:uid', githubID, uid);
					callback(null, {
						uid: uid
					});
				}

				User.getUidByEmail(email, function(err, uid) {
					if (!uid) {
						User.create(username, undefined, email, function(err, uid) {
							if (err !== null) {
								callback(err);
							} else success(uid);
						});
					} else success(uid); // Existing account -- merge
				});
			}
		});
	}

	GitHub.getUidByGitHubID = function(githubID, callback) {
		db.getObjectField('githubid:uid', githubID, function(err, uid) {
			if (err) {
				callback(err);
			} else {
				callback(null, uid);
			}
		});
	};

	GitHub.addMenuItem = function(custom_header, callback) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	};

	function renderAdmin(req, res, callback) {
		res.render('sso/github/admin', {});
	}

	GitHub.init = function(app, middleware, controllers) {
		app.get('/admin/github', middleware.admin.buildHeader, renderAdmin);
		app.get('/api/admin/github', renderAdmin);
	};

	module.exports = GitHub;
}(module));<commit_msg>lintin<commit_after>(function(module) {
	"use strict";

	var User = module.parent.require('./user'),
		db = module.parent.require('../src/database'),
		meta = module.parent.require('./meta'),
		passport = module.parent.require('passport'),
		passportGithub = require('passport-github').Strategy,
		fs = module.parent.require('fs'),
		path = module.parent.require('path');

	var constants = Object.freeze({
		'name': "GitHub",
		'admin': {
			'icon': 'fa-github'
		}
	});

	var GitHub = {};

	GitHub.getStrategy = function(strategies, callback) {
		if (meta.config['social:github:id'] && meta.config['social:github:secret']) {
			passport.use(new passportGithub({
				clientID: meta.config['social:github:id'],
				clientSecret: meta.config['social:github:secret'],
				callbackURL: module.parent.require('nconf').get('url') + 'auth/github/callback'
			}, function(token, tokenSecret, profile, done) {
				GitHub.login(profile.id, profile.username, profile.emails[0].value, function(err, user) {
					if (err) {
						return done(err);
					}
					done(null, user);
				});
			}));

			strategies.push({
				name: 'github',
				url: '/auth/github',
				callbackURL: '/auth/github/callback',
				icon: 'github',
				scope: 'user:email'
			});

			callback(null, strategies);
		}
	};

	GitHub.login = function(githubID, username, email, callback) {
		if (!email) {
			email = username + '@users.noreply.github.com';
		}

		GitHub.getUidByGitHubID(githubID, function(err, uid) {
			if (err) {
				return callback(err);
			}

			if (uid) {
				// Existing User
				callback(null, {
					uid: uid
				});
			} else {
				// New User
				var success = function(uid) {
					User.setUserField(uid, 'githubid', githubID);
					db.setObjectField('githubid:uid', githubID, uid);
					callback(null, {
						uid: uid
					});
				};

				User.getUidByEmail(email, function(err, uid) {
					if (!uid) {
						User.create(username, undefined, email, function(err, uid) {
							if (err !== null) {
								callback(err);
							} else {
								success(uid);
							}
						});
					} else {
						success(uid); // Existing account -- merge
					}
				});
			}
		});
	};

	GitHub.getUidByGitHubID = function(githubID, callback) {
		db.getObjectField('githubid:uid', githubID, function(err, uid) {
			if (err) {
				callback(err);
			} else {
				callback(null, uid);
			}
		});
	};

	GitHub.addMenuItem = function(custom_header, callback) {
		custom_header.authentication.push({
			"route": constants.admin.route,
			"icon": constants.admin.icon,
			"name": constants.name
		});

		callback(null, custom_header);
	};

	function renderAdmin(req, res, callback) {
		res.render('sso/github/admin', {});
	}

	GitHub.init = function(app, middleware, controllers) {
		app.get('/admin/github', middleware.admin.buildHeader, renderAdmin);
		app.get('/api/admin/github', renderAdmin);
	};

	module.exports = GitHub;
}(module));<|endoftext|>


<commit_before>'use strict';
const assert = require('chai').assert;
const init = require('../.').init;
describe('api', function() {

  describe('account', function() {
    it('account.getminedblocks', function(done){
      var api = init();
      var txlist = api.account.getminedblocks('0x9dd134d14d1e65f84b706d6f205cd5b1cd03a46b');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('account.tokenbalance by name', function(done){
      var api = init();

      var supply = api.account.tokenbalance(
        '0x0a869d79a7052c7f1b55a8ebabbea3420f0d1e13',
        'TheDAO');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('account.tokenbalance by address', function(done){
      var api = init();
      var supply = api.account.tokenbalance('0xe04f27eb70e025b78871a2ad7eabe85e61212761', false, '0x57d90b64a1a57749b0f932f1a3395792e12e7055');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('account.txlist', function(done){
      var api = init();
      var txlist = api.account.txlist('0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('account.txlistinternal', function(done){
      var api = init();
      var txlist = api.account.txlistinternal('0x40eb908387324f2b575b4879cd9d7188f69c8fc9d87c901b9e2daaea4b442170');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('account.balance', function(done){
      var api = init();
      var balance = api.account.balance('0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
      balance.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('account.balance multi', function(done){
      var api = init();
      var balance = api.account.balance(['0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae']);
      balance.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });
  describe('stats', function() {
    it('stats.ethsupply', function(done){
      var api = init();
      var supply = api.stats.ethsupply();
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('stats.tokensupply by tokenname', function(done){
      var api = init();
      var supply = api.stats.tokensupply('MKR');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('stats.tokensupply by address', function(done){
      var api = init();
      var supply = api.stats.tokensupply(null, '0x57d90b64a1a57749b0f932f1a3395792e12e7055');
      supply.then(function(res){
        assert.ok(res);
        done();
      }).catch(done);
    });

    it('stats.ethprice', function(done){
      var api = init();
      var price = api.stats.ethprice();
      price.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });

  it('block.getblockreward', function(done){
    var api = init();
    var blockreward = api.block.getblockreward();
    blockreward.then(function(res){
      assert.ok(res);
      done();
    });
  });

  it('transaction.getstatus', function(done){
    var api = init();
    var status = api.transaction.getstatus('0x15f8e5ea1079d9a0bb04a4c58ae5fe7654b5b2b4463375ff7ffb490aa0032f3a');
    status.then(function(res){
      assert.ok(res);
      done();
    });
  });

  it('contract.getabi', function(done){
    var api = init();
    var abi = api.contract.getabi('0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413');
    abi.then(function(res){
      assert.ok(res);
      done();
    });
  });

  describe('proxy', function() {
    it('proxy.eth_blockNumber', function(done){
      var api = init();
      var res = api.proxy.eth_blockNumber();
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getBlockByNumber', function(done){
      var api = init();
      var res = api.proxy.eth_getBlockByNumber('0x10d4f', true);
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getUncleByBlockNumberAndIndex', function(done){
      var api = init();
      var res = api.proxy.eth_getUncleByBlockNumberAndIndex('0x210A9B', '0x0');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getBlockTransactionCountByNumber', function(done){
      var api = init();
      var res = api.proxy.eth_getBlockTransactionCountByNumber('0x10FB78');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionByHash', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionByHash('0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionByBlockNumberAndIndex', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionByBlockNumberAndIndex('0x10d4f', '0x0');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionCount', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionCount('0x2910543af39aba0cd09dbb2d50200b3e800a63d2', 'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_sendRawTransaction', function(done){
      var api = init();
      var res = api.proxy.eth_sendRawTransaction('0xf904808000831cfde080');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionReceipt', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionReceipt('0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_call', function(done){
      var api = init();
      var res = api.proxy.eth_call('0xAEEF46DB4855E25702F8237E8f403FddcaF931C0', '0x70a08231000000000000000000000000e16359506c028e51f16be38986ec5746251e9724', 'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getCode', function(done){
      var api = init();
      var res = api.proxy.eth_getCode('0xf75e354c5edc8efed9b59ee9f67a80845ade7d0c',  'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getStorageAt', function(done){
      var api = init();
      var res = api.proxy.eth_getStorageAt('0x6e03d9cce9d60f3e9f2597e13cd4c54c55330cfd', '0x0',  'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_gasPrice', function(done){
      var api = init();
      var res = api.proxy.eth_gasPrice();
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_estimateGas', function(done){
      var api = init();
      var res = api.proxy.eth_estimateGas(
        '0xf0160428a8552ac9bb7e050d90eeade4ddd52843',
        '0xff22',
        '0x051da038cc',
        '0xffffff'
      );
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });
});
<commit_msg>(churn): removed prefixes<commit_after>'use strict';
const assert = require('chai').assert;
const init = require('../.').init;
describe('api', function() {

  describe('account', function() {
    it('getminedblocks', function(done){
      var api = init();
      var txlist = api.account.getminedblocks('0x9dd134d14d1e65f84b706d6f205cd5b1cd03a46b');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('tokenbalance by name', function(done){
      var api = init();

      var supply = api.account.tokenbalance(
        '0x0a869d79a7052c7f1b55a8ebabbea3420f0d1e13',
        'TheDAO');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('tokenbalance by address', function(done){
      var api = init();
      var supply = api.account.tokenbalance('0xe04f27eb70e025b78871a2ad7eabe85e61212761', false, '0x57d90b64a1a57749b0f932f1a3395792e12e7055');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('txlist', function(done){
      var api = init();
      var txlist = api.account.txlist('0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('txlistinternal', function(done){
      var api = init();
      var txlist = api.account.txlistinternal('0x40eb908387324f2b575b4879cd9d7188f69c8fc9d87c901b9e2daaea4b442170');
      txlist.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('balance', function(done){
      var api = init();
      var balance = api.account.balance('0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
      balance.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('balance multi', function(done){
      var api = init();
      var balance = api.account.balance(['0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae']);
      balance.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });
  describe('stats', function() {
    it('ethsupply', function(done){
      var api = init();
      var supply = api.stats.ethsupply();
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('tokensupply by tokenname', function(done){
      var api = init();
      var supply = api.stats.tokensupply('MKR');
      supply.then(function(res){
        assert.ok(res);
        done();
      });
    });
    it('tokensupply by address', function(done){
      var api = init();
      var supply = api.stats.tokensupply(null, '0x57d90b64a1a57749b0f932f1a3395792e12e7055');
      supply.then(function(res){
        assert.ok(res);
        done();
      }).catch(done);
    });

    it('ethprice', function(done){
      var api = init();
      var price = api.stats.ethprice();
      price.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });

  it('block.getblockreward', function(done){
    var api = init();
    var blockreward = api.block.getblockreward();
    blockreward.then(function(res){
      assert.ok(res);
      done();
    });
  });

  it('transaction.getstatus', function(done){
    var api = init();
    var status = api.transaction.getstatus('0x15f8e5ea1079d9a0bb04a4c58ae5fe7654b5b2b4463375ff7ffb490aa0032f3a');
    status.then(function(res){
      assert.ok(res);
      done();
    });
  });

  it('contract.getabi', function(done){
    var api = init();
    var abi = api.contract.getabi('0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413');
    abi.then(function(res){
      assert.ok(res);
      done();
    });
  });

  describe('proxy', function() {
    it('proxy.eth_blockNumber', function(done){
      var api = init();
      var res = api.proxy.eth_blockNumber();
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getBlockByNumber', function(done){
      var api = init();
      var res = api.proxy.eth_getBlockByNumber('0x10d4f', true);
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getUncleByBlockNumberAndIndex', function(done){
      var api = init();
      var res = api.proxy.eth_getUncleByBlockNumberAndIndex('0x210A9B', '0x0');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getBlockTransactionCountByNumber', function(done){
      var api = init();
      var res = api.proxy.eth_getBlockTransactionCountByNumber('0x10FB78');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionByHash', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionByHash('0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionByBlockNumberAndIndex', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionByBlockNumberAndIndex('0x10d4f', '0x0');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionCount', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionCount('0x2910543af39aba0cd09dbb2d50200b3e800a63d2', 'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_sendRawTransaction', function(done){
      var api = init();
      var res = api.proxy.eth_sendRawTransaction('0xf904808000831cfde080');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getTransactionReceipt', function(done){
      var api = init();
      var res = api.proxy.eth_getTransactionReceipt('0x1e2910a262b1008d0616a0beb24c1a491d78771baa54a33e66065e03b1f46bc1');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_call', function(done){
      var api = init();
      var res = api.proxy.eth_call('0xAEEF46DB4855E25702F8237E8f403FddcaF931C0', '0x70a08231000000000000000000000000e16359506c028e51f16be38986ec5746251e9724', 'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getCode', function(done){
      var api = init();
      var res = api.proxy.eth_getCode('0xf75e354c5edc8efed9b59ee9f67a80845ade7d0c',  'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_getStorageAt', function(done){
      var api = init();
      var res = api.proxy.eth_getStorageAt('0x6e03d9cce9d60f3e9f2597e13cd4c54c55330cfd', '0x0',  'latest');
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_gasPrice', function(done){
      var api = init();
      var res = api.proxy.eth_gasPrice();
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });

    it('proxy.eth_estimateGas', function(done){
      var api = init();
      var res = api.proxy.eth_estimateGas(
        '0xf0160428a8552ac9bb7e050d90eeade4ddd52843',
        '0xff22',
        '0x051da038cc',
        '0xffffff'
      );
      res.then(function(res){
        assert.ok(res);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>(function(module) {
    "use strict";
    var Imgur = {},
        post = '

',
        galleries = '

'
    var	embedpost = /.+<\/a>/g;
    var	embedgallery = /.+<\/a>/g;

    Imgur.parse = function(data, callback) {

        if (!data || !data.postData || !data.postData.content) {
            return callback(null, data);
        }
        if (data.postData.content.match(post)) {
            data.postData.content = data.postData.content.replace(post, embedpost);
        }
        if (data.postData.content.match(galleries)) {
            data.postData.content = data.postData.content.replace(galleries, embedgallery);
        }

        callback(null, data);
    };

    module.exports = Imgur;
}(module));
<commit_msg>0.0.1.0<commit_after>(function(module) {
    "use strict";
    var Imgur = {},
        post = '

',
        galleries = '

'
    var	embedpost = /.+<\/a>/g;
    var	embedgallery = /.+<\/a>/g;

    Imgur.parse = function(data, callback) {

        if (!data || !data.postData || !data.postData.content) {
            return callback(null, data);
        }
        if (data.postData.content.match(embedpost)) {
            data.postData.content = data.postData.content.replace(embedpost, post);
        }
        if (data.postData.content.match(embedgallery)) {
            data.postData.content = data.postData.content.replace(embedgallery, galleries);
        }

        callback(null, data);
    };

    module.exports = Imgur;
}(module));
<|endoftext|>


<commit_before>/* globals describe, it */
const assert = require("assert");
const Mojisyu = require("../src/mojisyu");
const defalutMojisyu = require("../src/default_mojisyu");

describe("Mojisyu", () => {
    const mZE = new Mojisyu("ZE", defalutMojisyu.ZE);
    const mHS = new Mojisyu("HS", defalutMojisyu.HS);

    it("range type", () => {
        assert.ok(mZE.types.range, "range");
        assert.ok(!mZE.types.regexp, "regexp");
    });

    it("range property", () => {
        assert.ok(mZE.props.start);
        assert.ok(mZE.props.end);
        assert.ok(!mZE.props.regexp);
    });

    it("regexp type", () => {
        assert.ok(!mHS.types.range, "range");
        assert.ok(mHS.types.patterns, "patterns");
    });
});
<commit_msg>タイポを修正<commit_after>/* globals describe, it */
const assert = require("assert");
const Mojisyu = require("../src/mojisyu");
const defaultMojisyu = require("../src/default_mojisyu");

describe("Mojisyu", () => {
    const mZE = new Mojisyu("ZE", defaultMojisyu.ZE);
    const mHS = new Mojisyu("HS", defaultMojisyu.HS);

    it("range type", () => {
        assert.ok(mZE.types.range, "range");
        assert.ok(!mZE.types.regexp, "regexp");
    });

    it("range property", () => {
        assert.ok(mZE.props.start);
        assert.ok(mZE.props.end);
        assert.ok(!mZE.props.regexp);
    });

    it("regexp type", () => {
        assert.ok(!mHS.types.range, "range");
        assert.ok(mHS.types.patterns, "patterns");
    });
});
<|endoftext|>


<commit_before>'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const config = require('./config');
const pug = require('./pug')(config);

const helpers = require('./helpers.js');

const sectionPath = path.join('includes', 'section.pug');
const sectionTemplate = pug.compileFile(sectionPath);

const templateWrapper = template => (options, metadata) => {
  const locals = _.assign({}, metadata, options, helpers);
  return template(locals);
};

const layouts = {

  section: (type) => {
    const typeConfiguration = config.types[type];
    assert.ok(typeConfiguration, 'Missing config.types[' + type + ']');
    assert.ok(typeConfiguration.layout,
              'Missing config.types[' + type + '].layout');

    // Create a copy of the layout from the configuration, to make sure we are
    // not mutating the config
    const layout = _.cloneDeep(typeConfiguration.layout);

    // Find all sections used in the configuration
    const sections = layout.sections;
    var typesInConfiguration = _.flatten(
      Object.keys(sections).map((sectionName) => {
        var section = sections[sectionName];
        return section.rows.map((row) => {
          return row.type;
        });
      })
    );

    // Add the default single type and use only unique values
    var rowTypes = _.uniq(_.concat(['simple'], typesInConfiguration))
    .filter((rowType) => {
      return !!rowType; // Filter out undefined
    });

    // For every type a template should be compiled
    const rowTypeTemplates = {};
    rowTypes.forEach((rowType) => {
      try {
        var relativePath = path.join('includes', 'row-types', rowType);
        rowTypeTemplates[rowType] = pug.compileFile(relativePath);
      } catch(err) {
        console.error('Error compiling asset row type template: ', err);
      }
    });

    Object.keys(layout.sections).forEach((sectionName) => {
      var section = layout.sections[sectionName];

      section.hasValues = (options, metadata) => {
        return section.rows.reduce((result, row) => {
          return result || row.hasValue(options, metadata);
        }, false);
      };

      section.rows.forEach((row) => {
        // Assume a simple row if type is not defined
        if (!row.type) {
          row.type = 'simple';
        }

        // Compile any single template for later use & inject the helpers using
        // the template wrapper
        if(typeof(row.template) === 'string') {
          const compiledTemplate = pug.compile(row.template);
          row.template = templateWrapper(compiledTemplate);
        }

        // Compile multiple templates for later use & inject the helpers using
        // the template wrapper
        if(typeof(row.templates) === 'object') {
          row.templates = Object.keys(row.templates)
          .reduce((result, t) => {
            const template = row.templates[t];
            const compiledTemplate = pug.compile(template);
            result[t] = templateWrapper(compiledTemplate);
            return result;
          }, {});
        }

        // Defining a render method on the row
        row.render = (options, metadata) => {
          if(row.type in rowTypeTemplates) {
            return rowTypeTemplates[row.type]({
              row: row,
              options: options,
              metadata: metadata,
              helpers: helpers
            });
          } else {
            throw new Error('Missing a template for row type: ' + row.type);
          }
        };

        row.hasValue = (options, metadata) => {
          // If the rendered version of the row is different when given the
          // metadata, then we assume the row has a value.
          let withMetadata = row.render(options, metadata);
          let withoutMetadata;
          try {
            withoutMetadata = row.render(options, {});
          } catch(err) {
            throw new Error('Make sure the layout renders without metadata:\n' +
                            err.message);
          }
          return withMetadata !== withoutMetadata;
        };
      });
    });

    return (options) => {
      // Returns a function that renders the asset layout.
      return (sectionName, metadata) => {
        if(!sectionName || !(sectionName in layout.sections)) {
          throw new Error('Section named "' + sectionName + '" not configured');
        }
        // Returns the markup for the layout, rendering each of the sections.
        return sectionTemplate({
          section: layout.sections[sectionName],
          options: options,
          metadata: metadata
        });
      };
    };
  }
};

module.exports = layouts;
<commit_msg>Lookup and calling the template on two seperate lines<commit_after>'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const config = require('./config');
const pug = require('./pug')(config);

const helpers = require('./helpers.js');

const sectionPath = path.join('includes', 'section.pug');
const sectionTemplate = pug.compileFile(sectionPath);

const templateWrapper = template => (options, metadata) => {
  const locals = _.assign({}, metadata, options, helpers);
  return template(locals);
};

const layouts = {

  section: (type) => {
    const typeConfiguration = config.types[type];
    assert.ok(typeConfiguration, 'Missing config.types[' + type + ']');
    assert.ok(typeConfiguration.layout,
              'Missing config.types[' + type + '].layout');

    // Create a copy of the layout from the configuration, to make sure we are
    // not mutating the config
    const layout = _.cloneDeep(typeConfiguration.layout);

    // Find all sections used in the configuration
    const sections = layout.sections;
    var typesInConfiguration = _.flatten(
      Object.keys(sections).map((sectionName) => {
        var section = sections[sectionName];
        return section.rows.map((row) => {
          return row.type;
        });
      })
    );

    // Add the default single type and use only unique values
    var rowTypes = _.uniq(_.concat(['simple'], typesInConfiguration))
    .filter((rowType) => {
      return !!rowType; // Filter out undefined
    });

    // For every type a template should be compiled
    const rowTypeTemplates = {};
    rowTypes.forEach((rowType) => {
      try {
        var relativePath = path.join('includes', 'row-types', rowType);
        rowTypeTemplates[rowType] = pug.compileFile(relativePath);
      } catch(err) {
        console.error('Error compiling asset row type template: ', err);
      }
    });

    Object.keys(layout.sections).forEach((sectionName) => {
      var section = layout.sections[sectionName];

      section.hasValues = (options, metadata) => {
        return section.rows.reduce((result, row) => {
          return result || row.hasValue(options, metadata);
        }, false);
      };

      section.rows.forEach((row) => {
        // Assume a simple row if type is not defined
        if (!row.type) {
          row.type = 'simple';
        }

        // Compile any single template for later use & inject the helpers using
        // the template wrapper
        if(typeof(row.template) === 'string') {
          const compiledTemplate = pug.compile(row.template);
          row.template = templateWrapper(compiledTemplate);
        }

        // Compile multiple templates for later use & inject the helpers using
        // the template wrapper
        if(typeof(row.templates) === 'object') {
          row.templates = Object.keys(row.templates)
          .reduce((result, t) => {
            const template = row.templates[t];
            const compiledTemplate = pug.compile(template);
            result[t] = templateWrapper(compiledTemplate);
            return result;
          }, {});
        }

        // Defining a render method on the row
        row.render = (options, metadata) => {
          if(row.type in rowTypeTemplates) {
            const template = rowTypeTemplates[row.type];
            // Render the template
            return template({
              row: row,
              options: options,
              metadata: metadata,
              helpers: helpers
            });
          } else {
            throw new Error('Missing a template for row type: ' + row.type);
          }
        };

        row.hasValue = (options, metadata) => {
          // If the rendered version of the row is different when given the
          // metadata, then we assume the row has a value.
          let withMetadata = row.render(options, metadata);
          let withoutMetadata;
          try {
            withoutMetadata = row.render(options, {});
          } catch(err) {
            throw new Error('Make sure the layout renders without metadata:\n' +
                            err.message);
          }
          return withMetadata !== withoutMetadata;
        };
      });
    });

    return (options) => {
      // Returns a function that renders the asset layout.
      return (sectionName, metadata) => {
        if(!sectionName || !(sectionName in layout.sections)) {
          throw new Error('Section named "' + sectionName + '" not configured');
        }
        // Returns the markup for the layout, rendering each of the sections.
        return sectionTemplate({
          section: layout.sections[sectionName],
          options: options,
          metadata: metadata
        });
      };
    };
  }
};

module.exports = layouts;
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2013 LevelUP contributors
 * See list at <https://github.com/rvagg/node-levelup#contributing>
 * MIT +no-false-attribs License
 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE>
 */

var EventEmitter   = require('events').EventEmitter
  , inherits       = require('util').inherits
  , extend         = require('xtend')
  , prr            = require('prr')
  , DeferredLevelDOWN = require('deferred-leveldown')

  , errors         = require('./errors')
  , ReadStream     = require('./read-stream')
  , WriteStream    = require('./write-stream')
  , util           = require('./util')
  , Batch          = require('./batch')

  , getOptions     = util.getOptions
  , defaultOptions = util.defaultOptions
  , getLevelDOWN   = util.getLevelDOWN
  , dispatchError  = util.dispatchError

function getCallback (options, callback) {
  return typeof options == 'function' ? options : callback
}

// Possible LevelUP#_status values:
//  - 'new'     - newly created, not opened or closed
//  - 'opening' - waiting for the database to be opened, post open()
//  - 'open'    - successfully opened the database, available for use
//  - 'closing' - waiting for the database to be closed, post close()
//  - 'closed'  - database has been successfully closed, should not be
//                 used except for another open() operation

function LevelUP (location, options, callback) {
  if (!(this instanceof LevelUP))
    return new LevelUP(location, options, callback)

  var error

  EventEmitter.call(this)
  this.setMaxListeners(Infinity)

  if (typeof options == 'function') {
    callback = options
    options  = {}
  }

  if (typeof location != 'string') {
    error = new errors.InitializationError(
        'Must provide a location for the database')
    if (callback) {
      process.nextTick(function () {
        callback(error)
      })
      return
    }
    throw error
  }

  options = getOptions(this, options)
  this.options = extend(defaultOptions, options)
  this._status = 'new'
  // set this.location as enumerable but not configurable or writable
  prr(this, 'location', location, 'e')

  this.open(callback)
}

inherits(LevelUP, EventEmitter)

LevelUP.prototype.open = function (callback) {
  var self = this
    , dbFactory
    , db

  if (this.isOpen()) {
    if (callback)
      process.nextTick(function () { callback(null, self) })
    return this
  }

  if (this._isOpening()) {
    return callback && this.once(
        'open'
      , function () { callback(null, self) }
    )
  }

  this.emit('opening')

  this._status = 'opening'
  this.db = new DeferredLevelDOWN(this.location)

  dbFactory = this.options.db || getLevelDOWN()
  db        = dbFactory(this.location)

  db.open(this.options, function (err) {
    if (err) {
      err = new errors.OpenError(err)
      return dispatchError(self, err, callback)
    } else {
      self.db.setDb(db)
      self.db = db
      self._status = 'open'
      if (callback)
        callback(null, self)
      self.emit('open')
      self.emit('ready')
    }
  })
}

LevelUP.prototype.close = function (callback) {
  var self = this

  if (this.isOpen()) {
    this._status = 'closing'
    this.db.close(function () {
      self._status = 'closed'
      self.emit('closed')
      if (callback)
        callback.apply(null, arguments)
    })
    this.emit('closing')
    this.db = null
  } else if (this._status == 'closed' && callback) {
    return process.nextTick(callback)
  } else if (this._status == 'closing' && callback) {
    this.once('closed', callback)
  } else if (this._isOpening()) {
    this.once('open', function () {
      self.close(callback)
    })
  }
}

LevelUP.prototype.isOpen = function () {
  return this._status == 'open'
}

LevelUP.prototype._isOpening = function () {
  return this._status == 'opening'
}

LevelUP.prototype.isClosed = function () {
  return (/^clos/).test(this._status)
}

LevelUP.prototype.get = function (key_, options, callback) {
  var self = this
    , key
    , err

  callback = getCallback(options, callback)

  if (typeof callback != 'function') {
    err = new errors.ReadError('get() requires key and callback arguments')
    return dispatchError(this, err)
  }

  if (!this._isOpening() && !this.isOpen()) {
    err = new errors.ReadError('Database is not open')
    return dispatchError(this, err, callback)
  }

  options = util.getOptions(this, options)
  key = util.encodeKey(key_, options)

  options.asBuffer = util.isValueAsBuffer(options)

  this.db.get(key, options, function (err, value) {
    if (err) {
      if ((/notfound/i).test(err)) {
        err = new errors.NotFoundError(
            'Key not found in database [' + key_ + ']', err)
      } else {
        err = new errors.ReadError(err)
      }
      return dispatchError(self, err, callback)
    }
    if (callback) {
      try {
        value = util.decodeValue(value, options)
      } catch (e) {
        return callback(new errors.EncodingError(e))
      }
      callback(null, value)
    }
  })
}

LevelUP.prototype.put = function (key_, value_, options, callback) {
  var self = this
    , err
    , key
    , value

  callback = getCallback(options, callback)

  if (key_ === null || key_ === undefined
        || value_ === null || value_ === undefined) {
    err = new errors.WriteError('put() requires key and value arguments')
    return dispatchError(this, err, callback)
  }

  if (!this._isOpening() && !this.isOpen()) {
    err = new errors.WriteError('Database is not open')
    return dispatchError(this, err, callback)
  }

  options = getOptions(this, options)
  key     = util.encodeKey(key_, options)
  value   = util.encodeValue(value_, options)

  this.db.put(key, value, options, function (err) {
    if (err) {
      err = new errors.WriteError(err)
      return dispatchError(self, err, callback)
    } else {
      self.emit('put', key_, value_)
      if (callback)
        callback()
    }
  })
}

LevelUP.prototype.del = function (key_, options, callback) {
  var self = this
    , err
    , key

  callback = getCallback(options, callback)

  if (key_ === null || key_ === undefined) {
    err = new errors.WriteError('del() requires a key argument')
    return dispatchError(this, err, callback)
  }

  if (!this._isOpening() && !this.isOpen()) {
    err = new errors.WriteError('Database is not open')
    return dispatchError(this, err, callback)
  }

  options = getOptions(this, options)
  key     = util.encodeKey(key_, options)

  this.db.del(key, options, function (err) {
    if (err) {
      err = new errors.WriteError(err)
      return dispatchError(self, err, callback)
    } else {
      self.emit('del', key_)
      if (callback)
        callback()
    }
  })
}

LevelUP.prototype.batch = function (arr_, options, callback) {
  var self = this
    , keyEnc
    , valueEnc
    , err
    , arr

  if (!arguments.length)
    return new Batch(this)

  callback = getCallback(options, callback)

  if (!Array.isArray(arr_)) {
    err = new errors.WriteError('batch() requires an array argument')
    return dispatchError(this, err, callback)
  }

  if (!this._isOpening() && !this.isOpen()) {
    err = new errors.WriteError('Database is not open')
    return dispatchError(this, err, callback)
  }

  options  = getOptions(this, options)
  keyEnc   = options.keyEncoding
  valueEnc = options.valueEncoding

  arr = arr_.map(function (e) {
    if (e.type === undefined || e.key === undefined)
      return {}

    // inherit encoding
    var kEnc = e.keyEncoding || keyEnc
      , vEnc = e.valueEncoding || e.encoding || valueEnc
      , o

    // If we're not dealing with plain utf8 strings or plain
    // Buffers then we have to do some work on the array to
    // encode the keys and/or values. This includes JSON types.

    if (kEnc != 'utf8' && kEnc != 'binary'
        || vEnc != 'utf8' && vEnc != 'binary') {
      o = {
          type: e.type
        , key: util.encodeKey(e.key, options, e)
      }

      if (e.value !== undefined)
        o.value = util.encodeValue(e.value, options, e)

      return o
    } else {
      return e
    }
  })

  this.db.batch(arr, options, function (err) {
    if (err) {
      err = new errors.WriteError(err)
      return dispatchError(self, err, callback)
    } else {
      self.emit('batch', arr_)
      if (callback)
        callback()
    }
  })
}

// DEPRECATED: prefer accessing LevelDOWN for this: db.db.approximateSize()
LevelUP.prototype.approximateSize = function (start_, end_, callback) {
  var self = this
    , err
    , start
    , end

  if (start_ === null || start_ === undefined
        || end_ === null || end_ === undefined
        || typeof callback != 'function') {
    err = new errors.ReadError('approximateSize() requires start, end and callback arguments')
    return dispatchError(this, err, callback)
  }

  start = util.encodeKey(start_, this.options)
  end   = util.encodeKey(end_, this.options)

  if (!this._isOpening() && !this.isOpen()) {
    err = new errors.WriteError('Database is not open')
    return dispatchError(this, err, callback)
  }

  this.db.approximateSize(start, end, function (err, size) {
    if (err) {
      err = new errors.OpenError(err)
      return dispatchError(self, err, callback)
    } else if (callback) {
      callback(null, size)
    }
  })
}

LevelUP.prototype.readStream =
LevelUP.prototype.createReadStream = function (options) {
  var self = this
  options = extend(this.options, options)
  return new ReadStream(
      options
    , this
    , function (options) {
        return self.db.iterator(options)
      }
  )
}

LevelUP.prototype.keyStream =
LevelUP.prototype.createKeyStream = function (options) {
  return this.createReadStream(extend(options, { keys: true, values: false }))
}

LevelUP.prototype.valueStream =
LevelUP.prototype.createValueStream = function (options) {
  return this.createReadStream(extend(options, { keys: false, values: true }))
}

LevelUP.prototype.writeStream =
LevelUP.prototype.createWriteStream = function (options) {
  return new WriteStream(extend(options), this)
}

LevelUP.prototype.toString = function () {
  return 'LevelUP'
}

function utilStatic (name) {
  return function (location, callback) {
    getLevelDOWN()[name](location, callback || function () {})
  }
}

module.exports         = LevelUP
module.exports.copy    = util.copy
// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').destroy()
module.exports.destroy = utilStatic('destroy')
// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').repair()
module.exports.repair  = utilStatic('repair')
<commit_msg>style tweakages<commit_after>/* Copyright (c) 2012-2013 LevelUP contributors
 * See list at <https://github.com/rvagg/node-levelup#contributing>
 * MIT +no-false-attribs License
 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE>
 */

var EventEmitter   = require('events').EventEmitter
  , inherits       = require('util').inherits
  , extend         = require('xtend')
  , prr            = require('prr')
  , DeferredLevelDOWN = require('deferred-leveldown')

  , errors         = require('./errors')
  , ReadStream     = require('./read-stream')
  , WriteStream    = require('./write-stream')
  , util           = require('./util')
  , Batch          = require('./batch')

  , getOptions     = util.getOptions
  , defaultOptions = util.defaultOptions
  , getLevelDOWN   = util.getLevelDOWN
  , dispatchError  = util.dispatchError

function getCallback (options, callback) {
  return typeof options == 'function' ? options : callback
}

// Possible LevelUP#_status values:
//  - 'new'     - newly created, not opened or closed
//  - 'opening' - waiting for the database to be opened, post open()
//  - 'open'    - successfully opened the database, available for use
//  - 'closing' - waiting for the database to be closed, post close()
//  - 'closed'  - database has been successfully closed, should not be
//                 used except for another open() operation

function LevelUP (location, options, callback) {
  if (!(this instanceof LevelUP))
    return new LevelUP(location, options, callback)

  var error

  EventEmitter.call(this)
  this.setMaxListeners(Infinity)

  if (typeof options == 'function') {
    callback = options
    options  = {}
  }

  if (typeof location != 'string') {
    error = new errors.InitializationError(
        'Must provide a location for the database')
    if (callback) {
      return process.nextTick(function () {
        callback(error)
      })
    }
    throw error
  }

  options      = getOptions(this, options)
  this.options = extend(defaultOptions, options)
  this._status = 'new'
  // set this.location as enumerable but not configurable or writable
  prr(this, 'location', location, 'e')

  this.open(callback)
}

inherits(LevelUP, EventEmitter)

LevelUP.prototype.open = function (callback) {
  var self = this
    , dbFactory
    , db

  if (this.isOpen()) {
    if (callback)
      process.nextTick(function () { callback(null, self) })
    return this
  }

  if (this._isOpening()) {
    return callback && this.once(
        'open'
      , function () { callback(null, self) }
    )
  }

  this.emit('opening')

  this._status = 'opening'
  this.db      = new DeferredLevelDOWN(this.location)
  dbFactory    = this.options.db || getLevelDOWN()
  db           = dbFactory(this.location)

  db.open(this.options, function (err) {
    if (err) {
      return dispatchError(self, new errors.OpenError(err), callback)
    } else {
      self.db.setDb(db)
      self.db = db
      self._status = 'open'
      if (callback)
        callback(null, self)
      self.emit('open')
      self.emit('ready')
    }
  })
}

LevelUP.prototype.close = function (callback) {
  var self = this

  if (this.isOpen()) {
    this._status = 'closing'
    this.db.close(function () {
      self._status = 'closed'
      self.emit('closed')
      if (callback)
        callback.apply(null, arguments)
    })
    this.emit('closing')
    this.db = null
  } else if (this._status == 'closed' && callback) {
    return process.nextTick(callback)
  } else if (this._status == 'closing' && callback) {
    this.once('closed', callback)
  } else if (this._isOpening()) {
    this.once('open', function () {
      self.close(callback)
    })
  }
}

LevelUP.prototype.isOpen = function () {
  return this._status == 'open'
}

LevelUP.prototype._isOpening = function () {
  return this._status == 'opening'
}

LevelUP.prototype.isClosed = function () {
  return (/^clos/).test(this._status)
}

LevelUP.prototype.get = function (key_, options, callback) {
  var self = this
    , key

  callback = getCallback(options, callback)

  if (typeof callback != 'function') {
    return dispatchError(
        this
      , new errors.ReadError('get() requires key and callback arguments')
    )
  }

  if (!this._isOpening() && !this.isOpen()) {
    return dispatchError(
        this
      , new errors.ReadError('Database is not open')
      , callback
    )
  }

  options = util.getOptions(this, options)
  key = util.encodeKey(key_, options)

  options.asBuffer = util.isValueAsBuffer(options)

  this.db.get(key, options, function (err, value) {
    if (err) {
      if ((/notfound/i).test(err)) {
        err = new errors.NotFoundError(
            'Key not found in database [' + key_ + ']', err)
      } else {
        err = new errors.ReadError(err)
      }
      return dispatchError(self, err, callback)
    }
    if (callback) {
      try {
        value = util.decodeValue(value, options)
      } catch (e) {
        return callback(new errors.EncodingError(e))
      }
      callback(null, value)
    }
  })
}

LevelUP.prototype.put = function (key_, value_, options, callback) {
  var self = this
    , key
    , value

  callback = getCallback(options, callback)

  if (key_ === null || key_ === undefined
        || value_ === null || value_ === undefined) {
    return dispatchError(
        this
       , new errors.WriteError('put() requires key and value arguments')
       , callback
    )
  }

  if (!this._isOpening() && !this.isOpen()) {
    return dispatchError(
        this
      , new errors.WriteError('Database is not open')
      , callback
    )
  }

  options = getOptions(this, options)
  key     = util.encodeKey(key_, options)
  value   = util.encodeValue(value_, options)

  this.db.put(key, value, options, function (err) {
    if (err) {
      return dispatchError(self, new errors.WriteError(err), callback)
    } else {
      self.emit('put', key_, value_)
      if (callback)
        callback()
    }
  })
}

LevelUP.prototype.del = function (key_, options, callback) {
  var self = this
    , key

  callback = getCallback(options, callback)

  if (key_ === null || key_ === undefined) {
    return dispatchError(
        this
      , new errors.WriteError('del() requires a key argument')
      , callback
    )
  }

  if (!this._isOpening() && !this.isOpen()) {
    return dispatchError(
        this
      , new errors.WriteError('Database is not open')
      , callback
    )
  }

  options = getOptions(this, options)
  key     = util.encodeKey(key_, options)

  this.db.del(key, options, function (err) {
    if (err) {
      return dispatchError(self, new errors.WriteError(err), callback)
    } else {
      self.emit('del', key_)
      if (callback)
        callback()
    }
  })
}

LevelUP.prototype.batch = function (arr_, options, callback) {
  var self = this
    , keyEnc
    , valueEnc
    , arr

  if (!arguments.length)
    return new Batch(this)

  callback = getCallback(options, callback)

  if (!Array.isArray(arr_)) {
    return dispatchError(
        this
      , new errors.WriteError('batch() requires an array argument')
      , callback
    )
  }

  if (!this._isOpening() && !this.isOpen()) {
    return dispatchError(
        this
      , new errors.WriteError('Database is not open')
      , callback
    )
  }

  options  = getOptions(this, options)
  keyEnc   = options.keyEncoding
  valueEnc = options.valueEncoding

  arr = arr_.map(function (e) {
    if (e.type === undefined || e.key === undefined)
      return {}

    // inherit encoding
    var kEnc = e.keyEncoding || keyEnc
      , vEnc = e.valueEncoding || e.encoding || valueEnc
      , o

    // If we're not dealing with plain utf8 strings or plain
    // Buffers then we have to do some work on the array to
    // encode the keys and/or values. This includes JSON types.

    if (kEnc != 'utf8' && kEnc != 'binary'
        || vEnc != 'utf8' && vEnc != 'binary') {
      o = {
          type: e.type
        , key: util.encodeKey(e.key, options, e)
      }

      if (e.value !== undefined)
        o.value = util.encodeValue(e.value, options, e)

      return o
    } else {
      return e
    }
  })

  this.db.batch(arr, options, function (err) {
    if (err) {
      return dispatchError(self, new errors.WriteError(err), callback)
    } else {
      self.emit('batch', arr_)
      if (callback)
        callback()
    }
  })
}

// DEPRECATED: prefer accessing LevelDOWN for this: db.db.approximateSize()
LevelUP.prototype.approximateSize = function (start_, end_, callback) {
  var self = this
    , start
    , end

  if (start_ === null || start_ === undefined
        || end_ === null || end_ === undefined
        || typeof callback != 'function') {
    return dispatchError(
        this
      , new errors.ReadError('approximateSize() requires start, end and callback arguments')
      , callback
    )
  }

  start = util.encodeKey(start_, this.options)
  end   = util.encodeKey(end_, this.options)

  if (!this._isOpening() && !this.isOpen()) {
    return dispatchError(
        this
      , new errors.WriteError('Database is not open')
      , callback
    )
  }

  this.db.approximateSize(start, end, function (err, size) {
    if (err) {
      return dispatchError(self, new errors.OpenError(err), callback)
    } else if (callback) {
      callback(null, size)
    }
  })
}

LevelUP.prototype.readStream =
LevelUP.prototype.createReadStream = function (options) {
  var self = this
  options = extend(this.options, options)
  return new ReadStream(
      options
    , this
    , function (options) {
        return self.db.iterator(options)
      }
  )
}

LevelUP.prototype.keyStream =
LevelUP.prototype.createKeyStream = function (options) {
  return this.createReadStream(extend(options, { keys: true, values: false }))
}

LevelUP.prototype.valueStream =
LevelUP.prototype.createValueStream = function (options) {
  return this.createReadStream(extend(options, { keys: false, values: true }))
}

LevelUP.prototype.writeStream =
LevelUP.prototype.createWriteStream = function (options) {
  return new WriteStream(extend(options), this)
}

LevelUP.prototype.toString = function () {
  return 'LevelUP'
}

function utilStatic (name) {
  return function (location, callback) {
    getLevelDOWN()[name](location, callback || function () {})
  }
}

module.exports         = LevelUP
module.exports.copy    = util.copy
// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').destroy()
module.exports.destroy = utilStatic('destroy')
// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').repair()
module.exports.repair  = utilStatic('repair')
<|endoftext|>


<commit_before>// Copyright (c) 2017, Patrick Quist
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

var should = require('chai').should();
var PascalDemangler = require('../lib/pascal-support').demangler;

describe('Pascal signature composer function', function () {
    var demangler = new PascalDemangler();

    it('Handle 0 parameter methods', function () {
        demangler.composeReadableMethodSignature("", "", "myfunc", "").should.equal("myfunc()");
        demangler.composeReadableMethodSignature("output", "", "myfunc", "").should.equal("myfunc()");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "").should.equal("tmyclass.myfunc()");
    });

    it('Handle 1 parameter methods', function () {
        demangler.composeReadableMethodSignature("output", "", "myfunc", "integer").should.equal("myfunc(integer)");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "integer").should.equal("tmyclass.myfunc(integer)");
    });

    it('Handle 2 parameter methods', function () {
        demangler.composeReadableMethodSignature("output", "", "myfunc", "integer,string").should.equal("myfunc(integer,string)");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "integer,string").should.equal("tmyclass.myfunc(integer,string)");
    });
});

describe('Pascal Demangling FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () {
        demangler.demangle("OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:").should.equal("maxarray(array_of_double,array_of_double)");
    });

    it('Should demangle OUTPUT_TMYCLASS_$__MYPROC$ANSISTRING', function () {
        demangler.demangle("OUTPUT_TMYCLASS_$__MYPROC$ANSISTRING:").should.equal("tmyclass.myproc(ansistring)");
    });

    it('Should demangle OUTPUT_TMYCLASS_$__MYFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_TMYCLASS_$__MYFUNC$$ANSISTRING:").should.equal("tmyclass.myfunc()");
    });

    it('Should demangle OUTPUT_NOPARAMFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_NOPARAMFUNC$$ANSISTRING:").should.equal("noparamfunc()");
    });

    it('Should demangle OUTPUT_NOPARAMPROC', function () {
        demangler.demangle("OUTPUT_NOPARAMPROC:").should.equal("noparamproc()");
    });

    it('Should demangle U_OUTPUT_MYGLOBALVAR', function () {
        demangler.demangle("U_OUTPUT_MYGLOBALVAR:").should.equal("myglobalvar");
    });

    it('Should demangle OUTPUT_INIT (custom method)', function () {
        demangler.demangle("OUTPUT_INIT:").should.equal("init()");
    });

    it('Should demangle OUTPUT_init (builtin symbol)', function () {
        demangler.demangle("OUTPUT_init:").should.equal("unit_initialization");
    });
});

describe('Pascal Demangling FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_$$_SQUARE$LONGINT$$LONGINT', function () {
        demangler.demangle("OUTPUT_$$_SQUARE$LONGINT$$LONGINT:").should.equal("square(longint)");
    });

    it('Should demangle OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () {
        demangler.demangle("OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:").should.equal("maxarray(array_of_double,array_of_double)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING:").should.equal("tmyclass.myproc(ansistring)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$$ANSISTRING:").should.equal("tmyclass.myfunc()");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER:").should.equal("tmyclass.myfunc(ansistring)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER:").should.equal("tmyclass.myfunc(ansistring,integer,integer)");
    });

    it('Should demangle OUTPUT_$$_NOPARAMFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_$$_NOPARAMFUNC$$ANSISTRING:").should.equal("noparamfunc()");
    });

    it('Should demangle OUTPUT_$$_NOPARAMPROC', function () {
        demangler.demangle("OUTPUT_$$_NOPARAMPROC:").should.equal("noparamproc()");
    });

    it('Should demangle OUTPUT_$$_INIT', function () {
        demangler.demangle("OUTPUT_$$_INIT:").should.equal("init()");
    });

    it('Should demangle U_$OUTPUT_$$_MYGLOBALVAR', function () {
        demangler.demangle("U_$OUTPUT_$$_MYGLOBALVAR:").should.equal("myglobalvar");
    });
});

describe('Pascal Demangling Fixed Symbols FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_finalize_implicit', function () {
        demangler.demangle("OUTPUT_finalize_implicit:").should.equal("unit_finalization_implicit");
    });
});

describe('Pascal Demangling Fixed Symbols FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_$$_init', function () {
        demangler.demangle("OUTPUT_$$_init:").should.equal("unit_initialization");
    });

    it('Should demangle OUTPUT_$$_finalize', function () {
        demangler.demangle("OUTPUT_$$_finalize:").should.equal("unit_finalization");
    });

    it('Should demangle OUTPUT_$$_init_implicit', function () {
        demangler.demangle("OUTPUT_$$_init_implicit:").should.equal("unit_initialization_implicit");
    });

    it('Should demangle OUTPUT_$$_finalize_implicit', function () {
        demangler.demangle("OUTPUT_$$_finalize_implicit:").should.equal("unit_finalization_implicit");
    });

    it('Should demangle OUTPUT_$$_finalize_implicit', function () {
        demangler.demangle("OUTPUT_$$_finalize_implicit:").should.equal("unit_finalization_implicit");
    });
});

describe('Pascal NOT Demangling certain symbols FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should NOT demangle VMT_OUTPUT_TMYCLASS', function () {
        demangler.demangle("VMT_OUTPUT_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle RTTI_OUTPUT_TMYCLASS', function () {
        demangler.demangle("RTTI_OUTPUT_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle INIT$_OUTPUT', function () {
        demangler.demangle("INIT$_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle FINALIZE$_OUTPUT', function () {
        demangler.demangle("FINALIZE$_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DEBUGSTART_OUTPUT', function () {
        demangler.demangle("DEBUGSTART_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DBGREF_OUTPUT_THELLO', function () {
        demangler.demangle("DBGREF_OUTPUT_THELLO:").should.equal(false);
    });

    it('Should NOT demangle non-label', function () {
        demangler.demangle("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal(false);
    });
});

describe('Pascal NOT Demangling certain symbols FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should NOT demangle RTTI_$OUTPUT_$$_TMYCLASS', function () {
        demangler.demangle("RTTI_$OUTPUT_$$_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle .Ld1', function () {
        demangler.demangle(".Ld1:").should.equal(false);
    });

    it('Should NOT demangle _$OUTPUT$_Ld3 (Same in FPC 2.6 and 3.2)', function () {
        demangler.demangle("_$OUTPUT$_Ld3:").should.equal(false);
    });

    it('Should NOT demangle INIT$_$OUTPUT', function () {
        demangler.demangle("INIT$_$OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DEBUGSTART_$OUTPUT', function () {
        demangler.demangle("DEBUGSTART_$OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DBGREF_$OUTPUT_$$_THELLO', function () {
        demangler.demangle("DBGREF_$OUTPUT_$$_THELLO:").should.equal(false);
    });
});

describe('Add, order and demangle inline', function () {
    var demangler = new PascalDemangler();

    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYTEST:");
    demangler.demangle("U_$OUTPUT_$$_MYGLOBALVAR:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYTEST2:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER:");

    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  movl U_$OUTPUT_$$_MYGLOBALVAR,%eax").should.equal("  movl myglobalvar,%eax");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST").should.equal("  call tmyclass.mytest()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING").should.equal("  call tmyclass.myoverload(ansistring)");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER").should.equal("  call tmyclass.myoverload(integer)");

    demangler.demangleIfNeeded(".Le1").should.equal(".Le1");
});

describe('Add, order and demangle inline - using addDemangleToCache()', function () {
    var demangler = new PascalDemangler();

    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYTEST:");
    demangler.addDemangleToCache("U_$OUTPUT_$$_MYGLOBALVAR:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYTEST2:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER:");

    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  movl U_$OUTPUT_$$_MYGLOBALVAR,%eax").should.equal("  movl myglobalvar,%eax");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST").should.equal("  call tmyclass.mytest()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING").should.equal("  call tmyclass.myoverload(ansistring)");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER").should.equal("  call tmyclass.myoverload(integer)");

    demangler.demangleIfNeeded(".Le1").should.equal(".Le1");
});

describe('Pascal Ignored Symbols', function () {
    var demangler = new PascalDemangler();

    it('Should ignore certain labels', function () {
        demangler.shouldIgnoreSymbol(".Le1").should.equal(true);
        demangler.shouldIgnoreSymbol("_$SomeThing").should.equal(true);
    });

    it('Should be able to differentiate between System and User functions', function() {
        demangler.shouldIgnoreSymbol("RTTI_OUTPUT_MyProperty").should.equal(true);
        demangler.shouldIgnoreSymbol("Rtti_Output_UserFunction").should.equal(false);
    });
});
<commit_msg>this one should take coverage to 100% again<commit_after>// Copyright (c) 2017, Patrick Quist
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

var should = require('chai').should();
var PascalDemangler = require('../lib/pascal-support').demangler;

describe('Pascal signature composer function', function () {
    var demangler = new PascalDemangler();

    it('Handle 0 parameter methods', function () {
        demangler.composeReadableMethodSignature("", "", "myfunc", "").should.equal("myfunc()");
        demangler.composeReadableMethodSignature("output", "", "myfunc", "").should.equal("myfunc()");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "").should.equal("tmyclass.myfunc()");
    });

    it('Handle 1 parameter methods', function () {
        demangler.composeReadableMethodSignature("output", "", "myfunc", "integer").should.equal("myfunc(integer)");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "integer").should.equal("tmyclass.myfunc(integer)");
    });

    it('Handle 2 parameter methods', function () {
        demangler.composeReadableMethodSignature("output", "", "myfunc", "integer,string").should.equal("myfunc(integer,string)");
        demangler.composeReadableMethodSignature("output", "tmyclass", "myfunc", "integer,string").should.equal("tmyclass.myfunc(integer,string)");
    });
});

describe('Pascal Demangling FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () {
        demangler.demangle("OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:").should.equal("maxarray(array_of_double,array_of_double)");
    });

    it('Should demangle OUTPUT_TMYCLASS_$__MYPROC$ANSISTRING', function () {
        demangler.demangle("OUTPUT_TMYCLASS_$__MYPROC$ANSISTRING:").should.equal("tmyclass.myproc(ansistring)");
    });

    it('Should demangle OUTPUT_TMYCLASS_$__MYFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_TMYCLASS_$__MYFUNC$$ANSISTRING:").should.equal("tmyclass.myfunc()");
    });

    it('Should demangle OUTPUT_NOPARAMFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_NOPARAMFUNC$$ANSISTRING:").should.equal("noparamfunc()");
    });

    it('Should demangle OUTPUT_NOPARAMPROC', function () {
        demangler.demangle("OUTPUT_NOPARAMPROC:").should.equal("noparamproc()");
    });

    it('Should demangle U_OUTPUT_MYGLOBALVAR', function () {
        demangler.demangle("U_OUTPUT_MYGLOBALVAR:").should.equal("myglobalvar");
    });

    it('Should demangle OUTPUT_INIT (custom method)', function () {
        demangler.demangle("OUTPUT_INIT:").should.equal("init()");
    });

    it('Should demangle OUTPUT_init (builtin symbol)', function () {
        demangler.demangle("OUTPUT_init:").should.equal("unit_initialization");
    });
});

describe('Pascal Demangling FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_$$_SQUARE$LONGINT$$LONGINT', function () {
        demangler.demangle("OUTPUT_$$_SQUARE$LONGINT$$LONGINT:").should.equal("square(longint)");
    });

    it('Should demangle OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () {
        demangler.demangle("OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:").should.equal("maxarray(array_of_double,array_of_double)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING:").should.equal("tmyclass.myproc(ansistring)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$$ANSISTRING:").should.equal("tmyclass.myfunc()");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER:").should.equal("tmyclass.myfunc(ansistring)");
    });

    it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER', function () {
        demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER:").should.equal("tmyclass.myfunc(ansistring,integer,integer)");
    });

    it('Should demangle OUTPUT_$$_NOPARAMFUNC$$ANSISTRING', function () {
        demangler.demangle("OUTPUT_$$_NOPARAMFUNC$$ANSISTRING:").should.equal("noparamfunc()");
    });

    it('Should demangle OUTPUT_$$_NOPARAMPROC', function () {
        demangler.demangle("OUTPUT_$$_NOPARAMPROC:").should.equal("noparamproc()");
    });

    it('Should demangle OUTPUT_$$_INIT', function () {
        demangler.demangle("OUTPUT_$$_INIT:").should.equal("init()");
    });

    it('Should demangle U_$OUTPUT_$$_MYGLOBALVAR', function () {
        demangler.demangle("U_$OUTPUT_$$_MYGLOBALVAR:").should.equal("myglobalvar");
    });
});

describe('Pascal Demangling Fixed Symbols FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_finalize_implicit', function () {
        demangler.demangle("OUTPUT_finalize_implicit:").should.equal("unit_finalization_implicit");
    });
});

describe('Pascal Demangling Fixed Symbols FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should demangle OUTPUT_$$_init', function () {
        demangler.demangle("OUTPUT_$$_init:").should.equal("unit_initialization");
    });

    it('Should demangle OUTPUT_$$_finalize', function () {
        demangler.demangle("OUTPUT_$$_finalize:").should.equal("unit_finalization");
    });

    it('Should demangle OUTPUT_$$_init_implicit', function () {
        demangler.demangle("OUTPUT_$$_init_implicit:").should.equal("unit_initialization_implicit");
    });

    it('Should demangle OUTPUT_$$_finalize_implicit', function () {
        demangler.demangle("OUTPUT_$$_finalize_implicit:").should.equal("unit_finalization_implicit");
    });

    it('Should demangle OUTPUT_$$_finalize_implicit', function () {
        demangler.demangle("OUTPUT_$$_finalize_implicit:").should.equal("unit_finalization_implicit");
    });
});

describe('Pascal NOT Demangling certain symbols FPC 2.6', function () {
    var demangler = new PascalDemangler();

    it('Should NOT demangle VMT_OUTPUT_TMYCLASS', function () {
        demangler.demangle("VMT_OUTPUT_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle RTTI_OUTPUT_TMYCLASS', function () {
        demangler.demangle("RTTI_OUTPUT_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle INIT$_OUTPUT', function () {
        demangler.demangle("INIT$_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle FINALIZE$_OUTPUT', function () {
        demangler.demangle("FINALIZE$_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DEBUGSTART_OUTPUT', function () {
        demangler.demangle("DEBUGSTART_OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DBGREF_OUTPUT_THELLO', function () {
        demangler.demangle("DBGREF_OUTPUT_THELLO:").should.equal(false);
    });

    it('Should NOT demangle non-label', function () {
        demangler.demangle("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal(false);
    });
});

describe('Pascal NOT Demangling certain symbols FPC 3.2', function () {
    var demangler = new PascalDemangler();

    it('Should NOT demangle RTTI_$OUTPUT_$$_TMYCLASS', function () {
        demangler.demangle("RTTI_$OUTPUT_$$_TMYCLASS:").should.equal(false);
    });

    it('Should NOT demangle .Ld1', function () {
        demangler.demangle(".Ld1:").should.equal(false);
    });

    it('Should NOT demangle _$OUTPUT$_Ld3 (Same in FPC 2.6 and 3.2)', function () {
        demangler.demangle("_$OUTPUT$_Ld3:").should.equal(false);
    });

    it('Should NOT demangle INIT$_$OUTPUT', function () {
        demangler.demangle("INIT$_$OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DEBUGSTART_$OUTPUT', function () {
        demangler.demangle("DEBUGSTART_$OUTPUT:").should.equal(false);
    });

    it('Should NOT demangle DBGREF_$OUTPUT_$$_THELLO', function () {
        demangler.demangle("DBGREF_$OUTPUT_$$_THELLO:").should.equal(false);
    });
});

describe('Add, order and demangle inline', function () {
    var demangler = new PascalDemangler();

    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYTEST:");
    demangler.demangle("U_$OUTPUT_$$_MYGLOBALVAR:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYTEST2:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING:");
    demangler.demangle("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER:");

    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  movl U_$OUTPUT_$$_MYGLOBALVAR,%eax").should.equal("  movl myglobalvar,%eax");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST").should.equal("  call tmyclass.mytest()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING").should.equal("  call tmyclass.myoverload(ansistring)");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER").should.equal("  call tmyclass.myoverload(integer)");

    demangler.demangleIfNeeded(".Le1").should.equal(".Le1");
    demangler.demangleIfNeeded("_$SomeThing").should.equal("_$SomeThing");
});

describe('Add, order and demangle inline - using addDemangleToCache()', function () {
    var demangler = new PascalDemangler();

    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYTEST:");
    demangler.addDemangleToCache("U_$OUTPUT_$$_MYGLOBALVAR:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYTEST2:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING:");
    demangler.addDemangleToCache("OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER:");

    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  movl U_$OUTPUT_$$_MYGLOBALVAR,%eax").should.equal("  movl myglobalvar,%eax");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST2").should.equal("  call tmyclass.mytest2()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYTEST").should.equal("  call tmyclass.mytest()");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING").should.equal("  call tmyclass.myoverload(ansistring)");
    demangler.demangleIfNeeded("  call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER").should.equal("  call tmyclass.myoverload(integer)");

    demangler.demangleIfNeeded(".Le1").should.equal(".Le1");
});

describe('Pascal Ignored Symbols', function () {
    var demangler = new PascalDemangler();

    it('Should ignore certain labels', function () {
        demangler.shouldIgnoreSymbol(".Le1").should.equal(true);
        demangler.shouldIgnoreSymbol("_$SomeThing").should.equal(true);
    });

    it('Should be able to differentiate between System and User functions', function() {
        demangler.shouldIgnoreSymbol("RTTI_OUTPUT_MyProperty").should.equal(true);
        demangler.shouldIgnoreSymbol("Rtti_Output_UserFunction").should.equal(false);
    });
});
<|endoftext|>


<commit_before>/* global describe, it, expect, before */
/* jshint expr: true */

var fs = require('fs')
  , parse = require('../lib/profile').parse;

describe('profile.parse', function() {

  describe('example profile', function() {
    var profile;

    before(function(done) {
      fs.readFile('test/data/example.json', 'utf8', function(err, data) {
        if (err) { return done(err); }
        profile = parse(data);
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.have.length(1);
      expect(profile.emails[0].value).to.equal('octocat@github.com');
    });
  });

  describe('example profile with null email', function() {
    var profile;

    before(function(done) {
      fs.readFile('test/data/example-null-email.json', 'utf8', function(err, data) {
        if (err) { return done(err); }
        profile = parse(data);
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.be.undefined;
    });
  });

});
<commit_msg>Removed profile test.<commit_after><|endoftext|>


<commit_before>'use strict';

/** Load other modules. */
var _ = require('lodash'),
    mapping = require('./mapping.js');

/** Native method references. */
var push = Array.prototype.push;

/*----------------------------------------------------------------------------*/

/** List of all object property dependencies. */
exports.objDeps = _.uniq(_.transform(mapping.objDep, _.bind(push.apply, push), [])).sort();

/** List of all variable dependencies. */
exports.varDeps = _.uniq(_.transform(mapping.varDep, _.bind(push.apply, push), [])).sort();

/** List of all functions. */
exports.funcs = _.filter(_.difference(_.keys(mapping.funcDep), exports.objDeps, exports.varDeps).sort(), function(key) {
  var type = typeof _.prototype[key];
  return type == 'function' || type == 'undefined';
});

/** List of lodash functions included by default. */
exports.includes = _.intersection(exports.funcs, _.union(
  _.functions(_),
  _.functions(_.prototype),
  mapping.category.Chain,
  ['main']
));

_.assign(module.exports, {

  /** List of all function categories. */
  'categories': _.keys(mapping.category).sort(),

  /** List of variables with complex assignments. */
  'complexVars': [
    'cloneableTags',
    'contextProps',
    'reWords',
    'typedArrayTags'
  ],

  /** List of functions included in the "core" build. */
  'coreFuncs': [
    'before',
    'bind',
    'chain',
    'clone',
    'defaults',
    'defer',
    'delay',
    'escape',
    'every',
    'extend',
    'extendWith',
    'filter',
    'find',
    'first',
    'flatten',
    'forEach',
    'functions',
    'gt',
    'has',
    'identity',
    'indexOf',
    'invoke',
    'isArguments',
    'isArray',
    'isEmpty',
    'isEqual',
    'isFinite',
    'isFunction',
    'isObject',
    'isString',
    'iteratee',
    'keys',
    'keysIn',
    'last',
    'lt',
    'map',
    'max',
    'min',
    'mixin',
    'negate',
    'noConflict',
    'noop',
    'now',
    'once',
    'pick',
    'reduce',
    'restParam',
    'result',
    'size',
    'some',
    'sortBy',
    'tap',
    'thru',
    'toArray',
    'uniqueId',
    'value',
    'values'
  ],

  /** List of the default ways to export the `lodash` function. */
  'exports': [
    'amd',
    'commonjs',
    'global',
    'iojs',
    'node',
    'umd'
  ],

  /** List of dependencies that should not cause a minor bump when changed. */
  'laxSemVerDeps': [
    'isArrayLike',
    'isBoolean',
    'isError',
    'isFinite',
    'isFunction',
    'isNaN',
    'isNull',
    'isNumber',
    'isObject',
    'isObjectLike',
    'isString',
    'isUndefined'
  ],

  /** List of functions that support argument placeholders. */
  'placeholderFuncs': [
    'bind',
    'bindKey',
    'curry',
    'curryRight',
    'partial',
    'partialRight'
  ],

  /* Used to designate dependencies at the top level. */
  'topLevelDeps': [
    'main'
  ],

  /** List of uninlinable dependencies. */
  'uninlinables': _.union(
    _.without(exports.includes,
      'constant',
      'drop',
      'dropRight',
      'filter',
      'identity',
      'isArray',
      'isObject',
      'last',
      'matches',
      'noop',
      'now',
      'pluck',
      'property',
      'toPlainObject',
      'values'
    ),
    _.keys(_.support),
    _.keys(_.templateSettings), [
    'arrayEach',
    'arrayEvery',
    'arrayFilter',
    'arrayMap',
    'baseAt',
    'baseCreate',
    'baseDelay',
    'baseDifference',
    'baseEach',
    'baseEachRight',
    'baseFilter',
    'baseFind',
    'baseFindIndex',
    'baseFlatten',
    'baseFor',
    'baseForRight',
    'baseFunctions',
    'baseGet',
    'baseIndexOf',
    'baseIsEqual',
    'baseIsMatch',
    'baseIteratee',
    'baseMatches',
    'baseMatchesProperty',
    'basePick',
    'basePickBy',
    'basePullAt',
    'baseRandom',
    'baseReduce',
    'baseSlice',
    'baseSortBy',
    'baseSortByOrder',
    'baseToString',
    'baseUniq',
    'baseValues',
    'binaryIndex',
    'binaryIndexBy',
    'bindIteratee',
    'cacheIndexOf',
    'charsLeftIndex',
    'charsRightIndex',
    'compareAscending',
    'copyArray',
    'copyObject',
    'copyObjectWith',
    'createAggregator',
    'createAssigner',
    'createCache',
    'createCompounder',
    'createPadding',
    'createWrapper',
    'getNative',
    'invokePath',
    'isIterateeCall',
    'reInterpolate',
    'reEscape',
    'reEvaluate',
    'replaceHolders',
    'templateSettings',
    'toIterable',
    'toPath',
    'trimmedLeftIndex',
    'trimmedRightIndex'
  ]).sort()
});
<commit_msg>Add `flattenDeep` to `coreFuncs` listing.<commit_after>'use strict';

/** Load other modules. */
var _ = require('lodash'),
    mapping = require('./mapping.js');

/** Native method references. */
var push = Array.prototype.push;

/*----------------------------------------------------------------------------*/

/** List of all object property dependencies. */
exports.objDeps = _.uniq(_.transform(mapping.objDep, _.bind(push.apply, push), [])).sort();

/** List of all variable dependencies. */
exports.varDeps = _.uniq(_.transform(mapping.varDep, _.bind(push.apply, push), [])).sort();

/** List of all functions. */
exports.funcs = _.filter(_.difference(_.keys(mapping.funcDep), exports.objDeps, exports.varDeps).sort(), function(key) {
  var type = typeof _.prototype[key];
  return type == 'function' || type == 'undefined';
});

/** List of lodash functions included by default. */
exports.includes = _.intersection(exports.funcs, _.union(
  _.functions(_),
  _.functions(_.prototype),
  mapping.category.Chain,
  ['main']
));

_.assign(module.exports, {

  /** List of all function categories. */
  'categories': _.keys(mapping.category).sort(),

  /** List of variables with complex assignments. */
  'complexVars': [
    'cloneableTags',
    'contextProps',
    'reWords',
    'typedArrayTags'
  ],

  /** List of functions included in the "core" build. */
  'coreFuncs': [
    'before',
    'bind',
    'chain',
    'clone',
    'defaults',
    'defer',
    'delay',
    'escape',
    'every',
    'extend',
    'extendWith',
    'filter',
    'find',
    'first',
    'flatten',
    'flattenDeep',
    'forEach',
    'functions',
    'gt',
    'has',
    'identity',
    'indexOf',
    'invoke',
    'isArguments',
    'isArray',
    'isEmpty',
    'isEqual',
    'isFinite',
    'isFunction',
    'isObject',
    'isString',
    'iteratee',
    'keys',
    'keysIn',
    'last',
    'lt',
    'map',
    'max',
    'min',
    'mixin',
    'negate',
    'noConflict',
    'noop',
    'now',
    'once',
    'pick',
    'reduce',
    'restParam',
    'result',
    'size',
    'some',
    'sortBy',
    'tap',
    'thru',
    'toArray',
    'uniqueId',
    'value',
    'values'
  ],

  /** List of the default ways to export the `lodash` function. */
  'exports': [
    'amd',
    'commonjs',
    'global',
    'iojs',
    'node',
    'umd'
  ],

  /** List of dependencies that should not cause a minor bump when changed. */
  'laxSemVerDeps': [
    'isArrayLike',
    'isBoolean',
    'isError',
    'isFinite',
    'isFunction',
    'isNaN',
    'isNull',
    'isNumber',
    'isObject',
    'isObjectLike',
    'isString',
    'isUndefined'
  ],

  /** List of functions that support argument placeholders. */
  'placeholderFuncs': [
    'bind',
    'bindKey',
    'curry',
    'curryRight',
    'partial',
    'partialRight'
  ],

  /* Used to designate dependencies at the top level. */
  'topLevelDeps': [
    'main'
  ],

  /** List of uninlinable dependencies. */
  'uninlinables': _.union(
    _.without(exports.includes,
      'constant',
      'drop',
      'dropRight',
      'filter',
      'identity',
      'isArray',
      'isObject',
      'last',
      'matches',
      'noop',
      'now',
      'pluck',
      'property',
      'toPlainObject',
      'values'
    ),
    _.keys(_.support),
    _.keys(_.templateSettings), [
    'arrayEach',
    'arrayEvery',
    'arrayFilter',
    'arrayMap',
    'baseAt',
    'baseCreate',
    'baseDelay',
    'baseDifference',
    'baseEach',
    'baseEachRight',
    'baseFilter',
    'baseFind',
    'baseFindIndex',
    'baseFlatten',
    'baseFor',
    'baseForRight',
    'baseFunctions',
    'baseGet',
    'baseIndexOf',
    'baseIsEqual',
    'baseIsMatch',
    'baseIteratee',
    'baseMatches',
    'baseMatchesProperty',
    'basePick',
    'basePickBy',
    'basePullAt',
    'baseRandom',
    'baseReduce',
    'baseSlice',
    'baseSortBy',
    'baseSortByOrder',
    'baseToString',
    'baseUniq',
    'baseValues',
    'binaryIndex',
    'binaryIndexBy',
    'bindIteratee',
    'cacheIndexOf',
    'charsLeftIndex',
    'charsRightIndex',
    'compareAscending',
    'copyArray',
    'copyObject',
    'copyObjectWith',
    'createAggregator',
    'createAssigner',
    'createCache',
    'createCompounder',
    'createPadding',
    'createWrapper',
    'getNative',
    'invokePath',
    'isIterateeCall',
    'reInterpolate',
    'reEscape',
    'reEvaluate',
    'replaceHolders',
    'templateSettings',
    'toIterable',
    'toPath',
    'trimmedLeftIndex',
    'trimmedRightIndex'
  ]).sort()
});
<|endoftext|>