<commit_before>/* File: gulpfile.js */

// Dependancies
var gulp   = require('gulp'),
    jshint = require('gulp-jshint'),
    qunit = require('gulp-qunit'),
    uglify = require('gulp-uglify'),
	pump = require('pump'),
	ghPages = require('gulp-gh-pages'),
	rename = require('gulp-rename'),
    inject = require('gulp-inject-string'),
    webserver = require('gulp-webserver');

// Default Gulp task is develop
gulp.task('default', ['develop']);

// Task for development
gulp.task('develop', ['watch', 'serve'])

// Build the project
gulp.task('build', ['jshint', 'test', 'compile:js', 'copy:html', 'compile:json', 'copy:icon']);

// Build
gulp.task('deploy', ['build', 'gh-pages']);

gulp.task('serve', ['serve:development'])

// configure the jshint task
gulp.task('jshint', function() {
  return gulp.src('source/javascript/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint', 'test']);
});

gulp.task('test', function() {
    return gulp.src('./spec/index.html')
        .pipe(qunit());
});

gulp.task('compile:js', function (cb) {
  pump([
        gulp.src('js/*.js'),
        uglify(),
        gulp.dest('dist/js')
    ],
    cb
  );
});

gulp.task('copy:html', function() {
  return gulp.src('index.html')
  	.pipe(inject.after('', ''))
    .pipe(gulp.dest('dist'));
});

gulp.task('copy:json', function() {
  return gulp.src(['responses/*.json'])
        .pipe(gulp.dest('dist/responses'));
});

gulp.task('copy:icon', function(){
	return gulp.src('favicon.ico')
		.pipe(gulp.dest('dist'));
});

gulp.task('serve:development', function() {
  gulp.src('./')
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

gulp.task('serve:staging', function() {
  gulp.src('./dist')
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

gulp.task('gh-pages', function() {
  return gulp.src(['dist/**/*', 'dist/*'])
    .pipe(ghPages());
});
<commit_msg>Readd test serving<commit_after>/* File: gulpfile.js */

// Dependancies
var gulp   = require('gulp'),
    jshint = require('gulp-jshint'),
    qunit = require('gulp-qunit'),
    uglify = require('gulp-uglify'),
	pump = require('pump'),
	ghPages = require('gulp-gh-pages'),
	rename = require('gulp-rename'),
    inject = require('gulp-inject-string'),
    webserver = require('gulp-webserver');

// Default Gulp task is develop
gulp.task('default', ['develop']);

// Task for development
gulp.task('develop', ['watch', 'serve'])

// Build the project
gulp.task('build', ['jshint', 'test', 'compile:js', 'copy:html', 'compile:json', 'copy:icon']);

// Build
gulp.task('deploy', ['build', 'gh-pages']);

gulp.task('serve', ['serve:development'])

// configure the jshint task
gulp.task('jshint', function() {
  return gulp.src('source/javascript/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
  gulp.watch('source/javascript/**/*.js', ['jshint', 'test']);
});

gulp.task('test', function() {
    return gulp.src('./spec/index.html')
        .pipe(qunit());
});

gulp.task('compile:js', function (cb) {
  pump([
        gulp.src('js/*.js'),
        uglify(),
        gulp.dest('dist/js')
    ],
    cb
  );
});

gulp.task('copy:html', function() {
  return gulp.src('index.html')
  	.pipe(inject.after('', ''))
    .pipe(gulp.dest('dist'));
});

gulp.task('copy:json', function() {
  return gulp.src(['responses/*.json'])
        .pipe(gulp.dest('dist/responses'));
});

gulp.task('copy:icon', function(){
	return gulp.src('favicon.ico')
		.pipe(gulp.dest('dist'));
});

gulp.task('serve:development', function() {
  gulp.src('./')
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

gulp.task('serve:test', function() {
  gulp.src('./')
    .pipe(webserver({
      livereload: true,
      open: "spec/",
      fallback: 'spec/index.html'
    }));
});

gulp.task('serve:staging', function() {
  gulp.src('./dist')
    .pipe(webserver({
      livereload: true,
      open: true,
      fallback: 'index.html'
    }));
});

gulp.task('gh-pages', function() {
  return gulp.src(['dist/**/*', 'dist/*'])
    .pipe(ghPages());
});
<|endoftext|>


<commit_before>'use strict';

var
	path = require('path'),
	fs = require('fs'),
	util = require('util');

var
	EventEmitter = require('events').EventEmitter,
	Promise = require('promise');

var
	clone = require('clone'),
	defined = require('defined'),
	endpointParser = require('bower-endpoint-parser'),
	findIndex = require('find-index'),
	findLastIndex = require('find-index/last'),
	fse = require('fs-extra'),
	unq = require('array-uniq');

var
	logger = require('../logger');

function Generator (opts) {
	if (!(this instanceof Generator)) return new Generator(opts);

	this.options = opts = clone(opts);
	this.package = opts.package = path.resolve(opts.package);

	logger.setLogLevel(opts.logLevel);

	this.initPackageDirectory();
}

module.exports = Generator;

util.inherits(Generator, EventEmitter);

Generator.prototype.initPackageDirectory = function () {

	// @todo Either leverage bower internals (if possible) to adjust the file contents based on
	// existing values or have a better scheme for porting the information
	// ideally this would be capable of setting up the package.json as well...

	logger.log('debug', 'initializing target package directory %s', this.package);

	var
		bowerFile = path.join(this.package, 'bower.json'),
		pkgFile = path.join(this.package, 'package.json');

	validateProjectDirectory(this.package);
	// ensure the bower.json file exists
	fse.ensureFileSync(bowerFile);
	fse.ensureFileSync(pkgFile);

	// now try and read in any available package.json file
	try {
		var pkg = this.pkgInfo = require(pkgFile);
		logger.log('debug', 'package.json existed');
	} catch (e) {
		logger.log('debug', 'package.json did not exist, will create it');
		pkg = this.pkgInfo = {};
	}

	// try and read in the bower.json file
	try {
		var bowerInfo = this.bowerInfo = require(bowerFile);
		logger.log('debug', 'bower.json existed');
	} catch (e) {
		logger.log('debug', 'bower.json did not exist, will create it');
		// nope...
		bowerInfo = this.bowerInfo = {};
	}

	// if the bowerInfo already has a name no need to update
	bowerInfo.name = defined(bowerInfo.name, this.options.name, pkg.name, path.basename(this.package));
	pkg.name = defined(pkg.name, bowerInfo.name);

	// by default we assume projects will want to remain private unless they've explicitly said
	// otherwise...this can be re-visited
	bowerInfo.private = defined(bowerInfo.private, true);

	// have to make sure that the file has json content or bower will complain later
	logger.log('debug', 'writing the bower.json file contents');
	fse.outputJsonSync(bowerFile, bowerInfo);
	logger.log('debug', 'writing the package.json file contents');
	fse.outputJsonSync(pkgFile, pkg);

	validateGitIgnoreFile(this.package);
};

function validateProjectDirectory (dir) {
	try {

		dir = fs.lstatSync(dir);

	} catch (e) {

		logger.log('debug', 'package directory did not exist, creating it');

		// @todo Do we need to set the mode here or is 0777 ok?
		// if either of these fail then we want the error to be uncaught for now
		fs.makedirSync(dir);
		dir = fs.lstatSync(dir);
	}

	if (!dir.isDirectory()) {
		throw new Error(
			'Error: the target package location exists but is not a directory'
		);
	}
}

function validateGitIgnoreFile (dir) {

	var
		ignores = [
			'node_modules',
			'lib',
			'dist'
		];

	var
		gitFile = path.join(dir, '.gitignore'),
		contents, len;

	fse.ensureFileSync(gitFile);

	contents = fs.readFileSync(gitFile, 'utf8');
	contents = contents ? contents.split('\n') : [];
	len = contents.length;

	contents = unq(contents.concat(ignores));
	logger.log('debug', 'writing .gitignore file contents back to file, added %d entries', contents.length - len);
	fs.writeFileSync(gitFile, contents.join('\n'));
}

Generator.prototype.init = function () {

	var
		rcPath = path.join(this.package, '.bowerrc'),
		tpl = require('./bowerrc.json'),
		generator = this,
		rc;

	this.once('done', function () {
		logger.log('info',
			'The initialization is complete. Please note that this generator is in ALPHA state and ' +
			'will support many more features in the future.'
		);

		logger.log('info',
			'Make sure to run `npm init` if you have not already setup a package.json file officially. ' +
			'If one did not already exist, one was created for you.'
		);

		logger.log('info',
			'To udpate any versions of the dependent libraries simply run a command of this form: ' +
			'`egen init --lib={LIBRARY}#{BRANCH OR TAG}` and it will be updated for you.'
		);
	});

	logger.log('info', 'initializing %s', this.package);

	// test to see if a .bowerrc file already exists because we will need to do some updates
	// if so instead of just blindly overwriting it
	try {
		rc = fs.readFileSync(rcPath, 'utf8');
	} catch (e) {}

	if (rc) {
		// alright, one already existed...
		logger.log('debug', 'found existing .bowerrc file in package');
		rc = JSON.parse(rc);
		Object.keys(tpl).forEach(function (key) {
			rc[key] = defined(rc[key], tpl[key]);
		});
	} else {
		// nope get to start fresh
		rc = tpl;
	}

	logger.log('debug', 'writing .bowerrc file to package location');
	fs.writeFile(path.join(this.package, '.bowerrc'), JSON.stringify(rc, null, 2), function (err) {
		if (err) throw err;
		generator.installBowerDeps();
	});
};

Generator.prototype.installBowerDeps = function () {

	logger.log('info', 'installing bower dependencies');

	// @todo
	var deps = [
		{name: 'enyo', source: 'git@github.com:enyojs/enyo.git', target: '2.6.0-dev'},
		{name: 'moonstone', source: 'git@github.com:enyojs/moonstone.git', target: '2.6.0-dev'},
		{name: 'spotlight', source: 'git@github.com:enyojs/spotlight.git', target: '2.6.0-dev'},
		{name: 'enyo-ilib', source: 'git@github.com:enyojs/enyo-ilib.git', target: '2.6.0-dev'},
		{name: 'layout', source: 'git@github.com:enyojs/layout.git', target: '2.6.0-dev'},
		{name: 'enyo-cordova', source: 'git@github.com:enyojs/enyo-cordova.git', target: '2.6.0-dev'},
		{name: 'enyo-webos', source: 'git@github.com:enyojs/enyo-webos.git', target: '2.6.0-dev'},
		{name: 'onyx', source: 'git@github.com:enyojs/onyx.git', target: '2.6.0-dev'},
		{name: 'canvas', source: 'git@github.com:enyojs/canvas.git', target: '2.6.0-dev'},
		{name: 'moonstone-extra', source: 'git@github.com:enyojs/moonstone-extra.git', target: 'master'}
	];

	var bowerToName = {
		'enyo-moonstone': 'moonstone',
		'enyo-layout': 'layout',
		'enyo-spotlight': 'spotlight',
		'enyo-canvas': 'canvas',
		'enyo-onyx': 'onyx'
	};

	var nameToBower = {
		'enyo': 'enyo',
		'enyo-webos': 'enyo-webos',
		'enyo-cordova': 'enyo-cordova',
		'enyo-ilib': 'enyo-ilib',
		'moonstone': 'enyo-moonstone',
		'layout': 'enyo-layout',
		'spotlight': 'enyo-spotlight',
		'canvas': 'enyo-canvas',
		'onyx': 'enyo-onyx'
	};

	var
		linked = this.options.linkAllLibs || this.options.linkLibs,
		useDefaults = this.options.defaults === true,
		libs;

	// @todo Should we worry about devDependencies or other variations?
	if (this.bowerInfo.dependencies) {
		var ldeps = useDefaults && deps.slice();

		libs = Object.keys(this.bowerInfo.dependencies).map(function (nom) {

			if (useDefaults) {
				// if this entry from bower.json is one of our defaults we remove it so we know
				// which ones we need to add at the end
				var idx = findIndex(ldeps, function (comp) { return nom == comp.name; });
				if (idx > -1) ldeps.splice(idx, 1);
			}

			return nom + '=' + this.bowerInfo.dependencies[nom];
		}, this);

		if (useDefaults && ldeps.length) libs = libs.concat(ldeps);
	}

	// if there are cli defined libs they take precedence but rather than parse them all here
	// separately and again later we combine them at the end and will give last-in priority
	// once processed
	if (this.options.libs) {
		if (libs) libs = libs.concat(this.options.libs);
		else libs = this.options.libs;
	}

	if (libs) {
		libs = libs.map(function (lib) {
			if (typeof lib == 'string') {
				var comp = endpointParser.decompose(lib);

				if (!comp.name) comp.name = defined(bowerToName[comp.source], comp.source);

				var idx = findIndex(deps, function (dep) { return dep.name == comp.name; });
				if (idx > -1) {
					comp.source = bowerToName[comp.source] || nameToBower[comp.source] ? deps[idx].source : comp.source;
					comp.target = comp.target == '*' ? deps[idx].target : comp.target;
				}

				logger.log('debug', 'decomposed %s into', lib, comp);

				return comp;
			} else return lib;
		});
	} else libs = deps;

	// unfortunately we have to make sure we only have one entry for any of the given libs
	if (libs !== deps) {
		// @todo
		libs.forEach(function (lib, idx) {
			var ldx = findLastIndex(libs, function (_lib) { return _lib.name == lib.name; });
			if (ldx !== idx) {
				// insert the last one instead
				libs[idx] = libs[ldx];
				// since we know the final index was greater we should be able to safely remove it
				// from the array
				libs.splice(ldx, 1);
			}
		});
	}

	if (linked) {
		if (linked === true) {
			linked = libs;
			libs = null;
		} else {
			linked.forEach(function (nom, idx) {
				var i = findIndex(libs, function (lib) { return lib.name == nom; });
				if (i > -1) {
					linked[idx] = libs[i];
					libs.splice(i, 1);
				}
			});
		}

		linked.forEach(function (lib) {
			lib.source = defined(nameToBower[lib.name], lib.source);
		});
	}

	var
		// fyi, requiring bower earlier means it won't see the .bowerrc we just wrote and at this
		// moment the reset method or others aren't actually getting it to reevaluate the env
		bower = require('bower'),
		generator = this,
		install;

	var installRemotes = function () {

		logger.log('debug', 'installing remote dependencies');

		libs = libs.map(function (lib) {

			var comp = endpointParser.compose(lib);

			logger.log('debug', 'requesting %s', comp);

			return comp;
		});

		bower
			.commands
			.install(libs, {save: generator.options.save, forceLatest: true})
			.on('log', function (msg) {

				logger.log(msg.level != 'warn' ? 'debug' : 'warn', '%s%s => %s',
					msg.data.endpoint ? '(' + msg.data.endpoint.name + ') ' : '',
					msg.id,
					msg.message
				);
			})
			.on('end', function () {
				logger.log('debug', 'installation of remote libraries complete');
				generator.emit('done');
			});
	};

	if (linked && linked.length) {
		logger.log('debug', 'linking from local versions of the libraries');

		install = function () {
			var lib = linked.pop();
			if (lib) {
				logger.log('debug', 'linking %s', lib.name);
				bower
					.commands
					.link(lib.source, lib.name)
					.on('end', install);
			} else {
				logger.log('debug', 'linking complete');
				if (libs && libs.length) installRemotes();
				else generator.emit('done');
			}
		};

		install();
	} else if (libs && libs.length) installRemotes();
};
<commit_msg>ENYO-1626: Adding support for the SVG library Evidently much trailing whitespace cleanup too.<commit_after>'use strict';

var
	path = require('path'),
	fs = require('fs'),
	util = require('util');

var
	EventEmitter = require('events').EventEmitter,
	Promise = require('promise');

var
	clone = require('clone'),
	defined = require('defined'),
	endpointParser = require('bower-endpoint-parser'),
	findIndex = require('find-index'),
	findLastIndex = require('find-index/last'),
	fse = require('fs-extra'),
	unq = require('array-uniq');

var
	logger = require('../logger');

function Generator (opts) {
	if (!(this instanceof Generator)) return new Generator(opts);

	this.options = opts = clone(opts);
	this.package = opts.package = path.resolve(opts.package);

	logger.setLogLevel(opts.logLevel);

	this.initPackageDirectory();
}

module.exports = Generator;

util.inherits(Generator, EventEmitter);

Generator.prototype.initPackageDirectory = function () {

	// @todo Either leverage bower internals (if possible) to adjust the file contents based on
	// existing values or have a better scheme for porting the information
	// ideally this would be capable of setting up the package.json as well...

	logger.log('debug', 'initializing target package directory %s', this.package);

	var
		bowerFile = path.join(this.package, 'bower.json'),
		pkgFile = path.join(this.package, 'package.json');

	validateProjectDirectory(this.package);
	// ensure the bower.json file exists
	fse.ensureFileSync(bowerFile);
	fse.ensureFileSync(pkgFile);

	// now try and read in any available package.json file
	try {
		var pkg = this.pkgInfo = require(pkgFile);
		logger.log('debug', 'package.json existed');
	} catch (e) {
		logger.log('debug', 'package.json did not exist, will create it');
		pkg = this.pkgInfo = {};
	}

	// try and read in the bower.json file
	try {
		var bowerInfo = this.bowerInfo = require(bowerFile);
		logger.log('debug', 'bower.json existed');
	} catch (e) {
		logger.log('debug', 'bower.json did not exist, will create it');
		// nope...
		bowerInfo = this.bowerInfo = {};
	}

	// if the bowerInfo already has a name no need to update
	bowerInfo.name = defined(bowerInfo.name, this.options.name, pkg.name, path.basename(this.package));
	pkg.name = defined(pkg.name, bowerInfo.name);

	// by default we assume projects will want to remain private unless they've explicitly said
	// otherwise...this can be re-visited
	bowerInfo.private = defined(bowerInfo.private, true);

	// have to make sure that the file has json content or bower will complain later
	logger.log('debug', 'writing the bower.json file contents');
	fse.outputJsonSync(bowerFile, bowerInfo);
	logger.log('debug', 'writing the package.json file contents');
	fse.outputJsonSync(pkgFile, pkg);

	validateGitIgnoreFile(this.package);
};

function validateProjectDirectory (dir) {
	try {

		dir = fs.lstatSync(dir);

	} catch (e) {

		logger.log('debug', 'package directory did not exist, creating it');

		// @todo Do we need to set the mode here or is 0777 ok?
		// if either of these fail then we want the error to be uncaught for now
		fs.makedirSync(dir);
		dir = fs.lstatSync(dir);
	}

	if (!dir.isDirectory()) {
		throw new Error(
			'Error: the target package location exists but is not a directory'
		);
	}
}

function validateGitIgnoreFile (dir) {

	var
		ignores = [
			'node_modules',
			'lib',
			'dist'
		];

	var
		gitFile = path.join(dir, '.gitignore'),
		contents, len;

	fse.ensureFileSync(gitFile);

	contents = fs.readFileSync(gitFile, 'utf8');
	contents = contents ? contents.split('\n') : [];
	len = contents.length;

	contents = unq(contents.concat(ignores));
	logger.log('debug', 'writing .gitignore file contents back to file, added %d entries', contents.length - len);
	fs.writeFileSync(gitFile, contents.join('\n'));
}

Generator.prototype.init = function () {

	var
		rcPath = path.join(this.package, '.bowerrc'),
		tpl = require('./bowerrc.json'),
		generator = this,
		rc;

	this.once('done', function () {
		logger.log('info',
			'The initialization is complete. Please note that this generator is in ALPHA state and ' +
			'will support many more features in the future.'
		);

		logger.log('info',
			'Make sure to run `npm init` if you have not already setup a package.json file officially. ' +
			'If one did not already exist, one was created for you.'
		);

		logger.log('info',
			'To udpate any versions of the dependent libraries simply run a command of this form: ' +
			'`egen init --lib={LIBRARY}#{BRANCH OR TAG}` and it will be updated for you.'
		);
	});

	logger.log('info', 'initializing %s', this.package);

	// test to see if a .bowerrc file already exists because we will need to do some updates
	// if so instead of just blindly overwriting it
	try {
		rc = fs.readFileSync(rcPath, 'utf8');
	} catch (e) {}

	if (rc) {
		// alright, one already existed...
		logger.log('debug', 'found existing .bowerrc file in package');
		rc = JSON.parse(rc);
		Object.keys(tpl).forEach(function (key) {
			rc[key] = defined(rc[key], tpl[key]);
		});
	} else {
		// nope get to start fresh
		rc = tpl;
	}

	logger.log('debug', 'writing .bowerrc file to package location');
	fs.writeFile(path.join(this.package, '.bowerrc'), JSON.stringify(rc, null, 2), function (err) {
		if (err) throw err;
		generator.installBowerDeps();
	});
};

Generator.prototype.installBowerDeps = function () {

	logger.log('info', 'installing bower dependencies');

	// @todo
	var deps = [
		{name: 'enyo', source: 'git@github.com:enyojs/enyo.git', target: '2.6.0-dev'},
		{name: 'moonstone', source: 'git@github.com:enyojs/moonstone.git', target: '2.6.0-dev'},
		{name: 'spotlight', source: 'git@github.com:enyojs/spotlight.git', target: '2.6.0-dev'},
		{name: 'enyo-ilib', source: 'git@github.com:enyojs/enyo-ilib.git', target: '2.6.0-dev'},
		{name: 'layout', source: 'git@github.com:enyojs/layout.git', target: '2.6.0-dev'},
		{name: 'enyo-cordova', source: 'git@github.com:enyojs/enyo-cordova.git', target: '2.6.0-dev'},
		{name: 'enyo-webos', source: 'git@github.com:enyojs/enyo-webos.git', target: '2.6.0-dev'},
		{name: 'onyx', source: 'git@github.com:enyojs/onyx.git', target: '2.6.0-dev'},
		{name: 'canvas', source: 'git@github.com:enyojs/canvas.git', target: '2.6.0-dev'},
		{name: 'moonstone-extra', source: 'git@github.com:enyojs/moonstone-extra.git', target: 'master'},
		{name: 'svg', source: 'git@github.com:enyojs/svg.git', target: 'master'}
	];

	var bowerToName = {
		'enyo-moonstone': 'moonstone',
		'enyo-layout': 'layout',
		'enyo-spotlight': 'spotlight',
		'enyo-canvas': 'canvas',
		'enyo-onyx': 'onyx'
	};

	var nameToBower = {
		'enyo': 'enyo',
		'enyo-webos': 'enyo-webos',
		'enyo-cordova': 'enyo-cordova',
		'enyo-ilib': 'enyo-ilib',
		'moonstone': 'enyo-moonstone',
		'layout': 'enyo-layout',
		'spotlight': 'enyo-spotlight',
		'canvas': 'enyo-canvas',
		'onyx': 'enyo-onyx',
		'svg': 'svg'
	};

	var
		linked = this.options.linkAllLibs || this.options.linkLibs,
		useDefaults = this.options.defaults === true,
		libs;

	// @todo Should we worry about devDependencies or other variations?
	if (this.bowerInfo.dependencies) {
		var ldeps = useDefaults && deps.slice();

		libs = Object.keys(this.bowerInfo.dependencies).map(function (nom) {

			if (useDefaults) {
				// if this entry from bower.json is one of our defaults we remove it so we know
				// which ones we need to add at the end
				var idx = findIndex(ldeps, function (comp) { return nom == comp.name; });
				if (idx > -1) ldeps.splice(idx, 1);
			}

			return nom + '=' + this.bowerInfo.dependencies[nom];
		}, this);

		if (useDefaults && ldeps.length) libs = libs.concat(ldeps);
	}

	// if there are cli defined libs they take precedence but rather than parse them all here
	// separately and again later we combine them at the end and will give last-in priority
	// once processed
	if (this.options.libs) {
		if (libs) libs = libs.concat(this.options.libs);
		else libs = this.options.libs;
	}

	if (libs) {
		libs = libs.map(function (lib) {
			if (typeof lib == 'string') {
				var comp = endpointParser.decompose(lib);

				if (!comp.name) comp.name = defined(bowerToName[comp.source], comp.source);

				var idx = findIndex(deps, function (dep) { return dep.name == comp.name; });
				if (idx > -1) {
					comp.source = bowerToName[comp.source] || nameToBower[comp.source] ? deps[idx].source : comp.source;
					comp.target = comp.target == '*' ? deps[idx].target : comp.target;
				}

				logger.log('debug', 'decomposed %s into', lib, comp);

				return comp;
			} else return lib;
		});
	} else libs = deps;

	// unfortunately we have to make sure we only have one entry for any of the given libs
	if (libs !== deps) {
		// @todo
		libs.forEach(function (lib, idx) {
			var ldx = findLastIndex(libs, function (_lib) { return _lib.name == lib.name; });
			if (ldx !== idx) {
				// insert the last one instead
				libs[idx] = libs[ldx];
				// since we know the final index was greater we should be able to safely remove it
				// from the array
				libs.splice(ldx, 1);
			}
		});
	}

	if (linked) {
		if (linked === true) {
			linked = libs;
			libs = null;
		} else {
			linked.forEach(function (nom, idx) {
				var i = findIndex(libs, function (lib) { return lib.name == nom; });
				if (i > -1) {
					linked[idx] = libs[i];
					libs.splice(i, 1);
				}
			});
		}

		linked.forEach(function (lib) {
			lib.source = defined(nameToBower[lib.name], lib.source);
		});
	}

	var
		// fyi, requiring bower earlier means it won't see the .bowerrc we just wrote and at this
		// moment the reset method or others aren't actually getting it to reevaluate the env
		bower = require('bower'),
		generator = this,
		install;

	var installRemotes = function () {

		logger.log('debug', 'installing remote dependencies');

		libs = libs.map(function (lib) {

			var comp = endpointParser.compose(lib);

			logger.log('debug', 'requesting %s', comp);

			return comp;
		});

		bower
			.commands
			.install(libs, {save: generator.options.save, forceLatest: true})
			.on('log', function (msg) {

				logger.log(msg.level != 'warn' ? 'debug' : 'warn', '%s%s => %s',
					msg.data.endpoint ? '(' + msg.data.endpoint.name + ') ' : '',
					msg.id,
					msg.message
				);
			})
			.on('end', function () {
				logger.log('debug', 'installation of remote libraries complete');
				generator.emit('done');
			});
	};

	if (linked && linked.length) {
		logger.log('debug', 'linking from local versions of the libraries');

		install = function () {
			var lib = linked.pop();
			if (lib) {
				logger.log('debug', 'linking %s', lib.name);
				bower
					.commands
					.link(lib.source, lib.name)
					.on('end', install);
			} else {
				logger.log('debug', 'linking complete');
				if (libs && libs.length) installRemotes();
				else generator.emit('done');
			}
		};

		install();
	} else if (libs && libs.length) installRemotes();
};
<|endoftext|>


<commit_before>exports.names = ['songinfo'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 30;
exports.cd_user = 30;
exports.cd_manager = 5;
exports.min_role = PERMISSIONS.NONE;

function do_history(data, format, cid, songs_ago)
{
    if (!cid || !format) {
        sendMessage('/me :tfw: MFW no song');
        return;
    }

    logger.info('do history: ' + format + ', ' + cid);

    Song.findAll({
        where: {
            format: format,
            cid: cid,
        },
        order: 'updated_at DESC'
    }).on('success', function (rows) {
        logger.info(rows);
        if (rows && rows.length > 0) {
            var song_ids = [];
            _.each(rows, function (row) {
                song_ids.push(row.id);
            });
            logger.info(song_ids);

            Play.findAll({
                where: { song_id: song_ids },
                order: 'updated_at DESC'
            }).on('success', function (rows) {
                logger.info(rows);
                var prefix = 'This song';
                if (songs_ago > 0) {
                    prefix = 'The song that played ' + (songs_ago) + ' songs ago';
                }
                if (rows && rows.length > 0) {
                    modMessage(data, prefix + ' has been played '+(rows.length)+' times in my lifetime, last time being ' + moment.utc(rows[0]['updated_at']).calendar() + ' (' + moment.utc(rows[0]['updated_at']).fromNow() + ')');
                } else {
                    modMessage(data, prefix + ' has not been played here in my lifetime.');
                }
            });
        } else {
            modMessage(data, 'This song has not been played here in my lifetime.');
        }
    });
}

exports.handler = function (data) {
    var input = data.message.split(' ');
    var command = _.first(input);
    var params = _.rest(input);
    var offset = false;
    var cid = false;
    var format = false;

    if (params.length >= 1) {
        var tmp_offset = parseInt(params);

        if (!isNaN(tmp_offset) && tmp_offset >= 1) {
            offset = tmp_offset;
        }
    }

    var media = bot.getMedia();
    if (media == null) {
        offset = 0;
    } else {
        cid = media.cid;
        format = media.format;
    }

    if (offset !== false) {
        logger.info('offset: ' + offset);
        sequelize.query('SELECT `plays`.`id`, `songs`.`format`, `songs`.`cid`, `songs`.`author`, `songs`.`title` FROM `plays` INNER JOIN `songs` ON `songs`.`id`=`plays`.`song_id` ORDER BY `plays`.`id` DESC LIMIT '+offset+',1',
                { type: Sequelize.QueryTypes.SELECT })
            .then(function(rows) {
                logger.info(rows);
                if (rows != null && rows.length == 1) {
                    var row = rows[0];
                    logger.info(row);
                    cid = row['cid'];
                    format = row['format'];
                }
            }).then(function() {
                do_history(data, format, cid, offset);
            });
    } else {
        do_history(data, format, cid, 0);
    }
};
<commit_msg>.songinfo now properly matches .history<commit_after>exports.names = ['songinfo'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 30;
exports.cd_user = 30;
exports.cd_manager = 5;
exports.min_role = PERMISSIONS.NONE;

function do_history(data, format, cid, songs_ago)
{
    if (!cid || !format) {
        sendMessage('/me :tfw: MFW no song');
        return;
    }

    logger.info('do history: ' + format + ', ' + cid);

    Song.findAll({
        where: {
            format: format,
            cid: cid,
        },
        order: 'updated_at DESC'
    }).on('success', function (rows) {
        logger.info(rows);
        if (rows && rows.length > 0) {
            var song_ids = [];
            _.each(rows, function (row) {
                song_ids.push(row.id);
            });
            logger.info(song_ids);

            Play.findAll({
                where: { song_id: song_ids },
                order: 'updated_at DESC'
            }).on('success', function (rows) {
                logger.info(rows);
                var prefix = 'This song';
                if (songs_ago >= 0) {
                    prefix = 'The song that played ' + (songs_ago+1) + ' songs ago ('+format+','+cid+')';
                }
                if (rows && rows.length > 0) {
                    modMessage(data, prefix + ' has been played '+(rows.length)+' times in my lifetime, last time being ' + moment.utc(rows[0]['updated_at']).calendar() + ' (' + moment.utc(rows[0]['updated_at']).fromNow() + ')');
                } else {
                    modMessage(data, prefix + ' has not been played here in my lifetime.');
                }
            });
        } else {
            modMessage(data, 'This song has not been played here in my lifetime.');
        }
    });
}

exports.handler = function (data) {
    var input = data.message.split(' ');
    var command = _.first(input);
    var params = _.rest(input);
    var offset = false;
    var cid = false;
    var format = false;

    if (params.length >= 1) {
        var tmp_offset = parseInt(params);

        if (!isNaN(tmp_offset) && tmp_offset >= 1) {
            offset = tmp_offset-1;
        }
    }

    var media = bot.getMedia();
    if (media == null) {
        offset = 0;
    } else {
        cid = media.cid;
        format = media.format;
    }

    if (offset !== false) {
        logger.info('offset: ' + offset);
        sequelize.query('SELECT `plays`.`id`, `songs`.`format`, `songs`.`cid`, `songs`.`author`, `songs`.`title` FROM `plays` INNER JOIN `songs` ON `songs`.`id`=`plays`.`song_id` ORDER BY `plays`.`id` DESC LIMIT '+offset+',1',
                { type: Sequelize.QueryTypes.SELECT })
            .then(function(rows) {
                logger.info(rows);
                if (rows != null && rows.length == 1) {
                    var row = rows[0];
                    logger.info(row);
                    cid = row['cid'];
                    format = row['format'];
                }
            }).then(function() {
                do_history(data, format, cid, offset);
            });
    } else {
        do_history(data, format, cid, 0);
    }
};
<|endoftext|>


<commit_before>var utilities = require('./utilities');

// argv[2] (required): the name of the active file
// argv[3] (required): the ipv4 address of the server to contact first

var activeFileName = process.argv[2];

var fileContents;

var otherServerUri = "http://" + process.argv[3] + ':' +
  utilities.SERVER_HTTP_PORT;
var p = new utilities.p2p.peer(otherServerUri, utilities.SERVER_HTTP_PORT);

utilities.fs.writeFile(activeFileName, "", function(error) {
  if (error) {
    throw err;
  }
  openFileInEmacs(activeFileName);
  p.start(
    // client init function
    function() {
      console.log("speaking on " + utilities.os.hostname() + ':' +
        utilities.SERVER_HTTP_PORT);
    },
    // client socket function
    function(socket) {
      // get user id, filename, and file contents; write to file
      socket.on('connection_info', function(sentFileName) {
        activeFileName = sentFileName;
      });
      socket.on('file_send', function(sentFileContents) {
        utilities.fs.writeFile(
          activeFileName,
          sentFileContents,
          function() {
            updateBufferInEmacs(activeFileName);
          });
      });
    },
    // server init function
    function() {
      console.log("listening on " + utilities.os.hostname() + ':' +
        utilities.SERVER_HTTP_PORT);
      if ("127.0.0.1" == process.argv[3]) { // if initial server
        setInterval(broadcastBuffer, utilities.FILE_SYNC_TIME);
      }
    },
    // server socket function
    function(socket) {
      socket.emit('connection_info', activeFileName);
    });
});

// requires emacs to be open and server to be on
function openFileInEmacs(filename) {
  emacsOpenFile = utilities.spawn('emacsclient', ['-n', filename]);
  emacsOpenFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsOpenFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsOpenFile.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be opened.");
    } else {
      console.log("FILE OPENED :DDDDDDDDDDDDDDDDDD");
    }
  });
}

function broadcastBuffer() {
  evalArg = "(send-buffer-to-file \"" + activeFileName + "\" \"" +
    utilities.TMP_DIFF_FILE_SUFFIX + "\")";
  emacsWriteFile = utilities.spawn('emacsclient', ['-e', evalArg]);
  emacsWriteFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsWriteFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsWriteFile.on('exit', function(
    return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be saved.");
    } else {
      console.log("file broadcasted");
      // did not previously have the + utilities.TMP_DIFF_FILE_SUFFIX
      utilities.fs.readFile(
        activeFileName + utilities.TMP_DIFF_FILE_SUFFIX,
        function(error, fileContents) {
          if (error) {
            throw error;
          }
          p.emit('file_send', fileContents.toString());
        });
    }
  });
}

function updateBufferInEmacs(filename) {
  evalArg = "(read-buffer-from-file \"" + filename + "\")";
  emacsReadFile = utilities.spawn('emacsclient', ['-e', evalArg]);
  emacsReadFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsReadFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsReadFile.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be read.");
    }
    console.log("file read");
  });
}
<commit_msg>BROADCASTING WORKS<commit_after>var utilities = require('./utilities');

// argv[2] (required): the name of the active file
// argv[3] (required): the ipv4 address of the server to contact first

var activeFileName = process.argv[2];

var fileContents;

var otherServerUri = "http://" + process.argv[3] + ':' +
  utilities.SERVER_HTTP_PORT;
var p = new utilities.p2p.peer(otherServerUri, utilities.SERVER_HTTP_PORT);

utilities.fs.writeFile(activeFileName, "", function(error) {
  if (error) {
    throw err;
  }
  openFileInEmacs(activeFileName);
  p.start(
    // client init function
    function() {
      console.log("speaking on " + utilities.os.hostname() + ':' +
        utilities.SERVER_HTTP_PORT);
    },
    // client socket function
    function(socket) {
      // get user id, filename, and file contents; write to file
      socket.on('connection_info', function(sentFileName) {
        activeFileName = sentFileName;
      });
      socket.on('file_send', function(sentFileContents) {
        utilities.fs.writeFile(
          activeFileName,
          sentFileContents,
          function() {
            updateBufferInEmacs(activeFileName);
          });
      });
    },
    // server init function
    function() {
      console.log("listening on " + utilities.os.hostname() + ':' +
        utilities.SERVER_HTTP_PORT);
      if ("127.0.0.1" == process.argv[3]) { // if initial server
        setInterval(broadcastBuffer, utilities.FILE_SYNC_TIME);
      }
    },
    // server socket function
    function(socket) {
      socket.emit('connection_info', activeFileName);
    });
});

// requires emacs to be open and server to be on
function openFileInEmacs(filename) {
  emacsOpenFile = utilities.spawn('emacsclient', ['-n', filename]);
  emacsOpenFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsOpenFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsOpenFile.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be opened.");
    } else {
      console.log("FILE OPENED :DDDDDDDDDDDDDDDDDD");
    }
  });
}

function broadcastBuffer() {
  evalArg = "(send-buffer-to-file \"" + activeFileName + "\" \"" +
    utilities.TMP_DIFF_FILE_SUFFIX + "\")";
  emacsWriteFile = utilities.spawn('emacsclient', ['-e', evalArg]);
  emacsWriteFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsWriteFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsWriteFile.on('exit', function(
    return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be saved.");
    } else {
      console.log("file broadcasted");
      // did not previously have the + utilities.TMP_DIFF_FILE_SUFFIX
      utilities.fs.readFile(
        activeFileName + utilities.TMP_DIFF_FILE_SUFFIX,
        function(error, fileContents) {
          if (error) {
            utilities.fs.writeFile(
              activeFileName + utilities.TMP_DIFF_FILE_SUFFIX,
              "",
              function() {
                p.emit('file_send', fileContents.toString());
              }
            );
          }
          p.emit('file_send', fileContents.toString());
        });
    }
  });
}

function updateBufferInEmacs(filename) {
  evalArg = "(read-buffer-from-file \"" + filename + "\")";
  emacsReadFile = utilities.spawn('emacsclient', ['-e', evalArg]);
  emacsReadFile.stdout.on('data', function(data) {
    console.log("emacs stdout: " + data);
  });
  emacsReadFile.stderr.on('data', function(data) {
    console.log("emacs stderr: " + data);
  });
  emacsReadFile.on('exit', function(return_code, signal) {
    if (return_code != 0) {
      console.log("error: file could not be read.");
    }
    console.log("file read");
  });
}
<|endoftext|>


<commit_before>const gulp = require('gulp');
const gutil = require('gulp-util');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const concatenate = require('gulp-concat');
const browsersync = require('browser-sync').create();
const eslint = require('gulp-eslint');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

const ESLINT_RULES = {
  // For reference including all possible rules, and (if any) their sub-options, see https://eslint.org/docs/rules/

  /*
   * (ALL SUPPORTED) RULES ON (POTENTIAL) ERRORS regarding code syntax / structure / flow
   */

  // (0) ALLOW THESE CASES
  'no-console': 0, // ALLOW using console.log(), these settings are for BOTH development AND "production" environment
  'no-constant-condition': 0, // ALLOW "if (true)" and similar
  'no-control-regex': 0, // If someone uses control chars like /\x1f/ inside regex, presume they have a reason
  'no-extra-boolean-cast': 0, // ALLOW unnecessary casting to boolean with "if (!!myVar)" (for purpose of strongly implying "this is represented as boolean")
  'no-prototype-builtins': 0, // ALLOW calling directly "myInstance.hasOwnProperty('some_prop')" instead of myInstance.prototype.hasOwnProperty('some_prop')
  'no-regex-spaces': 0, // ALLOW using repeated whitespace literals in regex instead of / {10}/ for example of ten whitespaces. Regex allows it.
                        // MOTIVATION: Regex does not automatically convert these for us, yet those as a string of "          " and " {10}" ARE different.
  'no-template-curly-in-string': 0, // ALLOW use of let notATemplateString = "something ${something}"; aswell as with '-quotes. It is not a syntax error.
  'no-unexpected-multiline': 0, // ALLOW multiline commands, it is not a syntax error and SOMETIMES preferable. Syntax errors will show up elsewhere.
  'valid-jsdoc': 0, // ALLOW using whatever other commenting scheme than JSDoc. We aren't using it yet at least.
                    // MAY CHANGE if we start using JSDoc.

  // (1) WARN BUT CONTINUE BUILD IN THESE CASES
  'no-await-in-loop': 1, // Warn but let (reasonless) looped await calls be
  'for-direction': 1, // Warn but if intended infinite-loop, let it be
  'no-empty': 1, // Warn but if intended "if(something) {  }" let it be; Do not require a comment
  'no-extra-parens': 1, // Warn but permit "let calc = 6 - (2*3);"
  'no-extra-semi': 1, // Warn but permit "doSomething();;"
  'no-func-assign': 1, // Warn but permit in case if need to shadow a function declaration "function asd() {}" from some library. Mostly because jQuery.
  'no-invalid-regexp': 1, // Warn but let the invalid regex run (in case if it would be intended)
  'no-irregular-whitespace': 1, // Warn but permit non-tab non-whitespace "other space characters" in code. For comment / regex / whatever use.
  'no-sparse-arrays': 1, // Warn but allow user of empty array slots like [a,b,,,c] which translate to [a,b,undefined,undefined,c]
  'no-unreachable': 1, // Warn but allow. Even though "return x; console.log(y);" is technically a syntax error, the code works. Inform but build.
  'no-unsafe-finally': 1, // Warn but allow control flow changes inside "finally { return somethingElse; }" -block.
                          // MOTIVATION: 0 or 2 would be more reasonable, but I can't decide so make it inform yet continue the build. Each to their own.
  'no-unsafe-negation': 1, // Warn but allow using for example "let a = truthyVal; if (!a in someArray) { }" which reads "if false in someArray".
                           // Also (unfortunately) permits using "if (!a instanceof someVar)" which reads "if false instanceof someVar" which makes no sense.
  'valid-typeof': 1, // Warn but allow using "typeof someVar === 'non-common-so-possibly-typo-object-name'" even if it doesn't work. Inform but build.

  // (2) STOP BUILD AND ERROR IN THESE CASES
  'getter-return': 2, // Stop, no empty getters
  'no-compare-neg-zero': 2, // Stop, no "x === -0" comparisons
  'no-cond-assign': 2, // Stop, no "if (x = 0)", may deny some oneliners but these are bad coding practise anyway
  'no-debugger': 2, // No reason to use "debugger;" unless specified for the project
  'no-dupe-args': 2, // Stop, no "function(a,b,a) {}"
  'no-dupe-keys': 2, // Stop, no "obj = {a: 1, a: 2}"
  'no-duplicate-case': 2, // Stop, no "case 1: break; case 2: break; case 1: break;"
  'no-empty-character-class': 2, // Stop, prevent regex errors in cases triggering this like /^abc[]/
  'no-ex-assign': 2, // Stop, no "catch (e) { e = 'asd'; }" please. Let error tell where it originated from.
  'no-inner-declarations': 2, // Stop; parsers permit this, standard does not. No function myNamespace() { function doSomething() {}; }. Use fn expressions.
  'no-obj-calls': 2, // Stop, no calling Math(), JSON(), or Reflect() as-if functions. Use their methods instead.
  'use-isnan': 2, // Stop, no comparing NaN directly to anything. FORCE the use of function isNan() instead.

  /*
   * (DEFAULT DEFINED) RULES ON BEST PRACTISES
   */
  'no-octal': 0, // ALLOW use of Octal numbers e.g. "var myNum = 070;" -> 57 in decimal
  'no-case-declarations': 1, // Warn, RECOMMEND using blocks in case/default statements when initialising new variables in it
                             // SPECIFICATION: https://eslint.org/docs/rules/no-case-declarations
  'no-empty-pattern': 1, // Warn, when using no-op destructuring like "var {a: {}} = someVar;" or "var {} = someVar;"
  'no-global-assign': 1, // Warn, when re-assigning something in place of existing global variable (e.g. window, Object, and $ if specified in ESLint globals -option)
  'no-unused-labels': 1, // Warn, when having un-used case labels in code
                         // SPECIFICATION: https://eslint.org/docs/rules/no-unused-labels
  'no-useless-escape': 1, // Warn, when having uselessly escaped characters e.g. "a string with \' character" -> more correctly "a string with ' character"
  'no-redeclare': 2, // Stop, no re-declaring stuff with keyword "var", e.g. "var a = 1; var a = 2;". Use "var a = 1; a = 2;" instead
  'no-self-assign': 2, // Stop, no self-assign such as "a = a;" or "[a,b] = [a,c];".
  'no-fallthrough': 2, // Stop, no switch-case fallthrough with operation without specific "fallthrough" comment
                       // SPECIFICATION: https://eslint.org/docs/rules/no-fallthrough

  /*
   * (DEFAULT DEFINED) RULES ON VARIABLES
   */
  'no-undef': 0, // ALLOW use of undefined and therefore presumably global variables. Bad practise, but we need it for this project involving implicit jQuery global.
                 // WE COULD use this rule with a separately specified /* global <whatever-defined-in-global> */ comment but for sake of simplicity just allow this.
  'no-unused-vars': 1, // Warn, when having unused variables or functions. Allow it anyway since these rules apply to BOTH development and "production".
  'no-delete-var': 2, // Stop, no using delete -keyword on variables. It is reserved for properties of an object, like "let obj = {a:1, b:2}; delete obj.b;"

  /*
   * (DEFAULT DEFINED) RULES ON CODING STYLES AND -PRACTISES
   */
  'no-mixed-spaces-and-tabs': 2, // Stop, no single lines of code containing BOTH whitespace and tab characters

  /*
   * (DEFAULT DEFINED) RULES ON ECMASCRIPT2015/ES6 SPECIFIC THINGIES
   */
  'constructor-super': 2, // Stop; Use super() when using "extends", do not use it when not extending. Force these cases.
  'no-class-assign': 1, // Warn, when assigning something else into a class e.g. "class A { }; A = 0;"
  'no-const-assign': 2, // Stop, no overriding const variables even if ES6/ES2015 may permit doing it.
  'no-dupe-class-members': 2, // Stop, no duplicate class members (properties or methods)
  'no-new-symbol': 2, // Stop, Symbol() is not meant to be called with new (and likely throws a type error).
  'no-this-before-super': 2, // Stop, no using this -keyword in constructor before super() -call. Superclass -> subclass.
  'require-yield': 2 // Stop, *generator functions should "yield" result(s) at some point, or they should not be generators.
};

gulp.task('html', function () {
  return gulp.src('sources/index.html')
    .pipe(gulp.dest('distribution'))
    .on('end', browsersync.reload);
});

gulp.task('sass-css', function(){
  return gulp.src('sources/scss/**/*.scss')
    .pipe(sass({outputStyle: 'compressed'})) // Minify aswell
    .pipe(autoprefixer({
      add: true,
      remove: true,
      cascade: false, // SASS is already minified so do not cascade
      browsers: ['last 2 versions', '> 1%', 'Firefox ESR'] // http://browserl.ist/?q=last+2+versions%2C+%3E+1%25%2C+Firefox+ESR
    }))
    .pipe(concatenate('bundle.min.css')) // Bundle css
    .pipe(gulp.dest('distribution'))
    .pipe(browsersync.reload({stream: true}));
});

gulp.task('javascript', function() {
  return gulp.src('sources/js/**/*.js')
    .pipe(eslint({
      envs: ['browser', 'es6'],
      globals: ['jQuery', '$'],
      rules: ESLINT_RULES,
      parserOptions: {
        sourceType: "module",
      }
    })).pipe(eslint.format()).pipe(eslint.failAfterError())
    .pipe(babel({presets: ['es2015']}))
    .pipe(concatenate('bundle.min.js')) // Bundle javascript
    .pipe(uglify().on('error', (err) => {gutil.log(err); throw new Error('Error when minifying - doublecheck mangled references');}))
    .pipe(gulp.dest('distribution'))
    .on('end', browsersync.reload);
});

gulp.task('browsersync', function() {
  browsersync.init({
    server: { baseDir: 'distribution' }
  })
});

gulp.task('watch', ['browsersync', 'html', 'sass-css', 'javascript'], function() {
  gulp.watch('sources/scss/**/*.scss', ['sass-css']);
  gulp.watch('sources/js/**/*.js', ['javascript']);
  gulp.watch('sources/index.html', ['html']);
});

gulp.task('just-build', ['html', 'sass-css', 'javascript']);<commit_msg>Actually remove the ES6 module support. We would have to use browserify/webpack otherwise and just no for this project.<commit_after>const gulp = require('gulp');
const gutil = require('gulp-util');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const concatenate = require('gulp-concat');
const browsersync = require('browser-sync').create();
const eslint = require('gulp-eslint');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

const ESLINT_RULES = {
  // For reference including all possible rules, and (if any) their sub-options, see https://eslint.org/docs/rules/

  /*
   * (ALL SUPPORTED) RULES ON (POTENTIAL) ERRORS regarding code syntax / structure / flow
   */

  // (0) ALLOW THESE CASES
  'no-console': 0, // ALLOW using console.log(), these settings are for BOTH development AND "production" environment
  'no-constant-condition': 0, // ALLOW "if (true)" and similar
  'no-control-regex': 0, // If someone uses control chars like /\x1f/ inside regex, presume they have a reason
  'no-extra-boolean-cast': 0, // ALLOW unnecessary casting to boolean with "if (!!myVar)" (for purpose of strongly implying "this is represented as boolean")
  'no-prototype-builtins': 0, // ALLOW calling directly "myInstance.hasOwnProperty('some_prop')" instead of myInstance.prototype.hasOwnProperty('some_prop')
  'no-regex-spaces': 0, // ALLOW using repeated whitespace literals in regex instead of / {10}/ for example of ten whitespaces. Regex allows it.
                        // MOTIVATION: Regex does not automatically convert these for us, yet those as a string of "          " and " {10}" ARE different.
  'no-template-curly-in-string': 0, // ALLOW use of let notATemplateString = "something ${something}"; aswell as with '-quotes. It is not a syntax error.
  'no-unexpected-multiline': 0, // ALLOW multiline commands, it is not a syntax error and SOMETIMES preferable. Syntax errors will show up elsewhere.
  'valid-jsdoc': 0, // ALLOW using whatever other commenting scheme than JSDoc. We aren't using it yet at least.
                    // MAY CHANGE if we start using JSDoc.

  // (1) WARN BUT CONTINUE BUILD IN THESE CASES
  'no-await-in-loop': 1, // Warn but let (reasonless) looped await calls be
  'for-direction': 1, // Warn but if intended infinite-loop, let it be
  'no-empty': 1, // Warn but if intended "if(something) {  }" let it be; Do not require a comment
  'no-extra-parens': 1, // Warn but permit "let calc = 6 - (2*3);"
  'no-extra-semi': 1, // Warn but permit "doSomething();;"
  'no-func-assign': 1, // Warn but permit in case if need to shadow a function declaration "function asd() {}" from some library. Mostly because jQuery.
  'no-invalid-regexp': 1, // Warn but let the invalid regex run (in case if it would be intended)
  'no-irregular-whitespace': 1, // Warn but permit non-tab non-whitespace "other space characters" in code. For comment / regex / whatever use.
  'no-sparse-arrays': 1, // Warn but allow user of empty array slots like [a,b,,,c] which translate to [a,b,undefined,undefined,c]
  'no-unreachable': 1, // Warn but allow. Even though "return x; console.log(y);" is technically a syntax error, the code works. Inform but build.
  'no-unsafe-finally': 1, // Warn but allow control flow changes inside "finally { return somethingElse; }" -block.
                          // MOTIVATION: 0 or 2 would be more reasonable, but I can't decide so make it inform yet continue the build. Each to their own.
  'no-unsafe-negation': 1, // Warn but allow using for example "let a = truthyVal; if (!a in someArray) { }" which reads "if false in someArray".
                           // Also (unfortunately) permits using "if (!a instanceof someVar)" which reads "if false instanceof someVar" which makes no sense.
  'valid-typeof': 1, // Warn but allow using "typeof someVar === 'non-common-so-possibly-typo-object-name'" even if it doesn't work. Inform but build.

  // (2) STOP BUILD AND ERROR IN THESE CASES
  'getter-return': 2, // Stop, no empty getters
  'no-compare-neg-zero': 2, // Stop, no "x === -0" comparisons
  'no-cond-assign': 2, // Stop, no "if (x = 0)", may deny some oneliners but these are bad coding practise anyway
  'no-debugger': 2, // No reason to use "debugger;" unless specified for the project
  'no-dupe-args': 2, // Stop, no "function(a,b,a) {}"
  'no-dupe-keys': 2, // Stop, no "obj = {a: 1, a: 2}"
  'no-duplicate-case': 2, // Stop, no "case 1: break; case 2: break; case 1: break;"
  'no-empty-character-class': 2, // Stop, prevent regex errors in cases triggering this like /^abc[]/
  'no-ex-assign': 2, // Stop, no "catch (e) { e = 'asd'; }" please. Let error tell where it originated from.
  'no-inner-declarations': 2, // Stop; parsers permit this, standard does not. No function myNamespace() { function doSomething() {}; }. Use fn expressions.
  'no-obj-calls': 2, // Stop, no calling Math(), JSON(), or Reflect() as-if functions. Use their methods instead.
  'use-isnan': 2, // Stop, no comparing NaN directly to anything. FORCE the use of function isNan() instead.

  /*
   * (DEFAULT DEFINED) RULES ON BEST PRACTISES
   */
  'no-octal': 0, // ALLOW use of Octal numbers e.g. "var myNum = 070;" -> 57 in decimal
  'no-case-declarations': 1, // Warn, RECOMMEND using blocks in case/default statements when initialising new variables in it
                             // SPECIFICATION: https://eslint.org/docs/rules/no-case-declarations
  'no-empty-pattern': 1, // Warn, when using no-op destructuring like "var {a: {}} = someVar;" or "var {} = someVar;"
  'no-global-assign': 1, // Warn, when re-assigning something in place of existing global variable (e.g. window, Object, and $ if specified in ESLint globals -option)
  'no-unused-labels': 1, // Warn, when having un-used case labels in code
                         // SPECIFICATION: https://eslint.org/docs/rules/no-unused-labels
  'no-useless-escape': 1, // Warn, when having uselessly escaped characters e.g. "a string with \' character" -> more correctly "a string with ' character"
  'no-redeclare': 2, // Stop, no re-declaring stuff with keyword "var", e.g. "var a = 1; var a = 2;". Use "var a = 1; a = 2;" instead
  'no-self-assign': 2, // Stop, no self-assign such as "a = a;" or "[a,b] = [a,c];".
  'no-fallthrough': 2, // Stop, no switch-case fallthrough with operation without specific "fallthrough" comment
                       // SPECIFICATION: https://eslint.org/docs/rules/no-fallthrough

  /*
   * (DEFAULT DEFINED) RULES ON VARIABLES
   */
  'no-undef': 0, // ALLOW use of undefined and therefore presumably global variables. Bad practise, but we need it for this project involving implicit jQuery global.
                 // WE COULD use this rule with a separately specified /* global <whatever-defined-in-global> */ comment but for sake of simplicity just allow this.
  'no-unused-vars': 1, // Warn, when having unused variables or functions. Allow it anyway since these rules apply to BOTH development and "production".
  'no-delete-var': 2, // Stop, no using delete -keyword on variables. It is reserved for properties of an object, like "let obj = {a:1, b:2}; delete obj.b;"

  /*
   * (DEFAULT DEFINED) RULES ON CODING STYLES AND -PRACTISES
   */
  'no-mixed-spaces-and-tabs': 2, // Stop, no single lines of code containing BOTH whitespace and tab characters

  /*
   * (DEFAULT DEFINED) RULES ON ECMASCRIPT2015/ES6 SPECIFIC THINGIES
   */
  'constructor-super': 2, // Stop; Use super() when using "extends", do not use it when not extending. Force these cases.
  'no-class-assign': 1, // Warn, when assigning something else into a class e.g. "class A { }; A = 0;"
  'no-const-assign': 2, // Stop, no overriding const variables even if ES6/ES2015 may permit doing it.
  'no-dupe-class-members': 2, // Stop, no duplicate class members (properties or methods)
  'no-new-symbol': 2, // Stop, Symbol() is not meant to be called with new (and likely throws a type error).
  'no-this-before-super': 2, // Stop, no using this -keyword in constructor before super() -call. Superclass -> subclass.
  'require-yield': 2 // Stop, *generator functions should "yield" result(s) at some point, or they should not be generators.
};

gulp.task('html', function () {
  return gulp.src('sources/index.html')
    .pipe(gulp.dest('distribution'))
    .on('end', browsersync.reload);
});

gulp.task('sass-css', function(){
  return gulp.src('sources/scss/**/*.scss')
    .pipe(sass({outputStyle: 'compressed'})) // Minify aswell
    .pipe(autoprefixer({
      add: true,
      remove: true,
      cascade: false, // SASS is already minified so do not cascade
      browsers: ['last 2 versions', '> 1%', 'Firefox ESR'] // http://browserl.ist/?q=last+2+versions%2C+%3E+1%25%2C+Firefox+ESR
    }))
    .pipe(concatenate('bundle.min.css')) // Bundle css
    .pipe(gulp.dest('distribution'))
    .pipe(browsersync.reload({stream: true}));
});

gulp.task('javascript', function() {
  return gulp.src('sources/js/**/*.js')
    .pipe(eslint({
      envs: ['browser', 'es6'],
      globals: ['jQuery', '$'],
      rules: ESLINT_RULES
    })).pipe(eslint.format()).pipe(eslint.failAfterError())
    .pipe(babel({presets: ['es2015']}))
    .pipe(concatenate('bundle.min.js')) // Bundle javascript
    .pipe(uglify().on('error', (err) => {gutil.log(err); throw new Error('Error when minifying - doublecheck mangled references');}))
    .pipe(gulp.dest('distribution'))
    .on('end', browsersync.reload);
});

gulp.task('browsersync', function() {
  browsersync.init({
    server: { baseDir: 'distribution' }
  })
});

gulp.task('watch', ['browsersync', 'html', 'sass-css', 'javascript'], function() {
  gulp.watch('sources/scss/**/*.scss', ['sass-css']);
  gulp.watch('sources/js/**/*.js', ['javascript']);
  gulp.watch('sources/index.html', ['html']);
});

gulp.task('just-build', ['html', 'sass-css', 'javascript']);<|endoftext|>


<commit_before>var gulp = require('gulp'),
    myth = require('gulp-myth'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    minify = require('gulp-minify-css'),
    ghPages = require('gulp-gh-pages'),

    // Node Modules
    del = require('del');

gulp.task('project', function () {
    gulp.src(['src/cinch.css'])
        .pipe(gulp.dest('dist'))
        .pipe(myth())
        .pipe(minify())
        .pipe(rename('cinch.lib.css'))
        .pipe(gulp.dest('dist'));
});

gulp.task('site', function () {
    gulp.src(['src/cinch.css', 'src/site.css'])
        .pipe(concat('site.css'))
        .pipe(myth())
        .pipe(gulp.dest('site/templates/css'));
});

gulp.task('clean', function () {
    del('dist/*');
    del('site/templates/css/*');
});

gulp.task('watch', function () {
    gulp.watch(['src/cinch.css', 'src/site.css'], ['project', 'site']);
});

gulp.task('default', ['project', 'site', 'watch']);
<commit_msg>Added deploy task to gulpfile.<commit_after>var gulp = require('gulp'),
    myth = require('gulp-myth'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    minify = require('gulp-minify-css'),
    ghPages = require('gulp-gh-pages'),

    // Node Modules
    del = require('del');

gulp.task('project', function () {
    gulp.src(['src/cinch.css'])
        .pipe(gulp.dest('dist'))
        .pipe(myth())
        .pipe(minify())
        .pipe(rename('cinch.lib.css'))
        .pipe(gulp.dest('dist'));
});

gulp.task('site', function () {
    gulp.src(['src/cinch.css', 'src/site.css'])
        .pipe(concat('site.css'))
        .pipe(myth())
        .pipe(gulp.dest('site/templates/css'));
});

gulp.task('deploy', function () {
    gulp.src('site/output')
        .pipe(ghPages());
});

gulp.task('clean', function () {
    del('dist/*');
    del('site/templates/css/*');
});

gulp.task('watch', function () {
    gulp.watch(['src/cinch.css', 'src/site.css'], ['project', 'site']);
});

gulp.task('default', ['project', 'site', 'watch']);
<|endoftext|>


<commit_before>var casual = require('casual');

module.exports = function(Sequelize) {
  'use strict';

  var _ = Sequelize.Utils._,
      DataTypes = Sequelize;

  Sequelize.prototype.fixtures = function () {

  };

  Sequelize.Model.prototype.fixtures = function (options) {
    options = to_options(options);
    var define = _.mapValues(this.rawAttributes, function (def, item) {
      return {
        def: def,
        custom_gen: options.define[item] || null,
        from_validate: from_validate(def),
        gen: random(def)
      };
    });

    function generator(options) {
      var self = this;
      options = to_options(options);

      function gen_associate(model) {
        return new Sequelize.Utils.CustomEventEmitter(function(emitter) {
          var count = 0;
          _.chain(options.include)
          .filter(function(associate) {
            return self.getAssociation(associate.model, associate.as);
          })
          .each(function(associate) {
            var option = _.extend({}, associate.fixture);
            if (associate.hasOwnProperty('include')) {
              option.include = associate.include;
            }
            associate = self.getAssociation(associate.model, associate.as);

            option = _.extend(option, {
              create: true,
              instance: model,
              accessors: associate.accessors
            });
            count++;

            associate.target.fixtures(option)
            .proxy(emitter, { events: ['error'] })
            .success(function() {
              count--;
              if (count === 0) {
                emitter.emit('success');
              }
            });
          });

          if (count === 0) {
            emitter.emit('success');
          }

        }).run();
      }

      function build() {
        var data = _.mapValues(define, function(fn, item) {
          var custom_gen = options.define[item] || fn.custom_gen || undefined;
          if (_.isFunction(custom_gen)) {
            return custom_gen();
          }
          if (!_.isUndefined(custom_gen)) {
            return custom_gen;
          }
          return (fn.from_validate || fn.gen)(options, fn.def);
        });

        return self.build(data);
      }

      function build_datasets() {
        if (options.num < 2) {
          return build();
        }

        var data = [];
        for (var i = 0, num = options.num; i < num; i++) {
          data.push(build());
        }
        return data;
      }

      function create_datasets() {
        return new Sequelize.Utils.CustomEventEmitter(function(emitter) {
          var i, num,
               chainer = new Sequelize.Utils.QueryChainer();
          if (options.instance && options.accessors && options.accessors.create) {
            for (i = 0, num = options.num; i < num; i++) {
              chainer.add(options.instance[options.accessors.create](build().values));
            }
          } else {
            for (i = 0, num = options.num; i < num; i++) {
              chainer.add(build().save());
            }
          }

          chainer.run()
          .proxy(emitter, { events: ['error'] })
          .success(function(models) {
            var find = {
              where: {id:[]},
              include: options.include
            };

            var chainer = new Sequelize.Utils.QueryChainer();
            _.each(models, function(model) {
              find.where.id.push(model.id);
              chainer.add(gen_associate(model));
            });

            chainer.run()
            .proxy(emitter, { events: ['error'] })
            .success(function() {
              self.findAll(find)
              .proxy(emitter, { events: ['error'] })
              .success(function(rows) {
                emitter.emit('success', rows);
              });
            });
          });
        }).run();
      }

      if (!options.create) {
        return build_datasets();
      }
      return create_datasets();
    }

    this.fixtures = generator;
    return this.fixtures(options);
  };

  var random_fn = {
    INTEGER: function() {
      return casual.integer(1, Math.pow(2, 31) - 1);
    },
    STRING: function() {
      return casual.string;
    },
    TEXT: function() {
      return casual.text;
    },
    BIGINT: function() {
      return casual.integer(1, Math.pow(2, 31) - 1);
    },
    FLOAT: function() {
      return casual.double(1, Math.pow(2, 31) - 1);
    },
    BOOLEAN: function() {
      return casual.integer() > 0;
    },
    DATE: function() {
      return new Date(casual.unix_time);
    },
    NOW: function() {
      return new Date();
    },
    BLOB: function() {
      return casual.text;
    },
    DECIMAL: function() {
      return casual.double(1, Math.pow(2, 31) - 1);
    },
    UUIDV1: function() {
      return casual.numerify('########-####-1###-####-############');
    },
    UUIDV4: function() {
      return casual.numerify('########-####-4###-####-############');
    }
  };
  random_fn.UUID = random_fn.UUIDV1;

  var validate = {
    isUrl: function() {
      return casual.url;
    },
    isEmail: function() {
      return casual.email;
    },
    isIP: function() {
      return casual.ip;
    },
    isIPv4: function() {
      return casual.ip;
    }
  };

  function from_validate(def) {
    if (!def.validate) {
      return;
    }

    for (var type in validate) {
      if (def.validate[type]) {
        return validate[type];
      }
    }
  }

  function auto_increment(options) {
    if (options.gen_auto_increment) {
      return _.uniqueId();
    }
    return null;
  }

  function unsupport(options) {
    if (!options.hasOwnProperty('default')) {
      return casual.numerify('###@unknow dataType');
    }
    if (_.isFunction(options.default)) {
      return options.default();
    }
    return options.default;
  }

  function random(def) {
    if (def.autoIncrement) {
      return auto_increment;
    }

    for (var type in random_fn) {
      var data_type = DataTypes[type];
      if (def === data_type || def.type === data_type || def.originalType === data_type) {
        return random_fn[type];
      }

      if (typeof data_type !== 'string' && def instanceof data_type) {
        return random_fn[type];
      }
    }

    return unsupport;
  }

  function to_options(options) {
    if (typeof options === 'number') {
      options = {num: options};
    }
    options = _.extend({define:{}}, options);

    options.num = Math.max(options.num, 1) || 1;

    if (options.hasOwnProperty('include')) {
      if (!options.include instanceof Array) {
        if (options.include.model) {
          options.include = [options.include];
        } else {
          options.include = undefined;
        }
      }

      if (!options.hasOwnProperty('create')) {
        options.create = !!options.include;
      }
    }

    return options;
  }

};
<commit_msg>refactor custom_gen<commit_after>var casual = require('casual');

module.exports = function(Sequelize) {
  'use strict';

  var _ = Sequelize.Utils._,
      DataTypes = Sequelize;

  Sequelize.prototype.fixtures = function () {

  };

  Sequelize.Model.prototype.fixtures = function (options) {
    options = to_options(options);
    var define = _.mapValues(this.rawAttributes, function (def, item) {
      return {
        def: def,
        gen: to_gen(options, item) || from_validate(def) || random(def)
      };
    });

    function generator(options) {
      var self = this;
      options = to_options(options);

      function gen_associate(model) {
        return new Sequelize.Utils.CustomEventEmitter(function(emitter) {
          var count = 0;
          _.chain(options.include)
          .filter(function(associate) {
            return self.getAssociation(associate.model, associate.as);
          })
          .each(function(associate) {
            var option = _.extend({}, associate.fixture);
            if (associate.hasOwnProperty('include')) {
              option.include = associate.include;
            }
            associate = self.getAssociation(associate.model, associate.as);

            option = _.extend(option, {
              create: true,
              instance: model,
              accessors: associate.accessors
            });
            count++;

            associate.target.fixtures(option)
            .proxy(emitter, { events: ['error'] })
            .success(function() {
              count--;
              if (count === 0) {
                emitter.emit('success');
              }
            });
          });

          if (count === 0) {
            emitter.emit('success');
          }

        }).run();
      }

      function build() {
        var data = _.mapValues(define, function(fn, item) {
          return (to_gen(options, item) || fn.gen)(options, fn.def);
        });

        return self.build(data);
      }

      function build_datasets() {
        if (options.num < 2) {
          return build();
        }

        var data = [];
        for (var i = 0, num = options.num; i < num; i++) {
          data.push(build());
        }
        return data;
      }

      function create_datasets() {
        return new Sequelize.Utils.CustomEventEmitter(function(emitter) {
          var i, num,
               chainer = new Sequelize.Utils.QueryChainer();
          if (options.instance && options.accessors && options.accessors.create) {
            for (i = 0, num = options.num; i < num; i++) {
              chainer.add(options.instance[options.accessors.create](build().values));
            }
          } else {
            for (i = 0, num = options.num; i < num; i++) {
              chainer.add(build().save());
            }
          }

          chainer.run()
          .proxy(emitter, { events: ['error'] })
          .success(function(models) {
            var find = {
              where: {id:[]},
              include: options.include
            };

            var chainer = new Sequelize.Utils.QueryChainer();
            _.each(models, function(model) {
              find.where.id.push(model.id);
              chainer.add(gen_associate(model));
            });

            chainer.run()
            .proxy(emitter, { events: ['error'] })
            .success(function() {
              self.findAll(find)
              .proxy(emitter, { events: ['error'] })
              .success(function(rows) {
                emitter.emit('success', rows);
              });
            });
          });
        }).run();
      }

      if (!options.create) {
        return build_datasets();
      }
      return create_datasets();
    }

    this.fixtures = generator;
    return this.fixtures(options);
  };

  var random_fn = {
    INTEGER: function() {
      return casual.integer(1, Math.pow(2, 31) - 1);
    },
    STRING: function() {
      return casual.string;
    },
    TEXT: function() {
      return casual.text;
    },
    BIGINT: function() {
      return casual.integer(1, Math.pow(2, 31) - 1);
    },
    FLOAT: function() {
      return casual.double(1, Math.pow(2, 31) - 1);
    },
    BOOLEAN: function() {
      return casual.integer() > 0;
    },
    DATE: function() {
      return new Date(casual.unix_time);
    },
    NOW: function() {
      return new Date();
    },
    BLOB: function() {
      return casual.text;
    },
    DECIMAL: function() {
      return casual.double(1, Math.pow(2, 31) - 1);
    },
    UUIDV1: function() {
      return casual.numerify('########-####-1###-####-############');
    },
    UUIDV4: function() {
      return casual.numerify('########-####-4###-####-############');
    }
  };
  random_fn.UUID = random_fn.UUIDV1;

  var validate = {
    isUrl: function() {
      return casual.url;
    },
    isEmail: function() {
      return casual.email;
    },
    isIP: function() {
      return casual.ip;
    },
    isIPv4: function() {
      return casual.ip;
    }
  };

  function from_validate(def) {
    if (!def.validate) {
      return;
    }

    for (var type in validate) {
      if (def.validate[type]) {
        return validate[type];
      }
    }
  }

  function auto_increment(options) {
    if (options.gen_auto_increment) {
      return _.uniqueId();
    }
    return null;
  }

  function unsupport(options) {
    if (!options.hasOwnProperty('default')) {
      return casual.numerify('###@unknow dataType');
    }
    if (_.isFunction(options.default)) {
      return options.default();
    }
    return options.default;
  }

  function random(def) {
    if (def.autoIncrement) {
      return auto_increment;
    }

    for (var type in random_fn) {
      var data_type = DataTypes[type];
      if (def === data_type || def.type === data_type || def.originalType === data_type) {
        return random_fn[type];
      }

      if (typeof data_type !== 'string' && def instanceof data_type) {
        return random_fn[type];
      }
    }

    return unsupport;
  }

  function to_options(options) {
    if (typeof options === 'number') {
      options = {num: options};
    }
    options = _.extend({define:{}}, options);

    options.num = Math.max(options.num, 1) || 1;

    if (options.hasOwnProperty('include')) {
      if (!options.include instanceof Array) {
        if (options.include.model) {
          options.include = [options.include];
        } else {
          options.include = undefined;
        }
      }

      if (!options.hasOwnProperty('create')) {
        options.create = !!options.include;
      }
    }

    return options;
  }

  function to_gen(options, item) {
    var cb = options.define[item] || undefined;
    if (_.isUndefined(cb)) {
      return;
    }
    if (_.isFunction(cb)) {
      return cb;
    }
    return function () {
      return cb;
    };
  }

};
<|endoftext|>


<commit_before>module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.user.username, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Nome cadastrado: `, value: `${member.user.username}` /*value: "[link](http://google.com)."*/ },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Conta verificada: `, value: `${member.user.verified}` },
            { name: `Entrou no grupo: `, value: `${member.user.joinedTimestamp}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    });
  }
};<commit_msg><commit_after>module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.user.username, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Nome cadastrado: `, value: `${member.user.username}` /*value: "[link](http://google.com)."*/ },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Conta verificada: `, value: `${member.user.verified}` },
            { name: `Entrou no grupo: `, value: `${member.user.joinedAt}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    });
  }
};<|endoftext|>


<commit_before>var config = require('./config/config');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
// var io = require('../..')(server);
// New:
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

var  Chess = require('chess.js').Chess
 var feed = require('./modules/feed.js');

feed.init(io);
io.on('connect', function (socket) {
  socket.on('join', function (gameId) {
    socket.join(gameId);
    var allPlayers = io.sockets.adapter.rooms[gameId];
    if (allPlayers.length === 2) {
      var chess = new Chess();
      feed.gameStarted(gameId);
      socket.emit('move', {
        id: gameId,
        board: chess.fen(),
      });
    }
  })

  socket.on('move', function (game) {
    var chess = new Chess(game.board);
    chess.move(game.move);
    feed.move({
      gameId: game.id,
      board: chess.fen()
    });
    if (chess.game_over()) {
      feed.gameEnded(game.id, chess)
    } else {
      game.board = chess.fen();
      socket.broadcast.to(game.id).emit('move', game);
    }
  });
});
<commit_msg>Nå starter vi også http serveren<commit_after>var config = require('./config/config');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
// var io = require('../..')(server);
// New:
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

var  Chess = require('chess.js').Chess
 var feed = require('./modules/feed.js');

feed.init(io);
io.on('connect', function (socket) {
  socket.on('join', function (gameId) {
    socket.join(gameId);
    var allPlayers = io.sockets.adapter.rooms[gameId];
    if (allPlayers.length === 2) {
      var chess = new Chess();
      feed.gameStarted(gameId);
      socket.emit('move', {
        id: gameId,
        board: chess.fen(),
      });
    }
  })

  socket.on('move', function (game) {
    var chess = new Chess(game.board);
    chess.move(game.move);
    feed.move({
      gameId: game.id,
      board: chess.fen()
    });
    if (chess.game_over()) {
      feed.gameEnded(game.id, chess)
    } else {
      game.board = chess.fen();
      socket.broadcast.to(game.id).emit('move', game);
    }
  });
});

server.listen(port, function () {
    console.log('Running our app on port: ' + port)
});<|endoftext|>


<commit_before>// Gulp tools
var gulp = require('gulp');
var u = require('gulp-util');
var log = u.log;
var c = u.colors;

// Project deps
var nodemon = require('gulp-nodemon');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var bs = require('browser-sync');
var reload = bs.reload;

// -----------------------------------------------------------------------------
// Sass Task
//
// Compiles Sass and runs the CSS through autoprefixer.
// -----------------------------------------------------------------------------
gulp.task('sass', function() {
  bs.notify('Running: Sass task');
  return gulp.src('sass/**/*.scss')
    .pipe(sass({
        outputStyle: 'nested',
      })
      .on('error', function(err, res) {
        log(c.red('sass'), 'failed to compile');
        log(c.red('> ') + err.message);
        bs.notify('Sass failed to compile');
      })
    )
    .pipe(prefix('last 2 versions', '> 1%'))
    .pipe(gulp.dest('_public/css'))
    .pipe(reload({stream:true}));
});

// -----------------------------------------------------------------------------
// Browser Sync
// -----------------------------------------------------------------------------
gulp.task('bs', function() {
  bs({
    proxy: 'localhost:8080',
    files: 'css/*.css'
  });
});

// -----------------------------------------------------------------------------
// JS task
// -----------------------------------------------------------------------------
gulp.task('js', function() {
  return gulp.src([
    'js/hammer.min.js',
    'js/utils.js',
    'js/socket.js',
    'js/client.js',
  ])
  .pipe(concat('all.min.js'))
  .pipe(uglify())
  .pipe(gulp.dest('_public/js'));
});

// -----------------------------------------------------------------------------
// Watch tasks
// -----------------------------------------------------------------------------
gulp.task('watch', function() {
  gulp.watch('sass/**/*', ['sass']);
});

// -----------------------------------------------------------------------------
// Run the dev server
// -----------------------------------------------------------------------------
gulp.task('start', ['sass', 'js', 'watch', 'bs'], function () {
  nodemon({
    script: 'index.js',
    ext: 'js html dust',
    env: { 'NODE_ENV': 'development' }
  });
});

// -----------------------------------------------------------------------------
// Default should just start the server
// -----------------------------------------------------------------------------
gulp.task('default', ['start']);
<commit_msg>:ghost: disable BrowserSync ghostMode since bustashape does that part<commit_after>// Gulp tools
var gulp = require('gulp');
var u = require('gulp-util');
var log = u.log;
var c = u.colors;

// Project deps
var nodemon = require('gulp-nodemon');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var bs = require('browser-sync');
var reload = bs.reload;

// -----------------------------------------------------------------------------
// Sass Task
//
// Compiles Sass and runs the CSS through autoprefixer.
// -----------------------------------------------------------------------------
gulp.task('sass', function() {
  bs.notify('Running: Sass task');
  return gulp.src('sass/**/*.scss')
    .pipe(sass({
        outputStyle: 'nested',
      })
      .on('error', function(err, res) {
        log(c.red('sass'), 'failed to compile');
        log(c.red('> ') + err.message);
        bs.notify('Sass failed to compile');
      })
    )
    .pipe(prefix('last 2 versions', '> 1%'))
    .pipe(gulp.dest('_public/css'))
    .pipe(reload({stream:true}));
});

// -----------------------------------------------------------------------------
// Browser Sync
// -----------------------------------------------------------------------------
gulp.task('bs', function() {
  bs({
    proxy: 'localhost:8080',
    files: 'css/*.css',
    ghostMode: false // ghostMode is incompatible with bustashape's socket data.
  });
});

// -----------------------------------------------------------------------------
// JS task
// -----------------------------------------------------------------------------
gulp.task('js', function() {
  return gulp.src([
    'js/hammer.min.js',
    'js/utils.js',
    'js/socket.js',
    'js/client.js',
  ])
  .pipe(concat('all.min.js'))
  .pipe(uglify())
  .pipe(gulp.dest('_public/js'));
});

// -----------------------------------------------------------------------------
// Watch tasks
// -----------------------------------------------------------------------------
gulp.task('watch', function() {
  gulp.watch('sass/**/*', ['sass']);
});

// -----------------------------------------------------------------------------
// Run the dev server
// -----------------------------------------------------------------------------
gulp.task('start', ['sass', 'js', 'watch', 'bs'], function () {
  nodemon({
    script: 'index.js',
    ext: 'js html dust',
    env: { 'NODE_ENV': 'development' }
  });
});

// -----------------------------------------------------------------------------
// Default should just start the server
// -----------------------------------------------------------------------------
gulp.task('default', ['start']);
<|endoftext|>


<commit_before>var _ = require('lodash');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var rename = require('gulp-rename');
var minifyCSS = require('gulp-minify-css');
var browserify = require('browserify');
var mergeStream = require('merge-stream');
var source = require('vinyl-source-stream');

gulp.task('css', function() {
    var merged = mergeStream();

    _.each({
        'ebook.less': 'ebook/ebook.css',
        'pdf.less': 'ebook/pdf.css',
        'mobi.less': 'ebook/mobi.css',
        'epub.less': 'ebook/epub.css',
        'website.less': 'website/style.css'
    }, function(out, input) {
        gutil.log('compiling', input, 'into', out);
        merged.add(gulp.src('theme/stylesheets/'+input)
            .pipe(less())
            .pipe(minifyCSS())
            .pipe(rename(out))
            .pipe(gulp.dest('theme/assets/')));
    });

    return merged;
});

gulp.task('js', function() {
    return browserify('./theme/javascript/index.js')
        .bundle()
        .pipe(source('app.js'))
        .pipe(gulp.dest('./theme/assets/'));
});

gulp.task('assets', function() {
    return gulp.src('./node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('theme/assets/fonts/fontawesome/'));
});

gulp.task('default', ['css', 'js', 'assets'], function() {

});

<commit_msg>Fix copy of assets and js path in gulpfile<commit_after>var _ = require('lodash');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var rename = require('gulp-rename');
var minifyCSS = require('gulp-minify-css');
var browserify = require('browserify');
var mergeStream = require('merge-stream');
var source = require('vinyl-source-stream');

gulp.task('css', function() {
    var merged = mergeStream();

    _.each({
        'ebook.less': 'ebook/ebook.css',
        'pdf.less': 'ebook/pdf.css',
        'mobi.less': 'ebook/mobi.css',
        'epub.less': 'ebook/epub.css',
        'website.less': 'website/style.css'
    }, function(out, input) {
        gutil.log('compiling', input, 'into', out);
        merged.add(gulp.src('theme/stylesheets/'+input)
            .pipe(less())
            .pipe(minifyCSS())
            .pipe(rename(out))
            .pipe(gulp.dest('theme/assets/')));
    });

    return merged;
});

gulp.task('js', function() {
    return browserify('./theme/javascript/index.js')
        .bundle()
        .pipe(source('app.js'))
        .pipe(gulp.dest('./theme/assets/website'));
});

gulp.task('assets', function() {
    return gulp.src('./node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('theme/assets/website/fonts/fontawesome/'));
});

gulp.task('default', ['css', 'js', 'assets'], function() {

});

<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.2.0';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<commit_msg>Update binary to v0.3.0<commit_after>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.3.0';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<|endoftext|>