<commit_before>require('./lib/util/patch');
var net = require('net');
var tls = require('tls');
var extend = require('extend');
var path = require('path');
var cluster = require('cluster');
var os = require('os');
var assert = require('assert');

var ver = process.version.substring(1).split('.');
var PROD_RE = /(^|\|)prod(uction)?($|\|)/;
var noop = function () {};
var state = {};
var INTERVAL = 1000;
var TIMEOUT = 10000;
var MASTER_TIMEOUT = 12000;

if (ver[0] >= 7 && ver[1] >= 7) {
  var connect = net.Socket.prototype.connect;
  if (typeof connect === 'function') {
    //fix: Node v7.7.0+引入的 `"listener" argument must be a function` 问题
    net.Socket.prototype.connect = function (options, cb) {
      if (options && typeof options === 'object' && typeof cb !== 'function') {
        return connect.call(this, options, null);
      }
      return connect.apply(this, arguments);
    };
  }
}

var env = process.env || '';
env.WHISTLE_ROOT = __dirname;
if (typeof tls.checkServerIdentity == 'function') {
  var checkServerIdentity = tls.checkServerIdentity;
  tls.checkServerIdentity = function () {
    try {
      return checkServerIdentity.apply(this, arguments);
    } catch (err) {
      return err;
    }
  };
}
if (env.WHISTLE_PLUGIN_EXEC_PATH) {
  env.PFORK_EXEC_PATH = env.WHISTLE_PLUGIN_EXEC_PATH;
}

function isPipeName(s) {
  return typeof s === 'string' && toNumber(s) === false;
}

function toNumber(x) {
  return (x = Number(x)) >= 0 ? x : false;
}

if (!net._normalizeConnectArgs) {
  //Returns an array [options] or [options, cb]
  //It is the same as the argument of Socket.prototype.connect().
  net._normalizeConnectArgs = function (args) {
    var options = {};

    if (args[0] !== null && typeof args[0] === 'object') {
      // connect(options, [cb])
      options = args[0];
    } else if (isPipeName(args[0])) {
      // connect(path, [cb]);
      options.path = args[0];
    } else {
      // connect(port, [host], [cb])
      options.port = args[0];
      if (typeof args[1] === 'string') {
        options.host = args[1];
      }
    }

    var cb = args[args.length - 1];
    return typeof cb === 'function' ? [options, cb] : [options];
  };
}

function loadConfig(options) {
  var config = options.config;
  if (config) {
    delete options.config;
    return require(path.resolve(config));
  }
}

function likePromise(p) {
  return p && typeof p.then === 'function' && typeof p.catch === 'function';
}

function killWorker(worker) {
  try {
    worker.removeAllListeners();
    worker.on('error', noop);
    worker.kill('SIGTERM');
  } catch (err) {}
}

function forkWorker(index) {
  var worker = cluster.fork({ workerIndex: index });
  var reforked;
  var refork = () => {
    if (!state[index]) {
      setTimeout(function () {
        process.exit(1);
      }, INTERVAL);
      return;
    }
    if (reforked) {
      return;
    }
    reforked = true;
    killWorker(worker);
    clearInterval(worker.timer);
    clearTimeout(worker.activeTimer);
    setTimeout(function () {
      forkWorker(index);
    }, 600);
  };
  worker.once('disconnect', refork);
  worker.once('exit', refork);
  worker.on('error', noop);
  worker.on('message', (msg) => {
    if (msg !== '1') {
      return;
    }
    state[index] = true;
    if (!worker.timer) {
      worker.timer = setInterval(() => {
        try {
          worker.send('1', noop);
        } catch (e) {
          clearInterval(worker.timer);
        }
      }, INTERVAL);
    } else {
      clearTimeout(worker.activeTimer);
    }
    worker.activeTimer = setTimeout(refork, MASTER_TIMEOUT);
  });
}

module.exports = function (options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = null;
  }
  var startWhistle = function () {
    var server = options.server;
    assert(!server || options.storage, 'options.storage is required if options.server exists (you can use package.name as options.storage)');
    var workerIndex = env.workerIndex;
    if (options && options.cluster && workerIndex >= 0) {
      options.storage =
        '.' +
        (options.storage || '') +
        '__cluster_worker.' +
        workerIndex +
        '_5b6af7b9884e1165__';
    }
    var conf = require('./lib/config').extend(options);
    if (!conf.cluster) {
      return require('./lib')(callback, server);
    }
    var timer;
    var activeTimeout = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        process.exit(1);
      }, TIMEOUT);
    };
    process.once('SIGTERM', function () {
      process.exit(0);
    });

    require('./lib')(function () {
      activeTimeout();
      process.on('message', activeTimeout);
      process.send('1', noop);
      setInterval(() => {
        try {
          process.send('1', noop);
        } catch (e) {}
      }, INTERVAL);
    });
  };
  if (options) {
    if (/^\d+$/.test(options.cluster)) {
      options.cluster = Math.min(parseInt(options.cluster, 10), 999);
    } else if (options.cluster) {
      options.cluster = Math.min(os.cpus().length, 999);
    }
    if (options.cluster && cluster.isMaster) {
      assert(!options.server, 'cannot exist options.server in cluster mode');
      for (var i = 0; i < options.cluster; i++) {
        forkWorker(i);
      }
      return;
    }
    if (options.debugMode) {
      if (PROD_RE.test(options.mode)) {
        options.debugMode = false;
      } else {
        env.PFORK_MODE = 'bind';
      }
    }
    var config = loadConfig(options);
    if (typeof config === 'function') {
      var handleCallback = function (opts) {
        opts && extend(options, opts);
        return startWhistle();
      };
      if (config.length < 2) {
        config = config(options);
        if (likePromise(config)) {
          return config.then(handleCallback).catch(function (err) {
            process.nextTick(function () {
              throw err;
            });
          });
        }
      } else {
        config(options, handleCallback);
      }
    }
    config && extend(options, config);
  }
  return startWhistle();
};
<commit_msg>refactor: refine code<commit_after>require('./lib/util/patch');
var net = require('net');
var tls = require('tls');
var extend = require('extend');
var path = require('path');
var cluster = require('cluster');
var os = require('os');
var assert = require('assert');

var ver = process.version.substring(1).split('.');
var PROD_RE = /(^|\|)prod(uction)?($|\|)/;
var noop = function () {};
var state = {};
var INTERVAL = 1000;
var TIMEOUT = 10000;
var MASTER_TIMEOUT = 12000;

if (ver[0] >= 7 && ver[1] >= 7) {
  var connect = net.Socket.prototype.connect;
  if (typeof connect === 'function') {
    //fix: Node v7.7.0+引入的 `"listener" argument must be a function` 问题
    net.Socket.prototype.connect = function (options, cb) {
      if (options && typeof options === 'object' && typeof cb !== 'function') {
        return connect.call(this, options, null);
      }
      return connect.apply(this, arguments);
    };
  }
}

var env = process.env || '';
env.WHISTLE_ROOT = __dirname;
if (typeof tls.checkServerIdentity == 'function') {
  var checkServerIdentity = tls.checkServerIdentity;
  tls.checkServerIdentity = function () {
    try {
      return checkServerIdentity.apply(this, arguments);
    } catch (err) {
      return err;
    }
  };
}
if (env.WHISTLE_PLUGIN_EXEC_PATH) {
  env.PFORK_EXEC_PATH = env.WHISTLE_PLUGIN_EXEC_PATH;
}

function isPipeName(s) {
  return typeof s === 'string' && toNumber(s) === false;
}

function toNumber(x) {
  return (x = Number(x)) >= 0 ? x : false;
}

if (!net._normalizeConnectArgs) {
  //Returns an array [options] or [options, cb]
  //It is the same as the argument of Socket.prototype.connect().
  net._normalizeConnectArgs = function (args) {
    var options = {};

    if (args[0] !== null && typeof args[0] === 'object') {
      // connect(options, [cb])
      options = args[0];
    } else if (isPipeName(args[0])) {
      // connect(path, [cb]);
      options.path = args[0];
    } else {
      // connect(port, [host], [cb])
      options.port = args[0];
      if (typeof args[1] === 'string') {
        options.host = args[1];
      }
    }

    var cb = args[args.length - 1];
    return typeof cb === 'function' ? [options, cb] : [options];
  };
}

function loadConfig(options) {
  var config = options.config;
  if (config) {
    delete options.config;
    return require(path.resolve(config));
  }
}

function likePromise(p) {
  return p && typeof p.then === 'function' && typeof p.catch === 'function';
}

function killWorker(worker) {
  try {
    worker.removeAllListeners();
    worker.on('error', noop);
    worker.kill('SIGTERM');
  } catch (err) {}
}

function forkWorker(index) {
  var worker = cluster.fork({ workerIndex: index });
  var reforked;
  var refork = () => {
    if (!state[index]) {
      setTimeout(function () {
        process.exit(1);
      }, INTERVAL);
      return;
    }
    if (reforked) {
      return;
    }
    reforked = true;
    killWorker(worker);
    clearInterval(worker.timer);
    clearTimeout(worker.activeTimer);
    setTimeout(function () {
      forkWorker(index);
    }, 600);
  };
  worker.once('disconnect', refork);
  worker.once('exit', refork);
  worker.on('error', noop);
  worker.on('message', (msg) => {
    if (msg !== '1') {
      return;
    }
    state[index] = true;
    if (!worker.timer) {
      worker.timer = setInterval(() => {
        try {
          worker.send('1', noop);
        } catch (e) {
          clearInterval(worker.timer);
        }
      }, INTERVAL);
    } else {
      clearTimeout(worker.activeTimer);
    }
    worker.activeTimer = setTimeout(refork, MASTER_TIMEOUT);
  });
}

module.exports = function (options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = null;
  }
  var startWhistle = function () {
    var server = options.server;
    assert(!server || options.port > 0, 'options.port of the custom server is required');
    options.storage = options.storage || '.custom_server_' + options.port;
    var workerIndex = env.workerIndex;
    if (options && options.cluster && workerIndex >= 0) {
      options.storage =
        '.' +
        (options.storage || '') +
        '__cluster_worker.' +
        workerIndex +
        '_5b6af7b9884e1165__';
    }
    var conf = require('./lib/config').extend(options);
    if (!conf.cluster) {
      return require('./lib')(callback, server);
    }
    var timer;
    var activeTimeout = function () {
      clearTimeout(timer);
      timer = setTimeout(function () {
        process.exit(1);
      }, TIMEOUT);
    };
    process.once('SIGTERM', function () {
      process.exit(0);
    });

    require('./lib')(function () {
      activeTimeout();
      process.on('message', activeTimeout);
      process.send('1', noop);
      setInterval(() => {
        try {
          process.send('1', noop);
        } catch (e) {}
      }, INTERVAL);
    });
  };
  if (options) {
    if (/^\d+$/.test(options.cluster)) {
      options.cluster = Math.min(parseInt(options.cluster, 10), 999);
    } else if (options.cluster) {
      options.cluster = Math.min(os.cpus().length, 999);
    }
    if (options.cluster && cluster.isMaster) {
      assert(!options.server, 'cannot exist options.server in cluster mode');
      for (var i = 0; i < options.cluster; i++) {
        forkWorker(i);
      }
      return;
    }
    if (options.debugMode) {
      if (PROD_RE.test(options.mode)) {
        options.debugMode = false;
      } else {
        env.PFORK_MODE = 'bind';
      }
    }
    var config = loadConfig(options);
    if (typeof config === 'function') {
      var handleCallback = function (opts) {
        opts && extend(options, opts);
        return startWhistle();
      };
      if (config.length < 2) {
        config = config(options);
        if (likePromise(config)) {
          return config.then(handleCallback).catch(function (err) {
            process.nextTick(function () {
              throw err;
            });
          });
        }
      } else {
        config(options, handleCallback);
      }
    }
    config && extend(options, config);
  }
  return startWhistle();
};
<|endoftext|>


<commit_before>var through = require('through2'),
	cheerio = require('cheerio'),
	uglifyjs = require('uglify-js'),
	cleancss = require('clean-css'),
	gutil = require('gulp-util');

const PLUGIN_NAME = 'gulp-minify-inline';

module.exports = function ( opt )
{
	opt = opt || {};

	function minify ( file, encoding, callback )
	{
		if (file.isNull())
		{
			return callback(null, file);
		}

		if (file.isStream())
		{
			return callback(new gutil.PluginError('gulp-minify-inline', 'doesn\'t support Streams'));
		}

		var $ = cheerio.load(file.contents.toString(), {decodeEntities: false});

		var has_done_nothing = true;

		var jsSelector = opt.jsSelector || 'script';

		if (opt.js !== false) $(jsSelector).each(function ( )
		{
			if (!opt.js) opt.js = {};

			opt.js.fromString = true;

			var $this = $(this),
				script_orig = $this.text().trim();

			if (script_orig !== '')
			{
				var script_min = uglifyjs.minify(script_orig, opt.js);

				$this.text(script_min.code);

				has_done_nothing = false;
			}
		});

		var cssSelector = opt.cssSelector || 'style';

		if (opt.css !== false) $(cssSelector).each(function ( )
		{
			var $this = $(this),
				style_orig = $this.text().trim();

			if (style_orig !== '')
			{
				var style_min = new cleancss(opt.css).minify(style_orig).styles;

				$this.text(style_min);

				has_done_nothing = false;
			}
		});

		if (!has_done_nothing) file.contents = new Buffer($.html());

		callback(null, file);
	}

	return through.obj(minify);
};
<commit_msg>Prevent </script> in JavaScript strings<commit_after>var through = require('through2'),
	cheerio = require('cheerio'),
	uglifyjs = require('uglify-js'),
	cleancss = require('clean-css'),
	gutil = require('gulp-util');

const PLUGIN_NAME = 'gulp-minify-inline';

module.exports = function ( opt )
{
	opt = opt || {};

	function minify ( file, encoding, callback )
	{
		if (file.isNull())
		{
			return callback(null, file);
		}

		if (file.isStream())
		{
			return callback(new gutil.PluginError('gulp-minify-inline', 'doesn\'t support Streams'));
		}

		var $ = cheerio.load(file.contents.toString(), {decodeEntities: false});

		var has_done_nothing = true;

		var jsSelector = opt.jsSelector || 'script';

		if (opt.js !== false) $(jsSelector).each(function ( )
		{
			if (!opt.js) opt.js = {};
			if (!opt.js.output) opt.js.output = {};

			opt.js.fromString = true;
			opt.js.output.inline_script = true;

			var $this = $(this),
				script_orig = $this.text().trim();

			if (script_orig !== '')
			{
				var script_min = uglifyjs.minify(script_orig, opt.js);

				$this.text(script_min.code);

				has_done_nothing = false;
			}
		});

		var cssSelector = opt.cssSelector || 'style';

		if (opt.css !== false) $(cssSelector).each(function ( )
		{
			var $this = $(this),
				style_orig = $this.text().trim();

			if (style_orig !== '')
			{
				var style_min = new cleancss(opt.css).minify(style_orig).styles;

				$this.text(style_min);

				has_done_nothing = false;
			}
		});

		if (!has_done_nothing) file.contents = new Buffer($.html());

		callback(null, file);
	}

	return through.obj(minify);
};
<|endoftext|>


<commit_before>const beautify = require("js-beautify").html;
const child = require("child_process");
const detectIndent = require("detect-indent");
const flattenDeep = require("lodash.flattendeep");
const fs = require("fs");
const list = require("./util").list;
const log = require("./util").log;
const path = require("path");
const plist = require("plist");
const pSettle = require("p-settle");
const stripIndents = require("common-tags/lib/stripIndents");
const unique = require("lodash.uniq");
const Xcode = require("pbxproj-dom/xcode").Xcode;

/**
 * Custom type definition for Promises
 * @typedef Promise
 * @property {*} result See the implementing function for the resolve type and description
 * @property {Error} result Rejection error object
 */

const env = {
	target: process.env.RNV && list(process.env.RNV)
};

/**
 * Returns default values for some options, namely android/ios file/folder paths
 * @private
 * @return {Object} Defaults
 */
function getDefaults() {
	return {
		android: "android/app/build.gradle",
		ios: "ios"
	};
}

/**
 * Returns Info.plist filenames
 * @private
 * @param {Xcode} xcode Opened Xcode project file
 * @return {Array} Plist filenames
 */
function getPlistFilenames(xcode) {
	return unique(
		flattenDeep(
			xcode.document.projects.map(project => {
				return project.targets.map(target => {
					return target.buildConfigurationsList.buildConfigurations.map(
						config => {
							return config.ast.value.get("buildSettings").get("INFOPLIST_FILE")
								.text;
						}
					);
				});
			})
		)
	);
}

/**
 * Versions your app
 * @param {Object} program commander/CLI-style options, camelCased
 * @param {string} projectPath Path to your React Native project
 * @return {Promise<string|Error>} A promise which resolves with the last commit hash
 */
function version(program, projectPath) {
	const prog = Object.assign({}, getDefaults(), program || {});

	const projPath = path.resolve(
		process.cwd(),
		projectPath || prog.args[0] || ""
	);

	const programOpts = Object.assign({}, prog, {
		android: path.join(projPath, prog.android),
		ios: path.join(projPath, prog.ios)
	});

	const targets = [].concat(programOpts.target, env.target).filter(Boolean);
	const appPkgJSONPath = path.join(projPath, "package.json");
	const MISSING_RN_DEP = "MISSING_RN_DEP";
	var appPkg;

	try {
		appPkg = require(appPkgJSONPath);

		if (!appPkg.dependencies["react-native"]) {
			throw new Error(MISSING_RN_DEP);
		}
	} catch (err) {
		if (err.message === MISSING_RN_DEP) {
			log({
				style: "red",
				text:
					"Is this the right folder? React Native isn't listed as a dependency in " +
					appPkgJSONPath
			});
		} else {
			log({
				style: "red",
				text: err.message
			});

			log({
				style: "red",
				text:
					"Is this the right folder? Looks like there isn't a package.json here"
			});
		}

		log({
			style: "yellow",
			text: "Pass the project path as an argument, see --help for usage"
		});

		if (program.outputHelp) {
			program.outputHelp();
		}

		process.exit(1);
	}

	var android;
	var ios;

	if (!targets.length || targets.indexOf("android") > -1) {
		android = new Promise(function(resolve, reject) {
			log({ text: "Versioning Android..." }, programOpts.quiet);

			var gradleFile;

			try {
				gradleFile = fs.readFileSync(programOpts.android, "utf8");
			} catch (err) {
				reject([
					{
						style: "red",
						text: "No gradle file found at " + programOpts.android
					},
					{
						style: "yellow",
						text: 'Use the "--android" option to specify the path manually'
					}
				]);
			}

			if (!programOpts.incrementBuild) {
				gradleFile = gradleFile.replace(
					/versionName "(.*)"/,
					'versionName "' + appPkg.version + '"'
				);
			}

			gradleFile = gradleFile.replace(/versionCode (\d+)/, function(
				match,
				cg1
			) {
				const newVersionCodeNumber = parseInt(cg1, 10) + 1;
				return "versionCode " + newVersionCodeNumber;
			});

			fs.writeFileSync(programOpts.android, gradleFile);
			log({ text: "Android updated" }, programOpts.quiet);
			resolve();
		});
	}

	if (!targets.length || targets.indexOf("ios") > -1) {
		ios = new Promise(function(resolve, reject) {
			log({ text: "Versioning iOS..." }, programOpts.quiet);

			if (program.legacy) {
				try {
					child.execSync("xcode-select --print-path", {
						stdio: ["ignore", "ignore", "pipe"]
					});
				} catch (err) {
					reject([
						{
							style: "red",
							text: err
						},
						{
							style: "yellow",
							text: "Looks like Xcode Command Line Tools aren't installed"
						},
						{
							text: "\n  Install:\n\n    $ xcode-select --install\n"
						}
					]);

					return;
				}

				const agvtoolOpts = {
					cwd: programOpts.ios
				};

				try {
					child.execSync("agvtool what-version", agvtoolOpts);
				} catch (err) {
					const stdout = err.stdout.toString().trim();

					reject(
						stdout.indexOf("directory") > -1
							? [
									{
										style: "red",
										text: "No project folder found at " + programOpts.ios
									},
									{
										style: "yellow",
										text: 'Use the "--ios" option to specify the path manually'
									}
								]
							: [
									{
										style: "red",
										text: stdout
									}
								]
					);

					return;
				}

				if (!programOpts.incrementBuild) {
					child.spawnSync(
						"agvtool",
						["new-marketing-version", appPkg.version],
						agvtoolOpts
					);
				}

				if (programOpts.resetBuild) {
					child.execSync("agvtool new-version -all 1", agvtoolOpts);
				} else {
					child.execSync("agvtool next-version -all", agvtoolOpts);
				}
			} else {
				// Find any folder ending in .xcodeproj
				const xcodeProjects = fs
					.readdirSync(programOpts.ios)
					.filter(file => /\.xcodeproj$/i.test(file));

				if (xcodeProjects.length < 1) {
					throw new Error(`Xcode project not found in "${programOpts.ios}"`);
				}

				const projectFolder = path.join(programOpts.ios, xcodeProjects[0]);
				const xcode = Xcode.open(path.join(projectFolder, "project.pbxproj"));
				const plistFilenames = getPlistFilenames(xcode);

				xcode.document.projects.forEach(project => {
					project.targets.forEach(target => {
						target.buildConfigurationsList.buildConfigurations.forEach(
							config => {
								if (target.name === appPkg.name) {
									config.patch({
										buildSettings: {
											CURRENT_PROJECT_VERSION: programOpts.resetBuild
												? 1
												: parseInt(
														config.ast.value
															.get("buildSettings")
															.get("CURRENT_PROJECT_VERSION").text,
														10
													) + 1
										}
									});
								}
							}
						);
					});

					const plistFiles = plistFilenames.map(filename => {
						return fs.readFileSync(
							path.join(programOpts.ios, filename),
							"utf8"
						);
					});

					const parsedPlistFiles = plistFiles.map(file => {
						return plist.parse(file);
					});

					parsedPlistFiles.forEach((json, index) => {
						fs.writeFileSync(
							path.join(programOpts.ios, plistFilenames[index]),
							plist.build(
								Object.assign(
									{},
									json,
									!programOpts.incrementBuild
										? {
												CFBundleShortVersionString: appPkg.version
											}
										: {},
									{
										CFBundleVersion: `${programOpts.resetBuild
											? 1
											: parseInt(json.CFBundleVersion, 10) + 1}`
									}
								)
							)
						);
					});

					plistFilenames.forEach((filename, index) => {
						const indent = detectIndent(plistFiles[index]);

						fs.writeFileSync(
							path.join(programOpts.ios, filename),
							stripIndents`
							<?xml version="1.0" encoding="UTF-8"?>
							<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
							<plist version="1.0">` +
								"\n" +
								beautify(
									fs
										.readFileSync(path.join(programOpts.ios, filename), "utf8")
										.match(/<dict>[\s\S]*<\/dict>/)[0],
									{
										end_with_newline: true,
										indent_char: indent.indent,
										indent_size: indent.amount
									}
								) +
								stripIndents`
							</plist>` +
								"\n"
						);
					});
				});

				xcode.save();
			}

			log({ text: "iOS updated" }, programOpts.quiet);
			resolve();
		});
	}

	return pSettle([android, ios].filter(Boolean))
		.then(function(result) {
			const errs = result
				.filter(function(item) {
					return item.isRejected;
				})
				.map(function(item) {
					return item.reason;
				});

			if (errs.length) {
				errs
					.reduce(function(a, b) {
						return a.concat(b);
					}, [])
					.forEach(function(err) {
						if (program.outputHelp) {
							err.text && log(err);
						}
					});

				if (program.outputHelp) {
					program.outputHelp();
				}

				throw errs
					.map(function(errGrp, index) {
						return errGrp
							.map(function(err) {
								return err.text;
							})
							.join(", ");
					})
					.join("; ");
			}

			const gitCmdOpts = {
				cwd: projPath
			};

			if (
				programOpts.amend ||
				(process.env.npm_lifecycle_event &&
					process.env.npm_lifecycle_event.indexOf("version") > -1 &&
					!programOpts.neverAmend)
			) {
				log({ text: "Amending..." }, programOpts.quiet);

				switch (process.env.npm_lifecycle_event) {
					case "version":
						child.spawnSync(
							"git",
							["add", programOpts.android, programOpts.ios],
							gitCmdOpts
						);

						break;

					case "postversion":
					default:
						child.execSync("git commit -a --amend --no-edit", gitCmdOpts);

						if (!programOpts.skipTag) {
							log({ text: "Adjusting Git tag..." }, programOpts.quiet);
							child.execSync(
								"git tag -f $(git tag --sort=v:refname | tail -1)",
								gitCmdOpts
							);
						}
				}
			}

			log(
				{
					style: "green",
					text: "Done"
				},
				programOpts.quiet
			);

			return child.execSync("git log -1 --pretty=%H", gitCmdOpts).toString();
		})
		.catch(function(err) {
			if (process.env.RNV_ENV === "ava") {
				console.error(err);
			}

			log({
				style: "red",
				text: "Done, with errors."
			});

			process.exit(1);
		});
}

module.exports = {
	getDefaults: getDefaults,
	getPlistFilenames: getPlistFilenames,
	version: version
};
<commit_msg>Fix #40 Improve indentation retention<commit_after>const beautify = require("js-beautify").html;
const child = require("child_process");
const detectIndent = require("detect-indent");
const flattenDeep = require("lodash.flattendeep");
const fs = require("fs");
const list = require("./util").list;
const log = require("./util").log;
const path = require("path");
const plist = require("plist");
const pSettle = require("p-settle");
const stripIndents = require("common-tags/lib/stripIndents");
const unique = require("lodash.uniq");
const Xcode = require("pbxproj-dom/xcode").Xcode;

/**
 * Custom type definition for Promises
 * @typedef Promise
 * @property {*} result See the implementing function for the resolve type and description
 * @property {Error} result Rejection error object
 */

const env = {
	target: process.env.RNV && list(process.env.RNV)
};

/**
 * Returns default values for some options, namely android/ios file/folder paths
 * @private
 * @return {Object} Defaults
 */
function getDefaults() {
	return {
		android: "android/app/build.gradle",
		ios: "ios"
	};
}

/**
 * Returns Info.plist filenames
 * @private
 * @param {Xcode} xcode Opened Xcode project file
 * @return {Array} Plist filenames
 */
function getPlistFilenames(xcode) {
	return unique(
		flattenDeep(
			xcode.document.projects.map(project => {
				return project.targets.map(target => {
					return target.buildConfigurationsList.buildConfigurations.map(
						config => {
							return config.ast.value.get("buildSettings").get("INFOPLIST_FILE")
								.text;
						}
					);
				});
			})
		)
	);
}

/**
 * Versions your app
 * @param {Object} program commander/CLI-style options, camelCased
 * @param {string} projectPath Path to your React Native project
 * @return {Promise<string|Error>} A promise which resolves with the last commit hash
 */
function version(program, projectPath) {
	const prog = Object.assign({}, getDefaults(), program || {});

	const projPath = path.resolve(
		process.cwd(),
		projectPath || prog.args[0] || ""
	);

	const programOpts = Object.assign({}, prog, {
		android: path.join(projPath, prog.android),
		ios: path.join(projPath, prog.ios)
	});

	const targets = [].concat(programOpts.target, env.target).filter(Boolean);
	const appPkgJSONPath = path.join(projPath, "package.json");
	const MISSING_RN_DEP = "MISSING_RN_DEP";
	var appPkg;

	try {
		appPkg = require(appPkgJSONPath);

		if (!appPkg.dependencies["react-native"]) {
			throw new Error(MISSING_RN_DEP);
		}
	} catch (err) {
		if (err.message === MISSING_RN_DEP) {
			log({
				style: "red",
				text:
					"Is this the right folder? React Native isn't listed as a dependency in " +
					appPkgJSONPath
			});
		} else {
			log({
				style: "red",
				text: err.message
			});

			log({
				style: "red",
				text:
					"Is this the right folder? Looks like there isn't a package.json here"
			});
		}

		log({
			style: "yellow",
			text: "Pass the project path as an argument, see --help for usage"
		});

		if (program.outputHelp) {
			program.outputHelp();
		}

		process.exit(1);
	}

	var android;
	var ios;

	if (!targets.length || targets.indexOf("android") > -1) {
		android = new Promise(function(resolve, reject) {
			log({ text: "Versioning Android..." }, programOpts.quiet);

			var gradleFile;

			try {
				gradleFile = fs.readFileSync(programOpts.android, "utf8");
			} catch (err) {
				reject([
					{
						style: "red",
						text: "No gradle file found at " + programOpts.android
					},
					{
						style: "yellow",
						text: 'Use the "--android" option to specify the path manually'
					}
				]);
			}

			if (!programOpts.incrementBuild) {
				gradleFile = gradleFile.replace(
					/versionName "(.*)"/,
					'versionName "' + appPkg.version + '"'
				);
			}

			gradleFile = gradleFile.replace(/versionCode (\d+)/, function(
				match,
				cg1
			) {
				const newVersionCodeNumber = parseInt(cg1, 10) + 1;
				return "versionCode " + newVersionCodeNumber;
			});

			fs.writeFileSync(programOpts.android, gradleFile);
			log({ text: "Android updated" }, programOpts.quiet);
			resolve();
		});
	}

	if (!targets.length || targets.indexOf("ios") > -1) {
		ios = new Promise(function(resolve, reject) {
			log({ text: "Versioning iOS..." }, programOpts.quiet);

			if (program.legacy) {
				try {
					child.execSync("xcode-select --print-path", {
						stdio: ["ignore", "ignore", "pipe"]
					});
				} catch (err) {
					reject([
						{
							style: "red",
							text: err
						},
						{
							style: "yellow",
							text: "Looks like Xcode Command Line Tools aren't installed"
						},
						{
							text: "\n  Install:\n\n    $ xcode-select --install\n"
						}
					]);

					return;
				}

				const agvtoolOpts = {
					cwd: programOpts.ios
				};

				try {
					child.execSync("agvtool what-version", agvtoolOpts);
				} catch (err) {
					const stdout = err.stdout.toString().trim();

					reject(
						stdout.indexOf("directory") > -1
							? [
									{
										style: "red",
										text: "No project folder found at " + programOpts.ios
									},
									{
										style: "yellow",
										text: 'Use the "--ios" option to specify the path manually'
									}
								]
							: [
									{
										style: "red",
										text: stdout
									}
								]
					);

					return;
				}

				if (!programOpts.incrementBuild) {
					child.spawnSync(
						"agvtool",
						["new-marketing-version", appPkg.version],
						agvtoolOpts
					);
				}

				if (programOpts.resetBuild) {
					child.execSync("agvtool new-version -all 1", agvtoolOpts);
				} else {
					child.execSync("agvtool next-version -all", agvtoolOpts);
				}
			} else {
				// Find any folder ending in .xcodeproj
				const xcodeProjects = fs
					.readdirSync(programOpts.ios)
					.filter(file => /\.xcodeproj$/i.test(file));

				if (xcodeProjects.length < 1) {
					throw new Error(`Xcode project not found in "${programOpts.ios}"`);
				}

				const projectFolder = path.join(programOpts.ios, xcodeProjects[0]);
				const xcode = Xcode.open(path.join(projectFolder, "project.pbxproj"));
				const plistFilenames = getPlistFilenames(xcode);

				xcode.document.projects.forEach(project => {
					project.targets.forEach(target => {
						target.buildConfigurationsList.buildConfigurations.forEach(
							config => {
								if (target.name === appPkg.name) {
									config.patch({
										buildSettings: {
											CURRENT_PROJECT_VERSION: programOpts.resetBuild
												? 1
												: parseInt(
														config.ast.value
															.get("buildSettings")
															.get("CURRENT_PROJECT_VERSION").text,
														10
													) + 1
										}
									});
								}
							}
						);
					});

					const plistFiles = plistFilenames.map(filename => {
						return fs.readFileSync(
							path.join(programOpts.ios, filename),
							"utf8"
						);
					});

					const parsedPlistFiles = plistFiles.map(file => {
						return plist.parse(file);
					});

					parsedPlistFiles.forEach((json, index) => {
						fs.writeFileSync(
							path.join(programOpts.ios, plistFilenames[index]),
							plist.build(
								Object.assign(
									{},
									json,
									!programOpts.incrementBuild
										? {
												CFBundleShortVersionString: appPkg.version
											}
										: {},
									{
										CFBundleVersion: `${programOpts.resetBuild
											? 1
											: parseInt(json.CFBundleVersion, 10) + 1}`
									}
								)
							)
						);
					});

					plistFilenames.forEach((filename, index) => {
						const indent = detectIndent(plistFiles[index]);

						fs.writeFileSync(
							path.join(programOpts.ios, filename),
							stripIndents`
							<?xml version="1.0" encoding="UTF-8"?>
							<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
							<plist version="1.0">` +
								"\n" +
								beautify(
									fs
										.readFileSync(path.join(programOpts.ios, filename), "utf8")
										.match(/<dict>[\s\S]*<\/dict>/)[0],
									Object.assign(
										{ end_with_newline: true },
										indent.type === "tab"
											? { indent_with_tabs: true }
											: { indent_size: indent.amount }
									)
								) +
								stripIndents`
							</plist>` +
								"\n"
						);
					});
				});

				xcode.save();
			}

			log({ text: "iOS updated" }, programOpts.quiet);
			resolve();
		});
	}

	return pSettle([android, ios].filter(Boolean))
		.then(function(result) {
			const errs = result
				.filter(function(item) {
					return item.isRejected;
				})
				.map(function(item) {
					return item.reason;
				});

			if (errs.length) {
				errs
					.reduce(function(a, b) {
						return a.concat(b);
					}, [])
					.forEach(function(err) {
						if (program.outputHelp) {
							err.text && log(err);
						}
					});

				if (program.outputHelp) {
					program.outputHelp();
				}

				throw errs
					.map(function(errGrp, index) {
						return errGrp
							.map(function(err) {
								return err.text;
							})
							.join(", ");
					})
					.join("; ");
			}

			const gitCmdOpts = {
				cwd: projPath
			};

			if (
				programOpts.amend ||
				(process.env.npm_lifecycle_event &&
					process.env.npm_lifecycle_event.indexOf("version") > -1 &&
					!programOpts.neverAmend)
			) {
				log({ text: "Amending..." }, programOpts.quiet);

				switch (process.env.npm_lifecycle_event) {
					case "version":
						child.spawnSync(
							"git",
							["add", programOpts.android, programOpts.ios],
							gitCmdOpts
						);

						break;

					case "postversion":
					default:
						child.execSync("git commit -a --amend --no-edit", gitCmdOpts);

						if (!programOpts.skipTag) {
							log({ text: "Adjusting Git tag..." }, programOpts.quiet);
							child.execSync(
								"git tag -f $(git tag --sort=v:refname | tail -1)",
								gitCmdOpts
							);
						}
				}
			}

			log(
				{
					style: "green",
					text: "Done"
				},
				programOpts.quiet
			);

			return child.execSync("git log -1 --pretty=%H", gitCmdOpts).toString();
		})
		.catch(function(err) {
			if (process.env.RNV_ENV === "ava") {
				console.error(err);
			}

			log({
				style: "red",
				text: "Done, with errors."
			});

			process.exit(1);
		});
}

module.exports = {
	getDefaults: getDefaults,
	getPlistFilenames: getPlistFilenames,
	version: version
};
<|endoftext|>


<commit_before>#! /usr/bin/env node
const process = require("process");
const fs = require("fs");
const path = require("path");

const semver = require("semver");
const Config = require("truffle-config");
const Resolver = require("truffle-resolver");
const tsort = require("tsort");
const SolidityParser = require("solidity-parser");

const PRAGAMA_SOLIDITY_VERSION_REGEX = /^\s*pragma\ssolidity\s+(.*?)\s*;/;
const SUPPORTED_VERSION_DECLARATION_REGEX = /^\^?\d+(\.\d+){1,2}$/;

function unique(array) {
  return [...new Set(array)];
}

function resolve(importPath) {
  const config = Config.default();
  const resolver = new Resolver(config);

  return new Promise((resolve, reject) => {
    resolver.resolve(importPath, (err, fileContents, filePath) => {
      if (err) {
        reject(err);
        return;
      }

      resolve({ fileContents, filePath });
    });
  });
}

function getDependencies(filePath, fileContents) {
  const dependencies = [];

  let imports;
  try {
    imports = SolidityParser.parse(fileContents, "imports");
  } catch (error) {
    throw new Error(
      "Could not parse " + filePath + " for extracting its imports."
    );
  }

  for (let dependency of imports) {
    if (dependency.startsWith("./") || dependency.startsWith("../")) {
      dependency =
        filePath.substring(0, filePath.lastIndexOf("/") + 1) + dependency;
      dependency = path.normalize(dependency);
    }

    dependencies.push(dependency);
  }

  return dependencies;
}

async function dependenciesDfs(graph, visitedFiles, filePath) {
  visitedFiles.push(filePath);

  const resolved = await resolve(filePath);

  const dependencies = getDependencies(
    resolved.filePath,
    resolved.fileContents
  );

  for (let dependency of dependencies) {
    graph.add(dependency, filePath);

    const resolvedDependency = await resolve(dependency);

    if (!visitedFiles.includes(dependency)) {
      await dependenciesDfs(graph, visitedFiles, dependency);
    }
  }
}

async function getSortedFilePaths(entryPoints) {
  const graph = tsort();
  const visitedFiles = [];

  for (const entryPoint of entryPoints) {
    await dependenciesDfs(graph, visitedFiles, entryPoint);
  }

  const topologicalSortedFiles = graph.sort();

  // If an enrty has no dependency it won't be included in the graph, so we
  // add them and then dedup the array
  const withEntries = topologicalSortedFiles.concat(entryPoints);

  const files = unique(withEntries);

  return files;
}

async function printFileWithoutPragma(filePath) {
  const resolved = await resolve(filePath);
  const output = resolved.fileContents.replace(
    PRAGAMA_SOLIDITY_VERSION_REGEX,
    ""
  );

  console.log(output.trim());
}

async function getFileCompilerVersionDeclaration(filePath) {
  const resolved = await resolve(filePath);

  const matched = resolved.fileContents.match(PRAGAMA_SOLIDITY_VERSION_REGEX);

  if (matched === null) {
    return undefined;
  }

  const version = matched[1];

  if (!SUPPORTED_VERSION_DECLARATION_REGEX.test(version)) {
    throw new Error(
      "Unsupported compiler version declaration in  " +
        filePath +
        ": " +
        version +
        ". Only pinned or ^ versions are supported."
    );
  }

  return version;
}

async function normalizeCompilerVersionDeclarations(files) {
  let pinnedVersion;
  let pinnedVersionFile;

  let maxCaretVersion;
  let maxCaretVersionFile;

  for (const file of files) {
    const version = await getFileCompilerVersionDeclaration(file);

    if (version === undefined) {
      continue;
    }

    if (version.startsWith("^")) {
      if (maxCaretVersion == undefined) {
        maxCaretVersion = version;
        maxCaretVersionFile = file;
      } else {
        if (semver.gt(version.substr(1), maxCaretVersion.substr(1))) {
          maxCaretVersion = version;
          maxCaretVersionFile = file;
        }
      }
    } else {
      if (pinnedVersion === undefined) {
        pinnedVersion = version;
        pinnedVersionFile = file;
      } else if (pinnedVersion !== version) {
        throw new Error(
          "Differernt pinned compiler versions in " +
            pinnedVersionFile +
            " and " +
            file
        );
      }
    }

    if (maxCaretVersion !== undefined && pinnedVersion !== undefined) {
      if (!semver.satisfies(pinnedVersion, maxCaretVersion)) {
        throw new Error(
          "Incompatible compiler version declarations in " +
            maxCaretVersionFile +
            " and " +
            pinnedVersionFile
        );
      }
    }
  }

  if (pinnedVersion !== undefined) {
    return pinnedVersion;
  }

  return maxCaretVersion;
}

async function printContactenation(files) {
  const version = await normalizeCompilerVersionDeclarations(files);

  if (version) {
    console.log("pragma solidity " + version + ";");
  }

  for (const file of files) {
    console.log("\n// File: " + file + "\n");
    await printFileWithoutPragma(file);
  }
}

async function main(files) {
  if (files.length == 0) {
    console.error("Usage: truffle-flattener <files>");
  }

  try {
    const sortedFiles = await getSortedFilePaths(files);
    await printContactenation(sortedFiles);
  } catch (error) {
    console.log(error);
  }
}

main(process.argv.slice(2));
<commit_msg>Remove import from concated solidity output<commit_after>#! /usr/bin/env node
const process = require("process");
const fs = require("fs");
const path = require("path");

const semver = require("semver");
const Config = require("truffle-config");
const Resolver = require("truffle-resolver");
const tsort = require("tsort");
const SolidityParser = require("solidity-parser");

const PRAGAMA_SOLIDITY_VERSION_REGEX = /^\s*pragma\ssolidity\s+(.*?)\s*;/;
const SUPPORTED_VERSION_DECLARATION_REGEX = /^\^?\d+(\.\d+){1,2}$/;
const IMPORT_SOLIDITY_REGEX = /^.*import.*$/mg;

function unique(array) {
  return [...new Set(array)];
}

function resolve(importPath) {
  const config = Config.default();
  const resolver = new Resolver(config);

  return new Promise((resolve, reject) => {
    resolver.resolve(importPath, (err, fileContents, filePath) => {
      if (err) {
        reject(err);
        return;
      }

      resolve({ fileContents, filePath });
    });
  });
}

function getDependencies(filePath, fileContents) {
  const dependencies = [];

  let imports;
  try {
    imports = SolidityParser.parse(fileContents, "imports");
  } catch (error) {
    throw new Error(
      "Could not parse " + filePath + " for extracting its imports."
    );
  }

  for (let dependency of imports) {
    if (dependency.startsWith("./") || dependency.startsWith("../")) {
      dependency =
        filePath.substring(0, filePath.lastIndexOf("/") + 1) + dependency;
      dependency = path.normalize(dependency);
    }

    dependencies.push(dependency);
  }

  return dependencies;
}

async function dependenciesDfs(graph, visitedFiles, filePath) {
  visitedFiles.push(filePath);

  const resolved = await resolve(filePath);

  const dependencies = getDependencies(
    resolved.filePath,
    resolved.fileContents
  );

  for (let dependency of dependencies) {
    graph.add(dependency, filePath);

    const resolvedDependency = await resolve(dependency);

    if (!visitedFiles.includes(dependency)) {
      await dependenciesDfs(graph, visitedFiles, dependency);
    }
  }
}

async function getSortedFilePaths(entryPoints) {
  const graph = tsort();
  const visitedFiles = [];

  for (const entryPoint of entryPoints) {
    await dependenciesDfs(graph, visitedFiles, entryPoint);
  }

  const topologicalSortedFiles = graph.sort();

  // If an enrty has no dependency it won't be included in the graph, so we
  // add them and then dedup the array
  const withEntries = topologicalSortedFiles.concat(entryPoints);

  const files = unique(withEntries);

  return files;
}

async function printFileWithoutPragma(filePath) {
  const resolved = await resolve(filePath);
  const output = resolved.fileContents.replace(
    PRAGAMA_SOLIDITY_VERSION_REGEX,
    ""
  ).replace(IMPORT_SOLIDITY_REGEX,"");

  console.log(output.trim());
}

async function getFileCompilerVersionDeclaration(filePath) {
  const resolved = await resolve(filePath);

  const matched = resolved.fileContents.match(PRAGAMA_SOLIDITY_VERSION_REGEX);

  if (matched === null) {
    return undefined;
  }

  const version = matched[1];

  if (!SUPPORTED_VERSION_DECLARATION_REGEX.test(version)) {
    throw new Error(
      "Unsupported compiler version declaration in  " +
        filePath +
        ": " +
        version +
        ". Only pinned or ^ versions are supported."
    );
  }

  return version;
}

async function normalizeCompilerVersionDeclarations(files) {
  let pinnedVersion;
  let pinnedVersionFile;

  let maxCaretVersion;
  let maxCaretVersionFile;

  for (const file of files) {
    const version = await getFileCompilerVersionDeclaration(file);

    if (version === undefined) {
      continue;
    }

    if (version.startsWith("^")) {
      if (maxCaretVersion == undefined) {
        maxCaretVersion = version;
        maxCaretVersionFile = file;
      } else {
        if (semver.gt(version.substr(1), maxCaretVersion.substr(1))) {
          maxCaretVersion = version;
          maxCaretVersionFile = file;
        }
      }
    } else {
      if (pinnedVersion === undefined) {
        pinnedVersion = version;
        pinnedVersionFile = file;
      } else if (pinnedVersion !== version) {
        throw new Error(
          "Differernt pinned compiler versions in " +
            pinnedVersionFile +
            " and " +
            file
        );
      }
    }

    if (maxCaretVersion !== undefined && pinnedVersion !== undefined) {
      if (!semver.satisfies(pinnedVersion, maxCaretVersion)) {
        throw new Error(
          "Incompatible compiler version declarations in " +
            maxCaretVersionFile +
            " and " +
            pinnedVersionFile
        );
      }
    }
  }

  if (pinnedVersion !== undefined) {
    return pinnedVersion;
  }

  return maxCaretVersion;
}

async function printContactenation(files) {
  const version = await normalizeCompilerVersionDeclarations(files);

  if (version) {
    console.log("pragma solidity " + version + ";");
  }

  for (const file of files) {
    console.log("\n// File: " + file + "\n");
    await printFileWithoutPragma(file);
  }
}

async function main(files) {
  if (files.length == 0) {
    console.error("Usage: truffle-flattener <files>");
  }

  try {
    const sortedFiles = await getSortedFilePaths(files);
    await printContactenation(sortedFiles);
  } catch (error) {
    console.log(error);
  }
}

main(process.argv.slice(2));
<|endoftext|>


<commit_before>

function find(array, test) {
  for(var i in array)
    if(test(array[i], i, array))
      return array[i]
}

module.exports = function (tagCodec) {

  var codecs = []

  function getRule (value) {
    return find(codecs, function (rule) { return rule.test(value) })
  }

  function _length (value, rule) {
    return (
      (tagCodec.length || tagCodec.encodingLength(rule.match))
    + (rule.codec.length || rule.codec.encodingLength(value))
    )
  }

  return {
    encode: function encode (value, buffer, offset) {
      var rule = find(codecs, function (rule) { return rule.test(value) })
      if(!rule) throw new Error('no encoding for:'+JSON.stringify(value))
      if(!buffer) {
        buffer = new Buffer(_length(value, rule))
        offset = 0
      }
      offset = offset | 0
      tagCodec.encode(rule.match, buffer, offset)
      offset += tagCodec.encode.bytesWritten
      rule.codec.encode(value, buffer, offset)
      encode.bytesWritten =
          tagCodec.encode.bytesWritten
        + rule.codec.encode.bytesWritten
      return buffer
    },
    decode: function decode (buffer, offset) {
      offset = offset | 0
      var match = tagCodec.decode(buffer, offset)
      if(match === undefined) return undefined
      var rule = find(codecs, function (e) { return e.match === match })
      offset += tagCodec.decode.bytesRead
      var value = rule.codec.decode(buffer, offset)
      decode.bytesRead =
          tagCodec.decode.bytesRead
        + rule.codec.decode.bytesRead
      return value
    },
    encodingLength: function (value) { return _length(value, getRule(value)) },
    type: function (match, codec, test) {
      codecs.push({match: match, codec: codec, test: test})
      return this
    }
  }
}
<commit_msg>new .bytes api<commit_after>

function find(array, test) {
  for(var i in array)
    if(test(array[i], i, array))
      return array[i]
}

module.exports = function (tagCodec) {

  var codecs = []

  function getRule (value) {
    return find(codecs, function (rule) { return rule.test(value) })
  }

  function _length (value, rule) {
    return (
      (tagCodec.length || tagCodec.encodingLength(rule.match))
    + (rule.codec.length || rule.codec.encodingLength(value))
    )
  }

  return {
    encode: function encode (value, buffer, offset) {
      var rule = find(codecs, function (rule) { return rule.test(value) })
      if(!rule) throw new Error('no encoding for:'+JSON.stringify(value))
      if(!buffer) {
        buffer = new Buffer(_length(value, rule))
        offset = 0
      }
      offset = offset | 0
      tagCodec.encode(rule.match, buffer, offset)
      offset += tagCodec.encode.bytes
      rule.codec.encode(value, buffer, offset)
      encode.bytes = tagCodec.encode.bytes + rule.codec.encode.bytes

      return buffer
    },
    decode: function decode (buffer, offset) {
      offset = offset | 0
      var match = tagCodec.decode(buffer, offset)
      if(match === undefined) return undefined
      var rule = find(codecs, function (e) { return e.match === match })
      offset += tagCodec.decode.bytes
      var value = rule.codec.decode(buffer, offset)
      decode.bytes = tagCodec.decode.bytes + rule.codec.decode.bytes
      return value
    },
    encodingLength: function (value) { return _length(value, getRule(value)) },
    type: function (match, codec, test) {
      codecs.push({match: match, codec: codec, test: test})
      return this
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

/** A drawing component for mapboxgl
 * @class mapbox.Draw
 *
 * @param {Object} options
 * @param {String} [options.position=top-right] A string indicating the control's position on the map. Options are `topright`, `topleft`, `bottomright`, `bottomleft`
 * @returns {Draw} `this`
 * @example
 * var map = new mapboxgl.Map({
 *   container: 'map',
 *   style: 'https://www.mapbox.com/mapbox-gl-styles/styles/outdoors-v7.json'
 * });
 *
 * // Initialize the drawing component
 * map.addControl(mapboxgl.Draw());
 */
mapboxgl.Draw = require('./src/draw.js');
<commit_msg>Fixed documentation typo<commit_after>'use strict';

var mapboxgl = require('mapbox-gl');
/** A drawing component for mapboxgl
 * @class mapbox.Draw
 *
 * @param {Object} options
 * @param {String} [options.position=top-left] A string indicating the control's position on the map. Options are `topright`, `topleft`, `bottomright`, `bottomleft`
 * @returns {Draw} `this`
 * @example
 * var map = new mapboxgl.Map({
 *   container: 'map',
 *   style: 'https://www.mapbox.com/mapbox-gl-styles/styles/outdoors-v7.json'
 * });
 *
 * // Initialize the drawing component
 * map.addControl(mapboxgl.Draw());
 */
mapboxgl.Draw = require('./src/draw.js');
<|endoftext|>


<commit_before>'use strict';
const electron = require('electron');
const app = electron.app;
const windowStateKeeper = require('electron-window-state');

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
let mainWindow;

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function createMainWindow() {
	const mainWindowState = windowStateKeeper({
		defaultWidth: 1200,
		defaultHeight: 800
	});

	let win = new electron.BrowserWindow({
		'x': mainWindowState.x,
		'y': mainWindowState.y,
		'width': mainWindowState.width,
		'height': mainWindowState.height
	});

	// Let us register listeners on the window, so we can update the state
	// automatically (the listeners will be removed when the window is closed)
	// and restore the maximized or full screen state
	mainWindowState.manage(win);

	win.loadURL(`file://${__dirname}/index.html`);
	win.on('closed', onClosed);

	return win;
}

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

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
});
<commit_msg>Fixed some style issues<commit_after>'use strict';
const electron = require('electron');
const app = electron.app;
const windowStateKeeper = require('electron-window-state');
const storage = require('electron-json-storage');

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

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
let mainWindow;

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function createMainWindow() {
	const mainWindowState = windowStateKeeper({
		defaultWidth: 1200,
		defaultHeight: 800
	});

	let win = new electron.BrowserWindow({
		x: mainWindowState.x,
		y: mainWindowState.y,
		width: mainWindowState.width,
		height: mainWindowState.height
	});

	// Let us register listeners on the window, so we can update the state
	// automatically (the listeners will be removed when the window is closed)
	// and restore the maximized or full screen state
	mainWindowState.manage(win);

	win.loadURL(`file://${__dirname}/index.html`);
	win.on('closed', onClosed);

	return win;
}

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

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();

});
<|endoftext|>


<commit_before>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];
  $scope.level1 = [];
 $http.get("level2.json")
    .then(function(response) {
        $scope.items = response.data;
    });

 $http.get("level1.json")
    .then(function(response) {
        $scope.level1 = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<commit_msg>Update app.js<commit_after>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];
  $scope.level1 = [];
  console.log('level2');
 $http.get("level2.json")
    .then(function(response) {
    	console.log('load');
        $scope.items = response.data;
    });
console.log('level1');
 $http.get("level1.json")
    .then(function(response) {
    	console.log('load');
        $scope.level1 = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<|endoftext|>


<commit_before>var app       = require(__dirname + '/app.js')
  , co        = require('co')
  , fs        = require('co-fs')
  , minimist  = require('minimist')
  , path      = require('path')
  , task      = require(__dirname + '/lib/task')
  , util      = require('util')
  ;

var addProject = function*(argv) {
  var args = minimist(argv);

  var provider   = args['_'][0]
    , repository = args['_'][1]
    , branch     = args['_'][2]
    , host       = args.h || args.host
    , options    = args.o || args.options
    , preCmds    = args['_'].slice(3)
    , url        = args.u || args.url
    ;

  yield task.addProject(provider, repository, branch, host, options, preCmds, url);
};

var addRemote = function*(argv) {
  var args = minimist(argv);
  var user = args['_'][0];
  var host = args['_'][1];

  yield task.addRemote(user, host);
};

var startApp = false, stopApp = false;

co(function*() {
  var argv = process.argv;
  var usage = util.format([
      'Usage: %s <start|stop|add-project|add-remote> [AddOptions|AddRemoteOptions]'
    , 'Add Options:'
    , '\tCode Host that provides webhooks: <github|bitbucket>'
    , '\tName of repository'
    , '\tName of branch'
    , '\tComma-separated list of remote hosts: host1.example.com,host2.example.com,etc.'
    , '\t-o --options\tContainer runtime options'
    , '\t-u --url\tURL of private code repository'
    , '\tThe rest are assumed to be pre-commands'
    , ''
    , 'Add-Remote Options'
    , '\tRemote User'
    , '\tRemote Host'
  ].join('\n'), argv.slice(0, 2).join(' '));

  var cmd = argv[2];

  switch (cmd) {
    case 'start':
      startApp = true;
      yield fs.writeFile('lanaci.pid', process.pid);
      break;
    case 'stop':
      stopApp = true;
      break;
    case 'add-project':
      yield addProject(argv.slice(3));
      break;
    case 'add-remote':
      yield addRemote(argv.slice(3));
      break;
    case '-h':
      console.log(usage);
      break;
    default:
      console.error(usage);
  }
});

// This is needed because co() kills the server
if (startApp) {
  app.createApp().listen(6823, function () {
    console.log('Server started!');
  });
}
else if (stopApp) {
  co(function*() {
    try {
      var pid = yield fs.readFile('lanaci.pid');
      process.kill(parseInt(pid), 'SIGKILL');
      yield fs.unlink('lanaci.pid');
    }
    catch (err) {
      console.error('LanaCI is not started!');
    }
  });
}
<commit_msg>Changed option to specify host from -h to -H for addProject<commit_after>var app       = require(__dirname + '/app.js')
  , co        = require('co')
  , fs        = require('co-fs')
  , minimist  = require('minimist')
  , path      = require('path')
  , task      = require(__dirname + '/lib/task')
  , util      = require('util')
  ;

var addProject = function*(argv) {
  var args = minimist(argv);

  var provider   = args['_'][0]
    , repository = args['_'][1]
    , branch     = args['_'][2]
    , host       = args.H || args.host
    , options    = args.o || args.options
    , preCmds    = args['_'].slice(3)
    , url        = args.u || args.url
    ;

  yield task.addProject(provider, repository, branch, host, options, preCmds, url);
};

var addRemote = function*(argv) {
  var args = minimist(argv);
  var user = args['_'][0];
  var host = args['_'][1];

  yield task.addRemote(user, host);
};

var startApp = false, stopApp = false;

co(function*() {
  var argv = process.argv;
  var usage = util.format([
      'Usage: %s <start|stop|add-project|add-remote> [AddOptions|AddRemoteOptions]'
    , 'Add Options:'
    , '\tCode Host that provides webhooks: <github|bitbucket>'
    , '\tName of repository'
    , '\tName of branch'
    , '\t-H --host\tName of remote host'
    , '\t-o --options\tContainer runtime options'
    , '\t-u --url\tURL of private code repository'
    , '\tThe rest are assumed to be pre-commands'
    , ''
    , 'Add-Remote Options'
    , '\tRemote User'
    , '\tRemote Host'
  ].join('\n'), argv.slice(0, 2).join(' '));

  var cmd = argv[2];

  switch (cmd) {
    case 'start':
      startApp = true;
      yield fs.writeFile('lanaci.pid', process.pid);
      break;
    case 'stop':
      stopApp = true;
      break;
    case 'add-project':
      yield addProject(argv.slice(3));
      break;
    case 'add-remote':
      yield addRemote(argv.slice(3));
      break;
    case '-h':
      console.log(usage);
      break;
    default:
      console.error(usage);
  }
});

// This is needed because co() kills the server
if (startApp) {
  app.createApp().listen(6823, function () {
    console.log('Server started!');
  });
}
else if (stopApp) {
  co(function*() {
    try {
      var pid = yield fs.readFile('lanaci.pid');
      process.kill(parseInt(pid), 'SIGKILL');
      yield fs.unlink('lanaci.pid');
    }
    catch (err) {
      console.error('LanaCI is not started!');
    }
  });
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import {
  View,
  Image,
  StyleSheet,
  TouchableOpacity,
  Platform
} from 'react-native'
import ImagePicker from 'react-native-image-picker'
import ImageResizer from 'react-native-image-resizer'
import RNFS from 'react-native-fs'

export default class PhotoUpload extends React.Component {
  static propTypes = {
    containerStyle: PropTypes.object,
    photoPickerTitle: PropTypes.string,
    height: PropTypes.number,
    width: PropTypes.number,
    format: PropTypes.string,
    quality: PropTypes.number,
    onPhotoSelect: PropTypes.func, // returns the base64 string of uploaded photo
    onError: PropTypes.func, // if any error occur with response
    onTapCustomButton: PropTypes.func, // on tap custom button
    onStart: PropTypes.func, // when user starts (useful for loading, etc)
    onCancel: PropTypes.func, // when user cancel
    onResponse: PropTypes.func, // on response exists!
    onRender: PropTypes.func, // after render
    onResizedImageUri: PropTypes.func, // when image resized is ready
    imagePickerProps: PropTypes.object // react-native-image-picker props
  }

  state = {
    height: this.props.height || 300,
    width: this.props.width || 300,
    format: this.props.format || 'JPEG',
    quality: this.props.quality || 80,
    buttonDisabled: false
  }

  options = {
    title: this.props.pickerTitle || 'Select Photo',
    storageOptions: {
      skipBackup: true,
      path: 'images'
    },
    ...this.props.imagePickerProps
  }

  openImagePicker = () => {
    this.setState({buttonDisabled: true})
    if (this.props.onStart) this.props.onStart()

    // get image from image picker
    ImagePicker.showImagePicker(this.options, async response => {
      this.setState({buttonDisabled: false})
      console.log('Response = ', response)
      let rotation = 0
      const {originalRotation} = response

      if (this.props.onResponse) this.props.onResponse(response)

      if (response.didCancel) {
        console.log('User cancelled image picker')
        if (this.props.onCancel) this.props.onCancel('User cancelled image picker')
        return
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error)
        if (this.props.onError) this.props.onError(response.error)
        return
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton)
        if (this.props.onTapCustomButton) this.props.onTapCustomButton(response.customButton)
        return
      }

      let { height, width, quality, format } = this.state

      //Determining rotation param
      if ( originalRotation === 90) {
        rotation = 90
      } else if (originalRotation === 180) {
        //For a few images rotation is 180.
        rotation = -180
      } else if ( originalRotation === 270 )  {
        //When taking images with the front camera (selfie), the rotation is 270.
        rotation = -90
      }
      // resize image
      const resizedImageUri = await ImageResizer.createResizedImage(
        `data:image/jpeg;base64,${response.data}`,
        height,
        width,
        format,
        quality,
        rotation
      )

      if (this.props.onResizedImageUri) this.props.onResizedImageUri(resizedImageUri)

      const filePath = Platform.OS === 'android' && resizedImageUri.uri.replace
        ? resizedImageUri.uri.replace('file:/data', '/data')
        : resizedImageUri.uri

      // convert image back to base64 string
      const photoData = await RNFS.readFile(filePath, 'base64')
      let source = { uri: resizedImageUri.uri }
      this.setState({
        avatarSource: source
      })

      // handle photo in props functions as data string
      if (this.props.onPhotoSelect) this.props.onPhotoSelect(photoData)
    })
  }

  renderChildren = props => {
    return React.Children.map(props.children, child => {
      if (child && child.type === Image && this.state.avatarSource) {
        return React.cloneElement(child, {
          source: this.state.avatarSource
        })
      } else return child
    })
  }

  componentDidUpdate() {
    if (this.props.onAfterRender) this.props.onAfterRender(this.state)
  }

  render() {
    return (
      <View style={[styles.container, this.props.containerStyle]}>
        <TouchableOpacity
          onPress={this.openImagePicker}
          disabled={this.state.buttonDisabled}
        >
          {this.renderChildren(this.props)}
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
})
<commit_msg>Fix prop name typo #44<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {
  View,
  Image,
  StyleSheet,
  TouchableOpacity,
  Platform
} from 'react-native'
import ImagePicker from 'react-native-image-picker'
import ImageResizer from 'react-native-image-resizer'
import RNFS from 'react-native-fs'

export default class PhotoUpload extends React.Component {
  static propTypes = {
    containerStyle: PropTypes.object,
    photoPickerTitle: PropTypes.string,
    height: PropTypes.number,
    width: PropTypes.number,
    format: PropTypes.string,
    quality: PropTypes.number,
    onPhotoSelect: PropTypes.func, // returns the base64 string of uploaded photo
    onError: PropTypes.func, // if any error occur with response
    onTapCustomButton: PropTypes.func, // on tap custom button
    onStart: PropTypes.func, // when user starts (useful for loading, etc)
    onCancel: PropTypes.func, // when user cancel
    onResponse: PropTypes.func, // on response exists!
    onRender: PropTypes.func, // after render
    onResizedImageUri: PropTypes.func, // when image resized is ready
    imagePickerProps: PropTypes.object // react-native-image-picker props
  }

  state = {
    height: this.props.height || 300,
    width: this.props.width || 300,
    format: this.props.format || 'JPEG',
    quality: this.props.quality || 80,
    buttonDisabled: false
  }

  options = {
    title: this.props.photoPickerTitle || 'Select Photo',
    storageOptions: {
      skipBackup: true,
      path: 'images'
    },
    ...this.props.imagePickerProps
  }

  openImagePicker = () => {
    this.setState({buttonDisabled: true})
    if (this.props.onStart) this.props.onStart()

    // get image from image picker
    ImagePicker.showImagePicker(this.options, async response => {
      this.setState({buttonDisabled: false})
      console.log('Response = ', response)
      let rotation = 0
      const {originalRotation} = response

      if (this.props.onResponse) this.props.onResponse(response)

      if (response.didCancel) {
        console.log('User cancelled image picker')
        if (this.props.onCancel) this.props.onCancel('User cancelled image picker')
        return
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error)
        if (this.props.onError) this.props.onError(response.error)
        return
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton)
        if (this.props.onTapCustomButton) this.props.onTapCustomButton(response.customButton)
        return
      }

      let { height, width, quality, format } = this.state

      //Determining rotation param
      if ( originalRotation === 90) {
        rotation = 90
      } else if (originalRotation === 180) {
        //For a few images rotation is 180.
        rotation = -180
      } else if ( originalRotation === 270 )  {
        //When taking images with the front camera (selfie), the rotation is 270.
        rotation = -90
      }
      // resize image
      const resizedImageUri = await ImageResizer.createResizedImage(
        `data:image/jpeg;base64,${response.data}`,
        height,
        width,
        format,
        quality,
        rotation
      )

      if (this.props.onResizedImageUri) this.props.onResizedImageUri(resizedImageUri)

      const filePath = Platform.OS === 'android' && resizedImageUri.uri.replace
        ? resizedImageUri.uri.replace('file:/data', '/data')
        : resizedImageUri.uri

      // convert image back to base64 string
      const photoData = await RNFS.readFile(filePath, 'base64')
      let source = { uri: resizedImageUri.uri }
      this.setState({
        avatarSource: source
      })

      // handle photo in props functions as data string
      if (this.props.onPhotoSelect) this.props.onPhotoSelect(photoData)
    })
  }

  renderChildren = props => {
    return React.Children.map(props.children, child => {
      if (child && child.type === Image && this.state.avatarSource) {
        return React.cloneElement(child, {
          source: this.state.avatarSource
        })
      } else return child
    })
  }

  componentDidUpdate() {
    if (this.props.onAfterRender) this.props.onAfterRender(this.state)
  }

  render() {
    return (
      <View style={[styles.container, this.props.containerStyle]}>
        <TouchableOpacity
          onPress={this.openImagePicker}
          disabled={this.state.buttonDisabled}
        >
          {this.renderChildren(this.props)}
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
})
<|endoftext|>


<commit_before>var gps = require("gps-tracking");
var db = require('./config/db');
var RawData = require('./models/raw_log').collection,
  GpsData = require('./models/gps_log').collection;
var express = require('express');
var webApp = express();

var options = {
    'debug': false, //We don't want to debug info automatically. We are going to log everything manually so you can check what happens everywhere
    'port': 8090,
    'device_adapter': "TK103"
  },
  CData = new RawData(),
  GData = new GpsData();

webApp.get('/', function(req, res) {
  res.send('hello user');
});

webApp.get('/raw-data', function(req, res) {
  CData.find()
    .orderBy('id', 'desc')
    .all()
    .then(function(models) {
      res.json(models);
    });
});

webApp.get('/gps-data', function(req, res) {
  GData.find()
    .orderBy('id', 'desc')
    .all()
    .then(function(models) {
      res.json(models);
    });
});

webApp.listen(4000);

var server = gps.server(options, function(device, connection) {

  device.on("connected", function(data) {
    console.log("I'm a new device connected");
    return data;
  });

  device.on("login_request", function(device_id, msg_parts) {

    console.log('Hey! I want to start transmiting my position. Please accept me. My name is ' + device_id);
    this.login_authorized(true);
    console.log("Ok, " + device_id + ", you're accepted!");
  });

  device.on("ping", function(data) {
    var devId = this.getUID(),
      gdata = GData.model({
        device_id: devId,
        latitude: data.latitude,
        longitude: data.longitude,
        timestamp: Math.floor(Date.now() / 1000)
      });

    gdata.save()
      .catch(function(error) {
        console.log('Could not validated:', error);
      });
    //this = device
    // console.log("I'm here: " + data.latitude + ", " + data.longitude + " (" + this.getUID() + ")");
    //Look what informations the device sends to you (maybe velocity, gas level, etc)
    //console.log(data);
    return data;
  });

  device.on("alarm", function(alarm_code, alarm_data, msg_data) {
    console.log("Help! Something happend: " + alarm_code + " (" + alarm_data.msg + ")");
  });

  //Also, you can listen on the native connection object
  connection.on('data', function(data) {
    var textData = data.toString(),
      sdata = CData.model({
        data: textData,
        ts: Math.floor(Date.now() / 1000)
      });

    sdata.save()
      .then(function(model) {
        // var id = model.get('id');
        // console.log('Created new post with ID:', model);
      })
      .catch(function(error) {
        console.log('Could not validated:', error);
      });
  });

});
<commit_msg>force auth<commit_after>var gps = require("gps-tracking");
var db = require('./config/db');
var RawData = require('./models/raw_log').collection,
  GpsData = require('./models/gps_log').collection;
var express = require('express');
var webApp = express();

var options = {
    'debug': false, //We don't want to debug info automatically. We are going to log everything manually so you can check what happens everywhere
    'port': 8090,
    'device_adapter': "TK103"
  },
  CData = new RawData(),
  GData = new GpsData();

webApp.get('/', function(req, res) {
  res.send('hello user');
});

webApp.get('/raw-data', function(req, res) {
  CData.find()
    .orderBy('id', 'desc')
    .all()
    .then(function(models) {
      res.json(models);
    });
});

webApp.get('/gps-data', function(req, res) {
  GData.find()
    .orderBy('id', 'desc')
    .all()
    .then(function(models) {
      res.json(models);
    });
});

webApp.listen(4000);

var server = gps.server(options, function(device, connection) {

  device.on("connected", function(data) {
    console.log("I'm a new device connected");
    this.login_authorized(true);
    return data;
  });

  device.on("login_request", function(device_id, msg_parts) {

    console.log('Hey! I want to start transmiting my position. Please accept me. My name is ' + device_id);
    this.login_authorized(true);
    console.log("Ok, " + device_id + ", you're accepted!");
  });

  device.on("ping", function(data) {
    var devId = this.getUID(),
      gdata = GData.model({
        device_id: devId,
        latitude: data.latitude,
        longitude: data.longitude,
        timestamp: Math.floor(Date.now() / 1000)
      });

    gdata.save()
      .catch(function(error) {
        console.log('Could not validated:', error);
      });
    //this = device
    // console.log("I'm here: " + data.latitude + ", " + data.longitude + " (" + this.getUID() + ")");
    //Look what informations the device sends to you (maybe velocity, gas level, etc)
    //console.log(data);
    return data;
  });

  device.on("alarm", function(alarm_code, alarm_data, msg_data) {
    console.log("Help! Something happend: " + alarm_code + " (" + alarm_data.msg + ")");
  });

  //Also, you can listen on the native connection object
  connection.on('data', function(data) {
    var textData = data.toString(),
      sdata = CData.model({
        data: textData,
        ts: Math.floor(Date.now() / 1000)
      });

    sdata.save()
      .then(function(model) {
        // var id = model.get('id');
        // console.log('Created new post with ID:', model);
      })
      .catch(function(error) {
        console.log('Could not validated:', error);
      });
  });

});
<|endoftext|>


<commit_before>const compile = require('pug').compile
const parse = require('posthtml-parser')

/**
 * @module posthtml-pug
 * @version 1.0.0
 * @author Michael Ciniawsky (@michael-ciniawsky)
 *
 * @desc Pug Parser for PostHTML
 *
 * @requires pug
 * @requires posthtml-parser
 *
 * @method posthtmlPug
 *
 * @param  {String} pug     Pug Source
 * @param  {Object} options Pug Options
 *
 * @return {Function} HTML
 */
module.exports = function posthtmlPug (options) {
  options.pretty = options.pretty || true
  options.locals = options.locals || {}

  return function (pug) {
    return parse(compile(pug, options)(options.locals))
  }
}
<commit_msg>fix(index): fix missing options assignment<commit_after>// ------------------------------------
// #PUG - INDEX
// ------------------------------------

const assign = Object.assign

const compile = require('pug').compile
const parse = require('posthtml-parser')

/**
 * @author Michael Ciniawsky (@michael-ciniawsky)
 * @description Pug Parser for PostHTML
 * @license MIT
 *
 * @module posthtml-pug
 * @version 1.0.0
 *
 * @requires pug
 * @requires posthtml-parser
 *
 * @param  {String} pug     Pug Source
 * @param  {Object} options Pug Options
 *
 * @return {Function} HTML
 */
module.exports = function (options) {
  options = assign({ pretty: true, locals: {} }, options)

  /**
   * @method pug
   *
   * @param  {String} src File
   *
   * @return {Object}     PostHTML Tree
   */
  return function pug (src) {
    return parse(compile(src, options)(options.locals))
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = Point;

/**
 * A standalone point geometry with useful accessor, comparison, and
 * modification methods.
 *
 * @class Point
 * @param {Number} x the x-coordinate. this could be longitude or screen
 * pixels, or any other sort of unit.
 * @param {Number} y the y-coordinate. this could be latitude or screen
 * pixels, or any other sort of unit.
 * @example
 * var point = new Point(-77, 38);
 */
function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype = {

    /**
     * Clone this point, returning a new point that can be modified
     * without affecting the old one.
     * @return {Point} the clone
     */
    clone: function() { return new Point(this.x, this.y); },

    /**
     * Add this point's x & y coordinates to another point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    add:     function(p) { return this.clone()._add(p); },

    /**
     * Subtract this point's x & y coordinates to from point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    sub:     function(p) { return this.clone()._sub(p); },

    /**
     * Multiply this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    multByPoint:    function(p) { return this.clone()._multByPoint(p); },

    /**
     * Divide this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    divByPoint:     function(p) { return this.clone()._divByPoint(p); },

    /**
     * Multiply this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    mult:    function(k) { return this.clone()._mult(k); },

    /**
     * Divide this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    div:     function(k) { return this.clone()._div(k); },

    /**
     * Rotate this point around the 0, 0 origin by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @return {Point} output point
     */
    rotate:  function(a) { return this.clone()._rotate(a); },

    /**
     * Rotate this point around p point by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @param {Point} p Point to rotate around
     * @return {Point} output point
     */
    rotateAround:  function(a,p) { return this.clone()._rotateAround(a,p); },

    /**
     * Multiply this point by a 4x1 transformation matrix
     * @param {Array<Number>} m transformation matrix
     * @return {Point} output point
     */
    matMult: function(m) { return this.clone()._matMult(m); },

    /**
     * Calculate this point but as a unit vector from 0, 0, meaning
     * that the distance from the resulting point to the 0, 0
     * coordinate will be equal to 1 and the angle from the resulting
     * point to the 0, 0 coordinate will be the same as before.
     * @return {Point} unit vector point
     */
    unit:    function() { return this.clone()._unit(); },

    /**
     * Compute a perpendicular point, where the new y coordinate
     * is the old x coordinate and the new x coordinate is the old y
     * coordinate multiplied by -1
     * @return {Point} perpendicular point
     */
    perp:    function() { return this.clone()._perp(); },

    /**
     * Return a version of this point with the x & y coordinates
     * rounded to integers.
     * @return {Point} rounded point
     */
    round:   function() { return this.clone()._round(); },

    /**
     * Return the magitude of this point: this is the Euclidean
     * distance from the 0, 0 coordinate to this point's x and y
     * coordinates.
     * @return {Number} magnitude
     */
    mag: function() {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    },

    /**
     * Judge whether this point is equal to another point, returning
     * true or false.
     * @param {Point} other the other point
     * @return {boolean} whether the points are equal
     */
    equals: function(other) {
        return this.x === other.x &&
               this.y === other.y;
    },

    /**
     * Calculate the distance from this point to another point
     * @param {Point} p the other point
     * @return {Number} distance
     */
    dist: function(p) {
        return Math.sqrt(this.distSqr(p));
    },

    /**
     * Calculate the distance from this point to another point,
     * without the square root step. Useful if you're comparing
     * relative distances.
     * @param {Point} p the other point
     * @return {Number} distance
     */
    distSqr: function(p) {
        var dx = p.x - this.x,
            dy = p.y - this.y;
        return dx * dx + dy * dy;
    },

    /**
     * Get the angle from the 0, 0 coordinate to this point, in radians
     * coordinates.
     * @return {Number} angle
     */
    angle: function() {
        return Math.atan2(this.y, this.x);
    },

    /**
     * Get the angle from this point to another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleTo: function(b) {
        return Math.atan2(this.y - b.y, this.x - b.x);
    },

    /**
     * Get the angle between this point and another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleWith: function(b) {
        return this.angleWithSep(b.x, b.y);
    },

    /*
     * Find the angle of the two vectors, solving the formula for
     * the cross product a x b = |a||b|sin(θ) for θ.
     * @param {Number} x the x-coordinate
     * @param {Number} y the y-coordinate
     * @return {Number} the angle in radians
     */
    angleWithSep: function(x, y) {
        return Math.atan2(
            this.x * y - this.y * x,
            this.x * x + this.y * y);
    },

    _matMult: function(m) {
        var x = m[0] * this.x + m[1] * this.y,
            y = m[2] * this.x + m[3] * this.y;
        this.x = x;
        this.y = y;
        return this;
    },

    _add: function(p) {
        this.x += p.x;
        this.y += p.y;
        return this;
    },

    _sub: function(p) {
        this.x -= p.x;
        this.y -= p.y;
        return this;
    },

    _mult: function(k) {
        this.x *= k;
        this.y *= k;
        return this;
    },

    _div: function(k) {
        this.x /= k;
        this.y /= k;
        return this;
    },

    _multByPoint: function(p) {
        this.x *= p.x;
        this.y *= p.y;
        return this;
    },

    _divByPoint: function(p) {
        this.x /= p.x;
        this.y /= p.y;
        return this;
    },

    _unit: function() {
        this._div(this.mag());
        return this;
    },

    _perp: function() {
        var y = this.y;
        this.y = this.x;
        this.x = -y;
        return this;
    },

    _rotate: function(angle) {
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            x = cos * this.x - sin * this.y,
            y = sin * this.x + cos * this.y;
        this.x = x;
        this.y = y;
        return this;
    },

    _rotateAround: function(angle, p) {
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),
            y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);
        this.x = x;
        this.y = y;
        return this;
    },

    _round: function() {
        this.x = Math.round(this.x);
        this.y = Math.round(this.y);
        return this;
    }
};

/**
 * Construct a point from an array if necessary, otherwise if the input
 * is already a Point, or an unknown type, return it unchanged
 * @param {Array<Number>|Point|*} a any kind of input value
 * @return {Point} constructed point, or passed-through value.
 * @example
 * // this
 * var point = Point.convert([0, 1]);
 * // is equivalent to
 * var point = new Point(0, 1);
 */
Point.convert = function (a) {
    if (a instanceof Point) {
        return a;
    }
    if (Array.isArray(a)) {
        return new Point(a[0], a[1]);
    }
    return a;
};
<commit_msg>fix typo (#13)<commit_after>'use strict';

module.exports = Point;

/**
 * A standalone point geometry with useful accessor, comparison, and
 * modification methods.
 *
 * @class Point
 * @param {Number} x the x-coordinate. this could be longitude or screen
 * pixels, or any other sort of unit.
 * @param {Number} y the y-coordinate. this could be latitude or screen
 * pixels, or any other sort of unit.
 * @example
 * var point = new Point(-77, 38);
 */
function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype = {

    /**
     * Clone this point, returning a new point that can be modified
     * without affecting the old one.
     * @return {Point} the clone
     */
    clone: function() { return new Point(this.x, this.y); },

    /**
     * Add this point's x & y coordinates to another point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    add:     function(p) { return this.clone()._add(p); },

    /**
     * Subtract this point's x & y coordinates to from point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    sub:     function(p) { return this.clone()._sub(p); },

    /**
     * Multiply this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    multByPoint:    function(p) { return this.clone()._multByPoint(p); },

    /**
     * Divide this point's x & y coordinates by point,
     * yielding a new point.
     * @param {Point} p the other point
     * @return {Point} output point
     */
    divByPoint:     function(p) { return this.clone()._divByPoint(p); },

    /**
     * Multiply this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    mult:    function(k) { return this.clone()._mult(k); },

    /**
     * Divide this point's x & y coordinates by a factor,
     * yielding a new point.
     * @param {Point} k factor
     * @return {Point} output point
     */
    div:     function(k) { return this.clone()._div(k); },

    /**
     * Rotate this point around the 0, 0 origin by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @return {Point} output point
     */
    rotate:  function(a) { return this.clone()._rotate(a); },

    /**
     * Rotate this point around p point by an angle a,
     * given in radians
     * @param {Number} a angle to rotate around, in radians
     * @param {Point} p Point to rotate around
     * @return {Point} output point
     */
    rotateAround:  function(a,p) { return this.clone()._rotateAround(a,p); },

    /**
     * Multiply this point by a 4x1 transformation matrix
     * @param {Array<Number>} m transformation matrix
     * @return {Point} output point
     */
    matMult: function(m) { return this.clone()._matMult(m); },

    /**
     * Calculate this point but as a unit vector from 0, 0, meaning
     * that the distance from the resulting point to the 0, 0
     * coordinate will be equal to 1 and the angle from the resulting
     * point to the 0, 0 coordinate will be the same as before.
     * @return {Point} unit vector point
     */
    unit:    function() { return this.clone()._unit(); },

    /**
     * Compute a perpendicular point, where the new y coordinate
     * is the old x coordinate and the new x coordinate is the old y
     * coordinate multiplied by -1
     * @return {Point} perpendicular point
     */
    perp:    function() { return this.clone()._perp(); },

    /**
     * Return a version of this point with the x & y coordinates
     * rounded to integers.
     * @return {Point} rounded point
     */
    round:   function() { return this.clone()._round(); },

    /**
     * Return the magnitude of this point: this is the Euclidean
     * distance from the 0, 0 coordinate to this point's x and y
     * coordinates.
     * @return {Number} magnitude
     */
    mag: function() {
        return Math.sqrt(this.x * this.x + this.y * this.y);
    },

    /**
     * Judge whether this point is equal to another point, returning
     * true or false.
     * @param {Point} other the other point
     * @return {boolean} whether the points are equal
     */
    equals: function(other) {
        return this.x === other.x &&
               this.y === other.y;
    },

    /**
     * Calculate the distance from this point to another point
     * @param {Point} p the other point
     * @return {Number} distance
     */
    dist: function(p) {
        return Math.sqrt(this.distSqr(p));
    },

    /**
     * Calculate the distance from this point to another point,
     * without the square root step. Useful if you're comparing
     * relative distances.
     * @param {Point} p the other point
     * @return {Number} distance
     */
    distSqr: function(p) {
        var dx = p.x - this.x,
            dy = p.y - this.y;
        return dx * dx + dy * dy;
    },

    /**
     * Get the angle from the 0, 0 coordinate to this point, in radians
     * coordinates.
     * @return {Number} angle
     */
    angle: function() {
        return Math.atan2(this.y, this.x);
    },

    /**
     * Get the angle from this point to another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleTo: function(b) {
        return Math.atan2(this.y - b.y, this.x - b.x);
    },

    /**
     * Get the angle between this point and another point, in radians
     * @param {Point} b the other point
     * @return {Number} angle
     */
    angleWith: function(b) {
        return this.angleWithSep(b.x, b.y);
    },

    /*
     * Find the angle of the two vectors, solving the formula for
     * the cross product a x b = |a||b|sin(θ) for θ.
     * @param {Number} x the x-coordinate
     * @param {Number} y the y-coordinate
     * @return {Number} the angle in radians
     */
    angleWithSep: function(x, y) {
        return Math.atan2(
            this.x * y - this.y * x,
            this.x * x + this.y * y);
    },

    _matMult: function(m) {
        var x = m[0] * this.x + m[1] * this.y,
            y = m[2] * this.x + m[3] * this.y;
        this.x = x;
        this.y = y;
        return this;
    },

    _add: function(p) {
        this.x += p.x;
        this.y += p.y;
        return this;
    },

    _sub: function(p) {
        this.x -= p.x;
        this.y -= p.y;
        return this;
    },

    _mult: function(k) {
        this.x *= k;
        this.y *= k;
        return this;
    },

    _div: function(k) {
        this.x /= k;
        this.y /= k;
        return this;
    },

    _multByPoint: function(p) {
        this.x *= p.x;
        this.y *= p.y;
        return this;
    },

    _divByPoint: function(p) {
        this.x /= p.x;
        this.y /= p.y;
        return this;
    },

    _unit: function() {
        this._div(this.mag());
        return this;
    },

    _perp: function() {
        var y = this.y;
        this.y = this.x;
        this.x = -y;
        return this;
    },

    _rotate: function(angle) {
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            x = cos * this.x - sin * this.y,
            y = sin * this.x + cos * this.y;
        this.x = x;
        this.y = y;
        return this;
    },

    _rotateAround: function(angle, p) {
        var cos = Math.cos(angle),
            sin = Math.sin(angle),
            x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),
            y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);
        this.x = x;
        this.y = y;
        return this;
    },

    _round: function() {
        this.x = Math.round(this.x);
        this.y = Math.round(this.y);
        return this;
    }
};

/**
 * Construct a point from an array if necessary, otherwise if the input
 * is already a Point, or an unknown type, return it unchanged
 * @param {Array<Number>|Point|*} a any kind of input value
 * @return {Point} constructed point, or passed-through value.
 * @example
 * // this
 * var point = Point.convert([0, 1]);
 * // is equivalent to
 * var point = new Point(0, 1);
 */
Point.convert = function (a) {
    if (a instanceof Point) {
        return a;
    }
    if (Array.isArray(a)) {
        return new Point(a[0], a[1]);
    }
    return a;
};
<|endoftext|>