<commit_before>(function (exports, node) {

	var GameState = node.GameState;
	var Utils = node.Utils;

	/*
	 * GameLoop
	 *
	 * Handle the states of the game
	 *
	 */

	/**
	 * Expose constructor
	 */

	exports.GameLoop = GameLoop;

	function GameLoop (loop) {
		this.loop = loop || {};

		this.limits = Array();

		for (var key in this.loop) {
			if (this.loop.hasOwnProperty(key)) {

				// Transform the loop obj if necessary.
				// When a state executes only one step,
				// it is allowed to pass directly the name of the function.
				// So such function must be incapsulated in a obj here.
				var loop = this.loop[key].state;
				if ('function' === typeof loop) {
					var o = Utils.clone(this.loop[key]);
					//var steps = 1;
					this.loop[key].state = {1: o};
				}

				var steps = Utils.getListSize(this.loop[key].state)

				var round = this.loop[key].rounds || 1;
				this.limits.push({rounds: round, steps: steps});
			}
		}

		this.nStates = this.limits.length;
	}

	GameLoop.prototype.exist = function (gameState) {
		if (!gameState) return false;

		if (typeof(this.loop[gameState.state]) === 'undefined') {
			node.log('Unexisting state: ' + gameState.state, 'WARN');
			return false;
		}

		if (typeof(this.loop[gameState.state]['state'][gameState.step]) === 'undefined'){
			node.log('Unexisting step: ' + gameState.step, 'WARN');
			return false;
		}
		// States are 1 based, arrays are 0-based => -1
		if (gameState.round > this.limits[gameState.state-1]['rounds']) {
			node.log('Unexisting round: ' + gameState.round + 'Max round: ' + this.limits[gameState.state]['rounds'], 'WARN');
			return false;
		}

		//node.log('This exist: ' + gameState, 'ERR');

		return true;
	};

	GameLoop.prototype.next = function (gameState) {

		node.log('NEXT OF THIS ' + gameState, 'DEBUG');
		//node.log(this.limits);

		// Game has not started yet, do it!
		if (gameState.state === 0) {
			//node.log('NEXT: NEW');
			return new GameState({
								 state: 1,
								 step: 1,
								 round: 1
			});
		}

		if (!this.exist(gameState)) {
			node.log('No next state of non-existing state: ' + gameState, 'WARN');
			return false;
		}

		var idxLimit = Number(gameState.state)-1; // 0 vs 1 based

		if (this.limits[idxLimit]['steps'] > gameState.step){
			var newStep = Number(gameState.step)+1;
	//		node.log('Limit: ' + this.limits[gameState.state]['steps']);
//			node.log('NEXT STEP: '  + new GameState({
//														state: gameState.state,
//														step: newStep,
//														round: gameState.round
//			}));
//
			return new GameState({
				state: gameState.state,
				step: newStep,
				round: gameState.round
			});
		}

		if (this.limits[idxLimit]['rounds'] > gameState.round){
			var newRound = Number(gameState.round)+1;
			//node.log('NEXT ROUND: ' + new GameState(gameState.state,1,newRound));
			return new GameState({
				state: gameState.state,
				step: 1,
				round: newRound
			});
		}

		if (this.nStates > gameState.state){
			var newState = Number(gameState.state)+1;
			//node.log('NEXT STATE: ' + new GameState(newState,1,1));
			//return new GameState(newState,1,1);
			return new GameState({
				state: newState,
				step: 1,
				round: 1
			});
		}

		return false; // game over
	};

	GameLoop.prototype.previous = function (gameState) {

		if (!this.exist(gameState)) {
			node.log('No previous state of non-existing state: ' + gameState, 'WARN');
		}

		var idxLimit = Number(gameState.state)-1; // 0 vs 1 based

		if (gameState.step > 1){
			var oldStep = Number(gameState.step)-1;
			//return new GameState(gameState.state,oldStep,gameState.round);
			return new GameState({
				state: gameState.state,
				step: oldStep,
				round: gameState.round
			});
		}
		else if (gameState.round > 1){
			var oldRound = Number(gameState.round)-1;
			var oldStep = this.limits[idxLimit]['steps'];
			return new GameState({
				state: gameState.state,
				step: oldStep,
				round: oldRound
			});
		}
		else if (gameState.state > 1){
			var oldRound = this.limits[idxLimit-1]['rounds'];
			var oldStep = this.limits[idxLimit-1]['steps'];
			var oldState = idxLimit;
			return new GameState({
				state: oldState,
				step: oldStep,
				round: oldRound
			});
		}

		return false; // game init
	};

	GameLoop.prototype.getName = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step]['name'];
	};

	GameLoop.prototype.getAllParams = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step];
	};

	GameLoop.prototype.getFunction = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step]['state'];
	};

	GameLoop.prototype.jumpTo = function (gameState, jump) {
		if (!this.exist(gameState)) return false;
		if (!jump || jump === 0) return gameState;

		var gs = gameState;
		var func = (jump > 0) ? this.next : this.previous;

		for (var i=0; i < Math.abs(jump); i++) {
			gs = func.call(this,gs);
			if (!gs) return false;
		}

//		node.log('FROM');
//		node.log(gameState);
//		node.log('TO');
//		node.log(gs);

		return gs;
	};

	/**
	 * Compute the total number of steps to go.
	 */
	GameLoop.prototype.length = function (state) {
		var state = state || new GameState();
		var count = 0;
		while (state) {
			//console.log(glCopy);
			count++;
			var state = this.next(state);
		}
		return count;
	};

	GameLoop.prototype.toArray = function() {
		var state = new GameState();
		var out = [];
		while (state) {
			out.push(state.toString());
			var state = this.next(state);
		}
		return out;
	};

	/**
	 * Returns the ordinal position of a state in the game loop.
	 * All steps and rounds in between are counted.
	 *
	 */
	GameLoop.prototype.indexOf = function (state) {
		if (!state) return -1;
		return this.diff(state, new GameState())
	};

	/**
	 * Returns the difference in number of steps between two states in the
	 * current game loop. If the second state is not passed, the current game
	 * state is assumed. All steps and rounds in between are counted.
	 *
	 */
	GameLoop.prototype.diff = function (state1, state2) {
		if (!state1) return false;
		// TODO: if node.game is not initialized yet?
		var state2 = (state2) ? state2 : node.game.gameState;

		var idx = 0;
		while (state2) {
			if (GameState.compare(state1, state) === 0){
				return idx;
			}
			state2 = this.next(search);
			idx++;
		}
		return -1;
	};

})(
	'undefined' != typeof node ? node : module.exports
  , 'undefined' != typeof node ? node : module.parent.exports
);<commit_msg>Fixed bug in GameLoop.diff<commit_after>(function (exports, node) {

	var GameState = node.GameState;
	var Utils = node.Utils;

	/*
	 * GameLoop
	 *
	 * Handle the states of the game
	 *
	 */

	/**
	 * Expose constructor
	 */

	exports.GameLoop = GameLoop;

	function GameLoop (loop) {
		this.loop = loop || {};

		this.limits = Array();

		for (var key in this.loop) {
			if (this.loop.hasOwnProperty(key)) {

				// Transform the loop obj if necessary.
				// When a state executes only one step,
				// it is allowed to pass directly the name of the function.
				// So such function must be incapsulated in a obj here.
				var loop = this.loop[key].state;
				if ('function' === typeof loop) {
					var o = Utils.clone(this.loop[key]);
					//var steps = 1;
					this.loop[key].state = {1: o};
				}

				var steps = Utils.getListSize(this.loop[key].state)

				var round = this.loop[key].rounds || 1;
				this.limits.push({rounds: round, steps: steps});
			}
		}

		this.nStates = this.limits.length;
	}

	GameLoop.prototype.exist = function (gameState) {
		if (!gameState) return false;

		if (typeof(this.loop[gameState.state]) === 'undefined') {
			node.log('Unexisting state: ' + gameState.state, 'WARN');
			return false;
		}

		if (typeof(this.loop[gameState.state]['state'][gameState.step]) === 'undefined'){
			node.log('Unexisting step: ' + gameState.step, 'WARN');
			return false;
		}
		// States are 1 based, arrays are 0-based => -1
		if (gameState.round > this.limits[gameState.state-1]['rounds']) {
			node.log('Unexisting round: ' + gameState.round + 'Max round: ' + this.limits[gameState.state]['rounds'], 'WARN');
			return false;
		}

		//node.log('This exist: ' + gameState, 'ERR');

		return true;
	};

	GameLoop.prototype.next = function (gameState) {

		node.log('NEXT OF THIS ' + gameState, 'DEBUG');
		//node.log(this.limits);

		// Game has not started yet, do it!
		if (gameState.state === 0) {
			//node.log('NEXT: NEW');
			return new GameState({
								 state: 1,
								 step: 1,
								 round: 1
			});
		}

		if (!this.exist(gameState)) {
			node.log('No next state of non-existing state: ' + gameState, 'WARN');
			return false;
		}

		var idxLimit = Number(gameState.state)-1; // 0 vs 1 based

		if (this.limits[idxLimit]['steps'] > gameState.step){
			var newStep = Number(gameState.step)+1;
	//		node.log('Limit: ' + this.limits[gameState.state]['steps']);
//			node.log('NEXT STEP: '  + new GameState({
//														state: gameState.state,
//														step: newStep,
//														round: gameState.round
//			}));
//
			return new GameState({
				state: gameState.state,
				step: newStep,
				round: gameState.round
			});
		}

		if (this.limits[idxLimit]['rounds'] > gameState.round){
			var newRound = Number(gameState.round)+1;
			//node.log('NEXT ROUND: ' + new GameState(gameState.state,1,newRound));
			return new GameState({
				state: gameState.state,
				step: 1,
				round: newRound
			});
		}

		if (this.nStates > gameState.state){
			var newState = Number(gameState.state)+1;
			//node.log('NEXT STATE: ' + new GameState(newState,1,1));
			//return new GameState(newState,1,1);
			return new GameState({
				state: newState,
				step: 1,
				round: 1
			});
		}

		return false; // game over
	};

	GameLoop.prototype.previous = function (gameState) {

		if (!this.exist(gameState)) {
			node.log('No previous state of non-existing state: ' + gameState, 'WARN');
		}

		var idxLimit = Number(gameState.state)-1; // 0 vs 1 based

		if (gameState.step > 1){
			var oldStep = Number(gameState.step)-1;
			//return new GameState(gameState.state,oldStep,gameState.round);
			return new GameState({
				state: gameState.state,
				step: oldStep,
				round: gameState.round
			});
		}
		else if (gameState.round > 1){
			var oldRound = Number(gameState.round)-1;
			var oldStep = this.limits[idxLimit]['steps'];
			return new GameState({
				state: gameState.state,
				step: oldStep,
				round: oldRound
			});
		}
		else if (gameState.state > 1){
			var oldRound = this.limits[idxLimit-1]['rounds'];
			var oldStep = this.limits[idxLimit-1]['steps'];
			var oldState = idxLimit;
			return new GameState({
				state: oldState,
				step: oldStep,
				round: oldRound
			});
		}

		return false; // game init
	};

	GameLoop.prototype.getName = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step]['name'];
	};

	GameLoop.prototype.getAllParams = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step];
	};

	GameLoop.prototype.getFunction = function (gameState) {
		if (!this.exist(gameState)) return false;
		return this.loop[gameState.state]['state'][gameState.step]['state'];
	};

	GameLoop.prototype.jumpTo = function (gameState, jump) {
		if (!this.exist(gameState)) return false;
		if (!jump || jump === 0) return gameState;

		var gs = gameState;
		var func = (jump > 0) ? this.next : this.previous;

		for (var i=0; i < Math.abs(jump); i++) {
			gs = func.call(this,gs);
			if (!gs) return false;
		}

//		node.log('FROM');
//		node.log(gameState);
//		node.log('TO');
//		node.log(gs);

		return gs;
	};

	/**
	 * Compute the total number of steps to go.
	 */
	GameLoop.prototype.length = function (state) {
		var state = state || new GameState();
		var count = 0;
		while (state) {
			//console.log(glCopy);
			count++;
			var state = this.next(state);
		}
		return count;
	};

	GameLoop.prototype.toArray = function() {
		var state = new GameState();
		var out = [];
		while (state) {
			out.push(state.toString());
			var state = this.next(state);
		}
		return out;
	};

	/**
	 * Returns the ordinal position of a state in the game loop.
	 * All steps and rounds in between are counted.
	 *
	 */
	GameLoop.prototype.indexOf = function (state) {
		if (!state) return -1;
		return this.diff(state, new GameState());
	};

	/**
	 * Returns the difference in number of steps between two states in the
	 * current game loop. If the second state is not passed, the current game
	 * state is assumed. All steps and rounds in between are counted.
	 *
	 */
	GameLoop.prototype.diff = function (state1, state2) {
		if (!state1) return false;
		// TODO: if node.game is not initialized yet?
		var state2 = (state2) ? state2 : node.game.gameState;

		var idx = 0;
		while (state2) {
			if (GameState.compare(state1, state2) === 0){
				return idx;
			}
			state2 = this.next(state2);
			idx++;
		}
		return -1;
	};

})(
	'undefined' != typeof node ? node : module.exports
  , 'undefined' != typeof node ? node : module.parent.exports
);<|endoftext|>


<commit_before>
var simplechess = require('../'),
    assert = require('assert');

var White = simplechess.White;
var Black = simplechess.Black;
var King = simplechess.King;
var Rook = simplechess.Rook;

// No check in empty board

var board = simplechess.createBoard();
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), false);
assert.equal(game.inCheck(Black), false);

// No check in only king is present

var board = simplechess.createBoard();
board.putContent(3, 3, { color: White, piece: King });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), false);
assert.equal(game.inCheck(Black), false);

// Check if Rook attack

var board = simplechess.createBoard();
board.putContent(3, 3, { color: White, piece: King });
board.putContent(3, 7, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(3, 7);
board.putContent(3, 0, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(3, 0);
board.putContent(0, 3, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(0, 3);
board.putContent(7, 3, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

<commit_msg>Bishop attacks King, check<commit_after>
var simplechess = require('../'),
    assert = require('assert');

var White = simplechess.White;
var Black = simplechess.Black;
var King = simplechess.King;
var Rook = simplechess.Rook;
var Bishop = simplechess.Bishop;

// No check in empty board

var board = simplechess.createBoard();
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), false);
assert.equal(game.inCheck(Black), false);

// No check in only king is present

var board = simplechess.createBoard();
board.putContent(3, 3, { color: White, piece: King });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), false);
assert.equal(game.inCheck(Black), false);

// Check if Rook attacks

var board = simplechess.createBoard();
board.putContent(3, 3, { color: White, piece: King });
board.putContent(3, 7, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(3, 7);
board.putContent(3, 0, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(3, 0);
board.putContent(0, 3, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(0, 3);
board.putContent(7, 3, { color: Black, piece: Rook });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

// Check if Bishop attacks

var board = simplechess.createBoard();
board.putContent(3, 3, { color: White, piece: King });
board.putContent(1, 1, { color: Black, piece: Bishop });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(1, 1);
board.putContent(7, 7, { color: Black, piece: Bishop });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(7, 7);
board.putContent(1, 5, { color: Black, piece: Bishop });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

board.removeContent(1, 5);
board.putContent(5, 1, { color: Black, piece: Bishop });
var game = simplechess.createGame(board);

assert.equal(game.inCheck(White), true);
assert.equal(game.inCheck(Black), false);

<|endoftext|>


<commit_before>/**
 * Created by staticfunction on 8/27/14.
 */
var gulp = require('gulp');
var dts = require('dts-bundle');
var ts = require('gulp-typescript');
var mocha = require('gulp-mocha');
var replace = require('gulp-replace');
var insert = require('gulp-insert');
var pkg = require('./package.json');
var del = require('del');
var merge = require('merge2');

var BUILD_DIR = "bin-build";

//TODO: automate release to commonjs, amd and umd

gulp.task("compile", function() {
    var stream = gulp.src(['src/kola.ts','typings/tsd.d.ts'])
        .pipe(ts({
            module: "commonjs",
            declaration: true
        }))
        .pipe(gulp.dest(BUILD_DIR));

    return stream;
});

gulp.task('test', ['compile'], function() {
    return gulp.src('test/**/*.js', {read: false})
        .pipe(mocha({reporter: 'nyan'}));
});

gulp.task('bundle', function(cb) {
    dts.bundle({
        name: "kola",
        main: BUILD_DIR + '/kola.d.ts',
        out:  'kola.d.ts'
    });

    cb();
})

gulp.task('clean', function(cb) {
    del(['dist'], cb);
})

gulp.task('release', ['clean'], function() {

    var commonjs = gulp.src(['src/kola.ts', 'typings/tsd.d.ts'])
                    .pipe(ts({
                        declarationFiles: true,
                        module: 'commonjs',
                        noExternalResolve: false
        }));

    var amd = gulp.src(['src/kola.ts', 'typings/tsd.d.ts'])
                    .pipe(ts({
                        module: 'amd',
                        noExternalResolve: false
                    }));

    return merge([
        commonjs.dts
            .pipe(replace(/declare\s/g, ''))
            .pipe(insert.wrap('declare module \"'+ pkg.name +'\" {\n', '\n}'))
            .pipe(gulp.dest('dist')),
        commonjs.js
            .pipe(gulp.dest('dist')),
        amd.js
            .pipe(gulp.dest('dist/amd'))
    ])
})
<commit_msg>use gulp typescript for compilation of src and test<commit_after>/**
 * Created by staticfunction on 8/27/14.
 */
var gulp = require('gulp');
var dts = require('dts-bundle');
var ts = require('gulp-typescript');
var mocha = require('gulp-mocha');
var replace = require('gulp-replace');
var insert = require('gulp-insert');
var pkg = require('./package.json');
var del = require('del');
var merge = require('merge2');
var filter = require('gulp-filter');

var tsProject = ts.createProject({
    declarationFiles: false,
    module: 'commonjs'
})

var srcOutOnly = filter(['*', '!**Spec.*']);
var testOutOnly = filter(['**Spec.*']);

gulp.task("compile", ['clean'], function() {
    var commonjs = gulp.src(['src/kola.ts', 'test/**Spec.ts', 'typings/tsd.d.ts'])
                        .pipe(ts(tsProject));

    return commonjs.js
        .pipe(srcOutOnly)
        .pipe(gulp.dest('build/src'))
        .pipe(srcOutOnly.restore())
        .pipe(testOutOnly)
        .pipe(gulp.dest('build/test'))
});

gulp.task('test', ['compile'], function() {
    return gulp.src('build/test/**/*.js', {read: false})
        .pipe(mocha({reporter: 'nyan'}));
});

gulp.task('clean', function(cb) {
    del(['build'], cb);
})

gulp.task('clean-release', function(cb) {
    del(['dist'], cb);
})

gulp.task('release', ['clean-release'], function() {

    var commonjs = gulp.src(['src/kola.ts', 'typings/tsd.d.ts'])
                    .pipe(ts({
                        declarationFiles: true,
                        module: 'commonjs',
                        noExternalResolve: false
        }));

    var amd = gulp.src(['src/kola.ts', 'typings/tsd.d.ts'])
                    .pipe(ts({
                        module: 'amd',
                        noExternalResolve: false
                    }));

    return merge([
        commonjs.dts
            .pipe(replace(/declare\s/g, ''))
            .pipe(insert.wrap('declare module \"'+ pkg.name +'\" {\n', '\n}'))
            .pipe(gulp.dest('dist')),
        commonjs.js
            .pipe(gulp.dest('dist')),
        amd.js
            .pipe(gulp.dest('dist/amd'))
    ])
})
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var sourcemaps = require('gulp-sourcemaps');
var KarmaServer = require('karma').Server;

var bower = require('./bower.json');

var dist_dir = './'
var dist_file = 'launchpad.js';

gulp.task('version', function(){
    return gulp.src('template/version.js')
        .pipe(template(bower))
        .pipe(gulp.dest('src/'));
});

gulp.task('concat', ['version'], function(){
    return gulp.src(['src/observer.js', 'src/**.js'])
        .pipe(concat(dist_file, { newLine: ';' }))
        .pipe(gulp.dest(dist_dir));
});

gulp.task('jshint', ['concat'], function(){
    return gulp.src(dist_file)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('compress', ['concat'], function(){
    return gulp.src(dist_file)
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(rename({ extname: '.min.js' }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(dist_dir));
});

gulp.task('test', ['compress'], function(done){
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start()
});

gulp.task('tdd', ['compress'], function(done){
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js'
    }, done).start()
});

gulp.task('default', ['compress'], function(){
    /* noting to do here */
});
<commit_msg>Include jshint as dependency in compress task<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var sourcemaps = require('gulp-sourcemaps');
var KarmaServer = require('karma').Server;

var bower = require('./bower.json');

var dist_dir = './'
var dist_file = 'launchpad.js';

gulp.task('version', function(){
    return gulp.src('template/version.js')
        .pipe(template(bower))
        .pipe(gulp.dest('src/'));
});

gulp.task('concat', ['version'], function(){
    return gulp.src(['src/observer.js', 'src/**.js'])
        .pipe(concat(dist_file, { newLine: ';' }))
        .pipe(gulp.dest(dist_dir));
});

gulp.task('jshint', ['concat'], function(){
    return gulp.src(dist_file)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('compress', ['jshint'], function(){
    return gulp.src(dist_file)
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(rename({ extname: '.min.js' }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(dist_dir));
});

gulp.task('test', ['compress'], function(done){
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start()
});

gulp.task('tdd', ['compress'], function(done){
    new KarmaServer({
        configFile: __dirname + '/karma.conf.js'
    }, done).start()
});

gulp.task('default', ['compress'], function(){
    /* noting to do here */
});
<|endoftext|>


<commit_before>// Gulpfile.js
var gulp = require('gulp'),
  nodemon = require('gulp-nodemon'),
  jshint = require('gulp-jshint'),
  browserify = require('gulp-browserify');

gulp.task('lint', function () {
  gulp.src('./**/*.js')
    .pipe(jshint())
});

gulp.task('develop', function () {
  nodemon({ script: 'server', ext: 'html js' })
    .on('change', ['lint'])
    .on('restart', function () {
      console.log('restarted!')
    })
});

gulp.task('scripts', function() {
  gulp.src(['client/browser/js/main.js'])
    .pipe(browserify())
    .pipe(gulp.dest('./.build/js'));
});

gulp.task('copy', function() {
  gulp.src(['client/browser/index.html'])
    .pipe(gulp.dest('./.build'));
});

gulp.task('browser', ['scripts', 'copy']);<commit_msg>Add jsHint<commit_after>// Gulpfile.js
var gulp = require('gulp'),
  nodemon = require('gulp-nodemon'),
  jshint = require('gulp-jshint'),
  browserify = require('gulp-browserify');

gulp.task('lint', function () {
  gulp.src('./**/*.js')
    .pipe(jshint())
});

gulp.task('develop', function () {
  nodemon({ script: 'server', ext: 'html js' })
    .on('change', ['lint'])
    .on('restart', function () {
      console.log('restarted!')
    })
});

gulp.task('scripts', function() {
  gulp.src(['client/browser/js/main.js'])
    .pipe(browserify())
    .pipe(gulp.dest('./.build/js'));
});

gulp.task('copy', function() {
  gulp.src(['client/browser/index.html'])
    .pipe(gulp.dest('./.build'));
});

gulp.task('js', function () {
  return gulp.src('client/browser/js/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
});

gulp.task('browser', ['scripts', 'copy']);<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var mustache = require('gulp-mustache');
var connect = require('gulp-connect');
var fs = require('fs');

var workerSrc = [
  'src/trix.js',
  'bower_components/gif.js/src/NeuQuant.js',
  'bower_components/gif.js/src/LZWEncoder.js',
  'bower_components/gif.js/src/GIFEncoder.js',
  'src/worker.js'
];

var combineSrc = ['bower_components/html2canvas/build/html2canvas.js', 'dist/html2gif.js'];

gulp.task('worker', function() {
  return gulp.src(workerSrc)
    .pipe(concat('worker.js'))
    .pipe(gulp.dest('dist'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

gulp.task('html2gif', function() {
  return gulp.src('template/html2gif.mustache')
    .pipe(mustache({
      workerSrc: JSON.stringify(fs.readFileSync('dist/worker.js').toString()),
      html2gifSrc: fs.readFileSync('src/html2gif.js').toString()
    }, { extension: '.js' }))
    .pipe(gulp.dest("./dist"));
});

gulp.task('combine', function() {
  return gulp.src(combineSrc)
    .pipe(concat('html2gif.min.js'))
    .pipe(gulp.dest('dist'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

gulp.task('dev', function() {
  gulp.start('default');
  gulp.watch('*.js', ['default']);
  connect.server();
});

gulp.task('default', ['worker', 'html2gif', 'combine']);
<commit_msg>html2gif task depends on worker task<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var mustache = require('gulp-mustache');
var connect = require('gulp-connect');
var fs = require('fs');

var workerSrc = [
  'src/trix.js',
  'bower_components/gif.js/src/NeuQuant.js',
  'bower_components/gif.js/src/LZWEncoder.js',
  'bower_components/gif.js/src/GIFEncoder.js',
  'src/worker.js'
];

var combineSrc = ['bower_components/html2canvas/build/html2canvas.js', 'dist/html2gif.js'];

gulp.task('worker', function() {
  return gulp.src(workerSrc)
    .pipe(concat('worker.js'))
    .pipe(gulp.dest('dist'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

gulp.task('html2gif', ['worker'], function() {
  return gulp.src('template/html2gif.mustache')
    .pipe(mustache({
      workerSrc: JSON.stringify(fs.readFileSync('dist/worker.js').toString()),
      html2gifSrc: fs.readFileSync('src/html2gif.js').toString()
    }, { extension: '.js' }))
    .pipe(gulp.dest("./dist"));
});

gulp.task('combine', function() {
  return gulp.src(combineSrc)
    .pipe(concat('html2gif.min.js'))
    .pipe(gulp.dest('dist'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

gulp.task('dev', function() {
  gulp.start('default');
  gulp.watch('*.js', ['default']);
  connect.server();
});

gulp.task('default', ['worker', 'html2gif', 'combine']);
<|endoftext|>


<commit_before>var expect = chai.expect;
describe('Initializing', function() {
  it('with new', function() {
    expect(new Moon({el: "#initialize"}) instanceof Moon).to.equal(true);
  });
});

describe('Instance', function() {
  var destroyApp = new Moon({
    el: "#destroy",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('when destroyed', function() {
    destroyApp.destroy();
    destroyApp.set('msg', 'New Value!');
    expect(document.getElementById("destroy").innerHTML).to.not.equal("New Value!")
  });
});

describe('Data', function() {
  var dataApp = new Moon({
    el: "#data",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('when initializing', function() {
    expect(document.getElementById("data").innerHTML).to.equal("Hello Moon!");
  });
  it('when setting', function() {
    dataApp.set('msg', 'New Value');
    expect(document.getElementById("data").innerHTML).to.equal("New Value");
  });
  it('when getting', function() {
    expect(dataApp.get('msg')).to.equal("New Value");
  });
});

describe('Methods', function() {
  var methodApp = new Moon({
    el: "#method",
    data: {
      count: 0
    },
    methods: {
      increment: function() {
        methodApp.set('count', methodApp.get('count') + 1);
      }
    }
  });
  it('when calling a method', function() {
    methodApp.method('increment');
    expect(methodApp.get('count')).to.equal(1);
  });
  it('should update DOM', function() {
    methodApp.method('increment');
    expect(document.getElementById("method").innerHTML).to.equal('2');
  });
});

describe('If Directive', function() {
  var ifApp = new Moon({
    el: "#if",
    data: {
      condition: true
    }
  });
  it('should exist when true', function() {
    expect(document.getElementById('if-condition').innerHTML).to.equal('Condition True');
  });
  it('should not exist when false', function() {
    ifApp.set('condition', false);
    expect(document.getElementById('if-condition').innerHTML).to.not.equal('Condition True');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('if-condition').getAttribute("m-if")).to.be.null;
  });
});

describe('Show Directive', function() {
  var showApp = new Moon({
    el: "#show",
    data: {
      condition: true
    }
  });
  it('should display when true', function() {
    expect(document.getElementById('show-condition').style.display).to.equal('block');
  });
  it('should not display when false', function() {
    showApp.set('condition', false);
    expect(document.getElementById('show-condition').style.display).to.equal('none');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('show-condition').getAttribute("m-show")).to.be.null;
  });
});

describe('Model Directive', function() {
  var modelApp = new Moon({
    el: "#model",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('should update value when initialized', function() {
    expect(document.getElementById('model-msg').innerHTML).to.equal('Hello Moon!');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('model-msg-input').getAttribute("m-model")).to.be.null;
  });
});

describe('On Directive', function() {
  var onApp = new Moon({
    el: "#on",
    data: {
      count: 0
    },
    methods: {
      increment: function() {
        onApp.set('count', onApp.get('count') + 1);
      }
    }
  });
  it('should call a method', function() {
    document.getElementById("on-increment-button").click();
    expect(onApp.get('count')).to.equal(1);
  });
  it('should update DOM', function() {
    document.getElementById("on-increment-button").click();
    expect(document.getElementById("on-count").innerHTML).to.equal('2');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('on-increment-button').getAttribute("m-on")).to.be.null;
  });
});

describe('Text Directive', function() {
  var textApp = new Moon({
    el: "#text",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('should fill DOM with a value', function() {
    expect(document.getElementById("text-directive-span").innerHTML).to.equal("Hello Moon!");
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('text-directive-span').getAttribute("m-text")).to.be.null;
  });
});
<commit_msg>add building times<commit_after>var expect = chai.expect;
var MoonBuild = Moon.prototype.build;

Moon.prototype.build = function() {
  var id = "root@build";
  marky.mark(id);
  MoonBuild.apply(this, arguments);
  var time = marky.stop(id);
  console.log(id + " - " + time.duration);
}

describe('Initializing', function() {
  it('with new', function() {
    expect(new Moon({el: "#initialize"}) instanceof Moon).to.equal(true);
  });
});

describe('Instance', function() {
  var destroyApp = new Moon({
    el: "#destroy",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('when destroyed', function() {
    destroyApp.destroy();
    destroyApp.set('msg', 'New Value!');
    expect(document.getElementById("destroy").innerHTML).to.not.equal("New Value!")
  });
});

describe('Data', function() {
  var dataApp = new Moon({
    el: "#data",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('when initializing', function() {
    expect(document.getElementById("data").innerHTML).to.equal("Hello Moon!");
  });
  it('when setting', function() {
    dataApp.set('msg', 'New Value');
    expect(document.getElementById("data").innerHTML).to.equal("New Value");
  });
  it('when getting', function() {
    expect(dataApp.get('msg')).to.equal("New Value");
  });
});

describe('Methods', function() {
  var methodApp = new Moon({
    el: "#method",
    data: {
      count: 0
    },
    methods: {
      increment: function() {
        methodApp.set('count', methodApp.get('count') + 1);
      }
    }
  });
  it('when calling a method', function() {
    methodApp.method('increment');
    expect(methodApp.get('count')).to.equal(1);
  });
  it('should update DOM', function() {
    methodApp.method('increment');
    expect(document.getElementById("method").innerHTML).to.equal('2');
  });
});

describe('If Directive', function() {
  var ifApp = new Moon({
    el: "#if",
    data: {
      condition: true
    }
  });
  it('should exist when true', function() {
    expect(document.getElementById('if-condition').innerHTML).to.equal('Condition True');
  });
  it('should not exist when false', function() {
    ifApp.set('condition', false);
    expect(document.getElementById('if-condition').innerHTML).to.not.equal('Condition True');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('if-condition').getAttribute("m-if")).to.be.null;
  });
});

describe('Show Directive', function() {
  var showApp = new Moon({
    el: "#show",
    data: {
      condition: true
    }
  });
  it('should display when true', function() {
    expect(document.getElementById('show-condition').style.display).to.equal('block');
  });
  it('should not display when false', function() {
    showApp.set('condition', false);
    expect(document.getElementById('show-condition').style.display).to.equal('none');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('show-condition').getAttribute("m-show")).to.be.null;
  });
});

describe('Model Directive', function() {
  var modelApp = new Moon({
    el: "#model",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('should update value when initialized', function() {
    expect(document.getElementById('model-msg').innerHTML).to.equal('Hello Moon!');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('model-msg-input').getAttribute("m-model")).to.be.null;
  });
});

describe('On Directive', function() {
  var onApp = new Moon({
    el: "#on",
    data: {
      count: 0
    },
    methods: {
      increment: function() {
        onApp.set('count', onApp.get('count') + 1);
      }
    }
  });
  it('should call a method', function() {
    document.getElementById("on-increment-button").click();
    expect(onApp.get('count')).to.equal(1);
  });
  it('should update DOM', function() {
    document.getElementById("on-increment-button").click();
    expect(document.getElementById("on-count").innerHTML).to.equal('2');
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('on-increment-button').getAttribute("m-on")).to.be.null;
  });
});

describe('Text Directive', function() {
  var textApp = new Moon({
    el: "#text",
    data: {
      msg: "Hello Moon!"
    }
  });
  it('should fill DOM with a value', function() {
    expect(document.getElementById("text-directive-span").innerHTML).to.equal("Hello Moon!");
  });
  it('should not be present at runtime', function() {
    expect(document.getElementById('text-directive-span').getAttribute("m-text")).to.be.null;
  });
});
<|endoftext|>


<commit_before>var gulp   = require('gulp');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var istanbul = require('gulp-istanbul');
var rename = require('gulp-rename');
var browserify = require('gulp-browserify');
var exec = require('child_process').exec;

var paths = {
  files: ['src/**/*.js', 'src/**/*.css', 'src/**/*.html'],
  main: ['src/main.js'],
  tests: ['test/spec_helper.js', 'test/**/*_spec.js'],
  dist: 'dist'
};

var distFile = 'api.min.js';

var namespace = 'WP3';

gulp.task('default', ['lint', 'build']);

gulp.task('generate-jst', function() {
  exec('node bin/jst_generator.js', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

gulp.task('build', ['generate-jst'], function() {
  gulp.src(paths.main)
    .pipe(browserify())
    .pipe(rename(distFile))
    .pipe(gulp.dest(paths.dist))
    .on("error", function(err) {
      throw err;
    });
});

gulp.task('dist', ['generate-jst'], function() {
  gulp.src(paths.main)
    .pipe(browserify())
    .pipe(uglify())
    .pipe(rename(distFile))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('test', ['build'], function() {
  gulp.src(paths.tests)
    .pipe(mocha({reporter: 'nyan'}))
    .on('error', function(err) {
      throw err;
    });
});

gulp.task('coverage', function() {
  gulp.src(paths.files)
    .pipe(istanbul())
    .on('end', function() {
      gulp.src(paths.tests)
        .pipe(mocha())
        .pipe(istanbul.writeReports());
    });
});

gulp.task('lint', function() {
  gulp.src(paths.files)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish));
});

gulp.task('watch', function() {
  gulp.watch(paths.files, function() {
    gulp.run('build');
  });
});
<commit_msg>gulpfile: lint just the js files<commit_after>var gulp   = require('gulp');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var istanbul = require('gulp-istanbul');
var rename = require('gulp-rename');
var browserify = require('gulp-browserify');
var exec = require('child_process').exec;

var paths = {
  files: ['src/**/*.js', 'src/**/*.css', 'src/**/*.html'],
  main: ['src/main.js'],
  tests: ['test/spec_helper.js', 'test/**/*_spec.js'],
  dist: 'dist'
};

var distFile = 'api.min.js';

var namespace = 'WP3';

gulp.task('default', ['lint', 'build']);

gulp.task('generate-jst', function() {
  exec('node bin/jst_generator.js', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
  });
});

gulp.task('build', ['generate-jst'], function() {
  gulp.src(paths.main)
    .pipe(browserify())
    .pipe(rename(distFile))
    .pipe(gulp.dest(paths.dist))
    .on("error", function(err) {
      throw err;
    });
});

gulp.task('dist', ['generate-jst'], function() {
  gulp.src(paths.main)
    .pipe(browserify())
    .pipe(uglify())
    .pipe(rename(distFile))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('test', ['build'], function() {
  gulp.src(paths.tests)
    .pipe(mocha({reporter: 'nyan'}))
    .on('error', function(err) {
      throw err;
    });
});

gulp.task('coverage', function() {
  gulp.src(paths.files[0])
    .pipe(istanbul())
    .on('end', function() {
      gulp.src(paths.tests)
        .pipe(mocha())
        .pipe(istanbul.writeReports());
    });
});

gulp.task('lint', function() {
  gulp.src(paths.files[0])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish));
});

gulp.task('watch', function() {
  gulp.watch(paths.files, function() {
    gulp.run('build');
  });
});
<|endoftext|>


<commit_before>var Promise = require('bluebird')

var createWriteStream = require('fs').createWriteStream
var path = require('path')

var ZipFile = require('yazl').ZipFile

function pack (finishedPath, paths) {
  return new Promise(function (resolve, reject) {
    var zipper = new ZipFile()
    var zipped = createWriteStream(finishedPath)
                   .on('error', reject)
                   .on('close', function () { resolve(finishedPath) })
    zipper.outputStream.pipe(zipped)

    paths.forEach(function (trackPath) {
      zipper.addFile(trackPath, path.basename(trackPath))
    })
    zipper.end()
  })
}

module.exports = { pack: pack }
<commit_msg>test: support relative paths; delete packed files<commit_after>var Bluebird = require('bluebird')

var createWriteStream = require('fs').createWriteStream
var path = require('path')

var log = require('npmlog')
var rimraf = Bluebird.promisify(require('rimraf'))
var ZipFile = require('yazl').ZipFile

function pack (finishedPath, paths) {
  return new Bluebird(function (resolve, reject) {
    var zipper = new ZipFile()
    var zipped = createWriteStream(finishedPath)
                   .on('error', reject)
                   .on('close', resolve)
    zipper.outputStream.pipe(zipped)

    var root = path.dirname(finishedPath)
    log.silly('zip.pack', 'root', root)

    paths.forEach(function (trackPath) {
      var target = trackPath
      if (target.indexOf(root) === 0) {
        // need to strip the path separator
        target = target.slice(root.length + 1)
      }
      log.silly('zip.pack', 'entry path', target)
      zipper.addFile(trackPath, target)
    })
    zipper.end()
  }).then(function () {
    return Bluebird.each(paths, function (path) { return rimraf(path) })
  }).then(function () { return finishedPath })
}

module.exports = { pack: pack }
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    vfs = require('../lib/fs'),
    TEST_DIR = path.join(__dirname, 'test-dir');

module.exports = {
    setUp : function(done) {
        fs.mkdirSync(TEST_DIR);
        done();
    },

    tearDown : function(done) {
        fs.rmdirSync(TEST_DIR);
        done();
    },

    'should make directory' : function(test) {
        var dir = path.join(TEST_DIR, 'a');
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should make directory if exists' :  function(test) {
        var dir = path.join(TEST_DIR, 'a');
        fs.mkdirSync(dir);
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should be failed if directory exists' : function(test) {
        var dir = path.join(TEST_DIR, 'a');
        fs.mkdirSync(dir);
        vfs.makeDir(dir, true)
            .then(
                function() {
                    test.ok(false);
                },
                function() {
                    test.ok(true);
                })
            .always(function() {
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should be failed if file with same name exists' : function(test) {
        var dir = path.join(TEST_DIR, 'test-file');
        fs.writeFileSync(dir, 'test');
        vfs.makeDir(dir)
            .then(
                function() {
                    test.ok(false);
                },
                function() {
                    test.ok(true);
                })
            .always(function() {
                fs.unlink(path.join(TEST_DIR, 'test-file'));
                test.done();
            });
    },

    'should make directory tree' : function(test) {
        var dir = path.join(TEST_DIR, 'a/b/c');
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(path.join(TEST_DIR, 'a/b/c'));
                fs.rmdirSync(path.join(TEST_DIR, 'a/b'));
                fs.rmdirSync(path.join(TEST_DIR, 'a'));
                test.done();
            });
    },

    'should make directory tree if exists' : function(test) {
        var dir = path.join(TEST_DIR, 'a/b/c');
        fs.mkdirSync(path.join(TEST_DIR, 'a'));
        fs.mkdirSync(path.join(TEST_DIR, 'a', 'b'));
        fs.mkdirSync(dir);
        vfs.makeDir(dir)
            .then(
                function() {
                    test.ok(true);
                },
                function() {
                    test.ok(false);
                })
            .always(function() {
                fs.rmdirSync(path.join(TEST_DIR, 'a/b/c'));
                fs.rmdirSync(path.join(TEST_DIR, 'a/b'));
                fs.rmdirSync(path.join(TEST_DIR, 'a'));
                test.done();
            });
    }
};<commit_msg>unlink -> unlinkSync<commit_after>var fs = require('fs'),
    path = require('path'),
    vfs = require('../lib/fs'),
    TEST_DIR = path.join(__dirname, 'test-dir');

module.exports = {
    setUp : function(done) {
        fs.mkdirSync(TEST_DIR);
        done();
    },

    tearDown : function(done) {
        fs.rmdirSync(TEST_DIR);
        done();
    },

    'should make directory' : function(test) {
        var dir = path.join(TEST_DIR, 'a');
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should make directory if exists' :  function(test) {
        var dir = path.join(TEST_DIR, 'a');
        fs.mkdirSync(dir);
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should be failed if directory exists' : function(test) {
        var dir = path.join(TEST_DIR, 'a');
        fs.mkdirSync(dir);
        vfs.makeDir(dir, true)
            .then(
                function() {
                    test.ok(false);
                },
                function() {
                    test.ok(true);
                })
            .always(function() {
                fs.rmdirSync(dir);
                test.done();
            });
    },

    'should be failed if file with same name exists' : function(test) {
        var dir = path.join(TEST_DIR, 'test-file');
        fs.writeFileSync(dir, 'test');
        vfs.makeDir(dir)
            .then(
                function() {
                    test.ok(false);
                },
                function() {
                    test.ok(true);
                })
            .always(function() {
                fs.unlinkSync(path.join(TEST_DIR, 'test-file'));
                test.done();
            });
    },

    'should make directory tree' : function(test) {
        var dir = path.join(TEST_DIR, 'a/b/c');
        vfs.makeDir(dir)
            .then(
                function() {
                    return vfs.exists(dir);
                },
                function() {
                    test.ok(false);
                })
            .always(function(promise) {
                test.ok(promise.valueOf());
                test.ok(fs.statSync(dir).isDirectory());
                fs.rmdirSync(path.join(TEST_DIR, 'a/b/c'));
                fs.rmdirSync(path.join(TEST_DIR, 'a/b'));
                fs.rmdirSync(path.join(TEST_DIR, 'a'));
                test.done();
            });
    },

    'should make directory tree if exists' : function(test) {
        var dir = path.join(TEST_DIR, 'a/b/c');
        fs.mkdirSync(path.join(TEST_DIR, 'a'));
        fs.mkdirSync(path.join(TEST_DIR, 'a', 'b'));
        fs.mkdirSync(dir);
        vfs.makeDir(dir)
            .then(
                function() {
                    test.ok(true);
                },
                function() {
                    test.ok(false);
                })
            .always(function() {
                fs.rmdirSync(path.join(TEST_DIR, 'a/b/c'));
                fs.rmdirSync(path.join(TEST_DIR, 'a/b'));
                fs.rmdirSync(path.join(TEST_DIR, 'a'));
                test.done();
            });
    }
};<|endoftext|>


<commit_before>var Trellode = require('../index.js');
var Settings = require('./settings.json');

var trello = new Trellode(Settings.trello_key, Settings.trello_token);

trello.getBoards(function(err, data){
	console.log(err);
	console.log(data);
});

trello.getBoards({filter: 'open'}).then(function(boards){
		trello.getListsOfBoard(boards[0].id).then(function(lists){
			trello.addCardToList(lists[0].id, 'TestCard1').then(function(card){
				console.log(card);
			});
		});
});

trello.checkItemOfChecklist('Salsa', '559c1d05776922c6b99e70e6').then(function(res){
    console.log(res);
});<commit_msg>Remove manual test<commit_after>var Trellode = require('../index.js');
var Settings = require('./settings.json');

var trello = new Trellode(Settings.trello_key, Settings.trello_token);

trello.getBoards(function(err, data){
	console.log(err);
	console.log(data);
});

trello.getBoards({filter: 'open'}).then(function(boards){
		trello.getListsOfBoard(boards[0].id).then(function(lists){
			trello.addCardToList(lists[0].id, 'TestCard1').then(function(card){
				console.log(card);
			});
		});
});
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

	let OrderedArray = require('../lib/OrderedArray'),
	RangeArray =  require('../lib/RangeArray').default,
	assert = require('assert'),
	arr;

console.log(RangeArray);

beforeEach(() => {
	arr = new OrderedArray([ 'score' ], [
		{ id: 22, score: 2 },
		{ id: 44, score: 4 },
		{ id: 77, score: 7 }
	]);
});

it('constructor', () => {
	assert.deepEqual(arr.arr, [
		{ id: 22, score: 2 },
		{ id: 44, score: 4 },
		{ id: 77, score: 7 }
	]);
});

it('indexOf between items', () => {
	assert.equal(arr.indexOf(3), 1);
});

it('indexOf at first item', () => {
	assert.equal(arr.indexOf(2), 0);
});

it('indexOf at middle item', () => {
	assert.equal(arr.indexOf(4), 1);
});

it('indexOf at last item', () => {
	assert.equal(arr.indexOf(7), 2);
});

it('indexOf before first', () => {
	assert.equal(arr.indexOf(1), 0);
});

it('indexOf after last', () => {
	assert.equal(arr.indexOf(9), 3);
});

it('getRange on empty range', () => {
	let range = new OrderedArray([]).getRange();
	assert.deepEqual(range, new RangeArray([ [ -Infinity, Infinity ] ]));
});

it('getRange on array with one item', () => {
	let range = new OrderedArray([ 'time' ], [ {id: 'askdjnf', time: 4} ]).getRange();
	assert.deepEqual(range, new RangeArray([ [ 4, 4 ] ]));
});

it('slice with a 3 range[start, before, 0] inclusive', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(6, 3, 0),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, before, 0]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(7, 3, 0),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, 0, after]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(4, 0, 3),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, 0, after]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(3, 0, 3),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});
<commit_msg>Add more test for OrderedArray.slice<commit_after>/* eslint-env mocha */
'use strict';

	let OrderedArray = require('../lib/OrderedArray'),
	RangeArray =  require('../lib/RangeArray').default,
	assert = require('assert'),
	arr;

console.log(RangeArray);

beforeEach(() => {
	arr = new OrderedArray([ 'score' ], [
		{ id: 22, score: 2 },
		{ id: 44, score: 4 },
		{ id: 77, score: 7 }
	]);
});

it('constructor', () => {
	assert.deepEqual(arr.arr, [
		{ id: 22, score: 2 },
		{ id: 44, score: 4 },
		{ id: 77, score: 7 }
	]);
});

it('indexOf between items', () => {
	assert.equal(arr.indexOf(3), 1);
});

it('indexOf at first item', () => {
	assert.equal(arr.indexOf(2), 0);
});

it('indexOf at middle item', () => {
	assert.equal(arr.indexOf(4), 1);
});

it('indexOf at last item', () => {
	assert.equal(arr.indexOf(7), 2);
});

it('indexOf before first', () => {
	assert.equal(arr.indexOf(1), 0);
});

it('indexOf after last', () => {
	assert.equal(arr.indexOf(9), 3);
});

it('getRange on empty range', () => {
	let range = new OrderedArray([]).getRange();
	assert.deepEqual(range, new RangeArray([ [ -Infinity, Infinity ] ]));
});

it('getRange on array with one item', () => {
	let range = new OrderedArray([ 'time' ], [ {id: 'askdjnf', time: 4} ]).getRange();
	assert.deepEqual(range, new RangeArray([ [ 4, 4 ] ]));
});

it('slice with a 3 range[start, before, 0] inclusive', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(6, 3, 0),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, before, 0]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(7, 3, 0),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, 0, after]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(4, 0, 3),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[start, 0, after]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	assert.deepEqual(
		orderedArray.slice(3, 0, 3),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it('slice with a 3 range[-Infinity, 0, after]', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	console.log(orderedArray.slice(-Infinity, 0, 3));

	assert.deepEqual(
		orderedArray.slice(-Infinity, 0, 3),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});

it.only('slice with a 3 range[Infinity, before, 0] inclusive', () => {
	let orderedArray = new OrderedArray([ 'time' ], [
		{id: 'askdjnf', time: 4},
		{id: 'askdjnfj', time: 5},
		{id: 'askdjnfp', time: 6},
	]);

	console.log(orderedArray.slice(Infinity, 3, 0));

	assert.deepEqual(
		orderedArray.slice(Infinity, 3, 0),
		new OrderedArray(['time'], [
			{id: 'askdjnf', time: 4},
			{id: 'askdjnfj', time: 5},
			{id: 'askdjnfp', time: 6},
		])
	);
});
<|endoftext|>


<commit_before>/*jshint plusplus:false*/

var assert  = require('assert');
var fs      = require('fs');
var path    = require('path');
var nock    = require('nock');
var _       = require('lodash');
var rimraf  = require('rimraf');
var glob    = require('glob');
var async   = require('async');
var config  = require('../lib/core/config');
var Package = require('../lib/core/package');

describe('package', function () {

  function clean(done) {
    var del = 0;

    rimraf(config.directory, function () {
      // Ignore the error if the local directory was not actually deleted
      if (++del >= 2) done();
    });

    rimraf(config.cache, function () {
      // Ignore the error if the cache directory was not actually deleted
      if (++del >= 2) done();
    });
  }

  beforeEach(clean);
  after(clean);

  it('Should resolve git URLs properly', function () {
    var pkg = new Package('jquery', 'git://github.com/jquery/jquery.git');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
  });

  it('Should resolve git shorthands (username/project)', function () {
    var pkg = new Package('jquery', 'jquery/jquery');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
  });

  it('Should resolve git shorthands (username/project) with specific tag', function () {
    var pkg = new Package('jquery', 'jquery/jquery#1.0.0');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
    assert.equal(pkg.tag, '1.0.0');
  });

  it('Should resolve git HTTP URLs properly', function () {
    var pkg = new Package('jquery', 'git+http://example.com/project.git');
    assert.equal(pkg.gitUrl, 'http://example.com/project.git');
  });

  it('Should resolve git HTTPS URLs properly', function () {
    var pkg = new Package('jquery', 'git+https://example.com/project.git');
    assert.equal(pkg.gitUrl, 'https://example.com/project.git');
  });

  it('Should resolve git URL tags', function () {
    var pkg = new Package('jquery', 'git://github.com/jquery/jquery.git#v1.0.1');
    assert.equal(pkg.tag, 'v1.0.1');
  });

  it('Should resolve github urls', function () {
    var pkg = new Package('jquery', 'git@github.com:twitter/flight.git#v1.0.1');
    assert.equal(pkg.tag, 'v1.0.1');
    assert.equal(pkg.gitUrl, 'git@github.com:twitter/flight.git');
  });

  it('Should resolve normal HTTP URLs', function (next) {
    var pkg = new Package('bootstrap', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');

    pkg.on('resolve', function () {
      assert(pkg.assetUrl);
      assert.equal(pkg.assetUrl, 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should resolve url when we got redirected', function (next) {
    after(function () {
      nock.cleanAll();
    });

    var redirecting_url    = 'http://redirecting-url.com';
    var redirecting_to_url = 'http://redirected-to-url.com';

    nock(redirecting_url)
      .defaultReplyHeaders({'location': redirecting_to_url + '/jquery.js'})
      .get('/jquery.js')
      .reply(302);

    nock(redirecting_to_url)
      .get('/jquery.js')
      .reply(200, 'jquery content');

    var pkg = new Package('jquery', redirecting_url + '/jquery.js');

    pkg.on('resolve', function () {
      assert(pkg.assetUrl);
      assert.equal(pkg.assetUrl, redirecting_to_url + '/jquery.js');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error if the HTTP status is not OK', function (next) {
    var pkg = new Package('test', 'http://somedomainthatwillneverexistbower.com/test.js');

    pkg.on('resolve', function () {
      throw new Error('Should have given an error');
    });

    pkg.on('error', function () {
      next();
    });

    pkg.resolve();
  });

  it('Should clone git packages', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');

    pkg.on('resolve', function () {
      assert(pkg.path);
      assert(fs.existsSync(pkg.path));
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error on clone fail', function (next) {
    var pkg = new Package('random', 'git://example.com');

    pkg.on('error', function (err) {
      assert(err);
      next();
    });

    pkg.resolve();
  });

  it('Should copy path packages', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-jquery');

    pkg.on('resolve', function () {
      assert(pkg.path);
      assert(fs.existsSync(pkg.path));
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should load correct json', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-jquery');

    pkg.on('loadJSON', function () {
      assert(pkg.json);
      assert.equal(pkg.json.name, 'jquery');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.loadJSON();
  });

  it('Should give an error on an invalid components.json', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-invalid-json');

    pkg.on('error', function (error) {
      if (/parse json/i.test(error)) next();
      else throw new Error(error);
    });
    pkg.on('loadJSON', function () {
      throw new Error('Should have throw an error parsing the JSON.');
    });

    pkg.loadJSON();
  });

  it('Should resolve JSON dependencies', function (next) {
    var pkg = new Package('project', __dirname + '/assets/project');

    pkg.on('resolve', function () {
      var deps = _.pluck(pkg.getDeepDependencies(), 'name');
      assert.deepEqual(_.uniq(deps), ['package-bootstrap', 'jquery-ui', 'jquery']);
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error when copying fails from non existing path', function (next) {
    var pkg = new Package('project', __dirname + '/assets/project-non-existent');

    pkg.on('error', function (err) {
      assert(err);
      next();
    });

    pkg.resolve();
  });

  it('Should copy files from temp folder to local path', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      assert(fs.existsSync(pkg.localPath));
      next();
    });

    pkg.resolve();
  });

  it('Should treat local packages as git repositories if there is a .git', function (next) {
    var dir = __dirname + '/assets/package-repo';

    fs.renameSync(dir + '/git_repo', dir + '/.git');

    var pkg = new Package('spark-md5', dir);

    pkg.on('resolve', function () {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      assert(fs.existsSync(pkg.path + '/spark-md5.js'));
      assert(fs.existsSync(pkg.path + '/spark-md5.min.js'));
      assert(fs.existsSync(pkg.path + '/.jshintrc'));
      next();
    });

    pkg.on('error', function (err) {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should treat local packages as git repositories if there is a .git (and handle versions)', function (next) {
    var dir = __dirname + '/assets/package-repo';

    fs.renameSync(dir + '/git_repo', dir + '/.git');

    var pkg = new Package('spark-md5', dir + '#0.0.1');

    pkg.on('resolve', function () {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      assert(fs.existsSync(pkg.path + '/spark-md5.js'));
      assert(fs.existsSync(pkg.path + '/spark-md5.min.js'));
      assert(fs.existsSync(pkg.path + '/.jshintrc') === false);
      next();
    });

    pkg.on('error', function (err) {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should have accessible file permissions', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');
    var cachePath;

    pkg.on('cache', function () {
      cachePath = pkg.path;
    });

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      async.map([pkg.localPath, cachePath], fs.stat, function (err, results) {
        if (err) throw new Error(err);
        var mode0777 = parseInt('0777', 8);
        var expectedMode = mode0777 & (~process.umask());
        assert.equal(results[0].mode, results[1].mode);
        assert((results[0].mode & expectedMode) === expectedMode || results[0].mode === 16822);  // 16822 is for windows
        next();
      });
    });

    pkg.resolve();
  });

  it('Should have accessible file permissions for downloaded files', function (next) {
    var pkg = new Package('bootstrap', 'http://twitter.github.com/bootstrap/assets/bootstrap.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.stat(pkg.localPath, function (err, stat) {
        if (err) throw new Error(err);
        var mode0777 = parseInt('0777', 8);
        var expectedMode = mode0777 & (~process.umask());
        assert((stat.mode & expectedMode) === expectedMode || stat.mode === 16822);  // 16822 is for windows
        next();
      });
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should download normal URL packages', function (next) {
    var pkg = new Package('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should extract tar and zip files from normal URL packages', function (next) {
    var pkg = new Package('jquery', 'http://github.com/satazor/SparkMD5/archive/master.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') === -1);
        assert(files.indexOf('master.zip') === -1);
        assert(files.indexOf('spark-md5.js') !== -1);
        assert(files.indexOf('spark-md5.min.js') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should extract tar and zip files from normal URL packages and move them if the archive only contains a folder', function (next) {
    var pkg = new Package('jquery', 'http://twitter.github.com/bootstrap/assets/bootstrap.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') === -1);
        assert(files.indexOf('bootstrap.zip') === -1);
        assert(files.indexOf('js') !== -1);
        assert(files.indexOf('css') !== -1);
        assert(files.indexOf('img') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should remove ignored filepaths', function (next) {
    var pkg = new Package('turtles', __dirname + '/assets/package-ignorables');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    var pkgInstallPath = path.join(__dirname, '/../components/turtles/');
    pkg.on('install', function () {
      // these files should have been deleted
      assert(!fs.existsSync(pkgInstallPath + 'don.txt'));
      assert(!fs.existsSync(pkgInstallPath + 'leo.txt'));
      assert(!fs.existsSync(pkgInstallPath + '/test/'));
      // this file should still be there
      assert(fs.existsSync(pkgInstallPath + 'index.js'));
      // all ignore file pattern should be removed
      async.forEach(pkg.json.ignore, function (ignorePattern, asyncNext) {
        var pattern = path.join(__dirname, '/../components/turtles/' + ignorePattern);
        glob(pattern, function (err, globPath) {
          assert(globPath.length === 0);
          asyncNext();
        });
      }, next);
    });

    pkg.resolve();
  });
});
<commit_msg>test - should remove .git directory<commit_after>/*jshint plusplus:false*/

var assert  = require('assert');
var fs      = require('fs');
var path    = require('path');
var nock    = require('nock');
var _       = require('lodash');
var rimraf  = require('rimraf');
var glob    = require('glob');
var async   = require('async');
var config  = require('../lib/core/config');
var Package = require('../lib/core/package');

describe('package', function () {

  function clean(done) {
    var del = 0;

    rimraf(config.directory, function () {
      // Ignore the error if the local directory was not actually deleted
      if (++del >= 2) done();
    });

    rimraf(config.cache, function () {
      // Ignore the error if the cache directory was not actually deleted
      if (++del >= 2) done();
    });
  }

  beforeEach(clean);
  after(clean);

  it('Should resolve git URLs properly', function () {
    var pkg = new Package('jquery', 'git://github.com/jquery/jquery.git');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
  });

  it('Should resolve git shorthands (username/project)', function () {
    var pkg = new Package('jquery', 'jquery/jquery');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
  });

  it('Should resolve git shorthands (username/project) with specific tag', function () {
    var pkg = new Package('jquery', 'jquery/jquery#1.0.0');
    assert.equal(pkg.gitUrl, 'git://github.com/jquery/jquery.git');
    assert.equal(pkg.tag, '1.0.0');
  });

  it('Should resolve git HTTP URLs properly', function () {
    var pkg = new Package('jquery', 'git+http://example.com/project.git');
    assert.equal(pkg.gitUrl, 'http://example.com/project.git');
  });

  it('Should resolve git HTTPS URLs properly', function () {
    var pkg = new Package('jquery', 'git+https://example.com/project.git');
    assert.equal(pkg.gitUrl, 'https://example.com/project.git');
  });

  it('Should resolve git URL tags', function () {
    var pkg = new Package('jquery', 'git://github.com/jquery/jquery.git#v1.0.1');
    assert.equal(pkg.tag, 'v1.0.1');
  });

  it('Should resolve github urls', function () {
    var pkg = new Package('jquery', 'git@github.com:twitter/flight.git#v1.0.1');
    assert.equal(pkg.tag, 'v1.0.1');
    assert.equal(pkg.gitUrl, 'git@github.com:twitter/flight.git');
  });

  it('Should resolve normal HTTP URLs', function (next) {
    var pkg = new Package('bootstrap', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');

    pkg.on('resolve', function () {
      assert(pkg.assetUrl);
      assert.equal(pkg.assetUrl, 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should resolve url when we got redirected', function (next) {
    after(function () {
      nock.cleanAll();
    });

    var redirecting_url    = 'http://redirecting-url.com';
    var redirecting_to_url = 'http://redirected-to-url.com';

    nock(redirecting_url)
      .defaultReplyHeaders({'location': redirecting_to_url + '/jquery.js'})
      .get('/jquery.js')
      .reply(302);

    nock(redirecting_to_url)
      .get('/jquery.js')
      .reply(200, 'jquery content');

    var pkg = new Package('jquery', redirecting_url + '/jquery.js');

    pkg.on('resolve', function () {
      assert(pkg.assetUrl);
      assert.equal(pkg.assetUrl, redirecting_to_url + '/jquery.js');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error if the HTTP status is not OK', function (next) {
    var pkg = new Package('test', 'http://somedomainthatwillneverexistbower.com/test.js');

    pkg.on('resolve', function () {
      throw new Error('Should have given an error');
    });

    pkg.on('error', function () {
      next();
    });

    pkg.resolve();
  });

  it('Should clone git packages', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');

    pkg.on('resolve', function () {
      assert(pkg.path);
      assert(fs.existsSync(pkg.path));
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error on clone fail', function (next) {
    var pkg = new Package('random', 'git://example.com');

    pkg.on('error', function (err) {
      assert(err);
      next();
    });

    pkg.resolve();
  });

  it('Should copy path packages', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-jquery');

    pkg.on('resolve', function () {
      assert(pkg.path);
      assert(fs.existsSync(pkg.path));
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should load correct json', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-jquery');

    pkg.on('loadJSON', function () {
      assert(pkg.json);
      assert.equal(pkg.json.name, 'jquery');
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.loadJSON();
  });

  it('Should give an error on an invalid components.json', function (next) {
    var pkg = new Package('jquery', __dirname + '/assets/package-invalid-json');

    pkg.on('error', function (error) {
      if (/parse json/i.test(error)) next();
      else throw new Error(error);
    });
    pkg.on('loadJSON', function () {
      throw new Error('Should have throw an error parsing the JSON.');
    });

    pkg.loadJSON();
  });

  it('Should resolve JSON dependencies', function (next) {
    var pkg = new Package('project', __dirname + '/assets/project');

    pkg.on('resolve', function () {
      var deps = _.pluck(pkg.getDeepDependencies(), 'name');
      assert.deepEqual(_.uniq(deps), ['package-bootstrap', 'jquery-ui', 'jquery']);
      next();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should error when copying fails from non existing path', function (next) {
    var pkg = new Package('project', __dirname + '/assets/project-non-existent');

    pkg.on('error', function (err) {
      assert(err);
      next();
    });

    pkg.resolve();
  });

  it('Should copy files from temp folder to local path', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      assert(fs.existsSync(pkg.localPath));
      next();
    });

    pkg.resolve();
  });

  it('Should treat local packages as git repositories if there is a .git', function (next) {
    var dir = __dirname + '/assets/package-repo';

    fs.renameSync(dir + '/git_repo', dir + '/.git');

    var pkg = new Package('spark-md5', dir);

    pkg.on('resolve', function () {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      assert(fs.existsSync(pkg.path + '/spark-md5.js'));
      assert(fs.existsSync(pkg.path + '/spark-md5.min.js'));
      assert(fs.existsSync(pkg.path + '/.jshintrc'));
      next();
    });

    pkg.on('error', function (err) {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should treat local packages as git repositories if there is a .git (and handle versions)', function (next) {
    var dir = __dirname + '/assets/package-repo';

    fs.renameSync(dir + '/git_repo', dir + '/.git');

    var pkg = new Package('spark-md5', dir + '#0.0.1');

    pkg.on('resolve', function () {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      assert(fs.existsSync(pkg.path + '/spark-md5.js'));
      assert(fs.existsSync(pkg.path + '/spark-md5.min.js'));
      assert(fs.existsSync(pkg.path + '/.jshintrc') === false);
      next();
    });

    pkg.on('error', function (err) {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should have accessible file permissions', function (next) {
    var pkg = new Package('jquery', 'git://github.com/maccman/package-jquery.git');
    var cachePath;

    pkg.on('cache', function () {
      cachePath = pkg.path;
    });

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      async.map([pkg.localPath, cachePath], fs.stat, function (err, results) {
        if (err) throw new Error(err);
        var mode0777 = parseInt('0777', 8);
        var expectedMode = mode0777 & (~process.umask());
        assert.equal(results[0].mode, results[1].mode);
        assert((results[0].mode & expectedMode) === expectedMode || results[0].mode === 16822);  // 16822 is for windows
        next();
      });
    });

    pkg.resolve();
  });

  it('Should have accessible file permissions for downloaded files', function (next) {
    var pkg = new Package('bootstrap', 'http://twitter.github.com/bootstrap/assets/bootstrap.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.stat(pkg.localPath, function (err, stat) {
        if (err) throw new Error(err);
        var mode0777 = parseInt('0777', 8);
        var expectedMode = mode0777 & (~process.umask());
        assert((stat.mode & expectedMode) === expectedMode || stat.mode === 16822);  // 16822 is for windows
        next();
      });
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.resolve();
  });

  it('Should download normal URL packages', function (next) {
    var pkg = new Package('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should extract tar and zip files from normal URL packages', function (next) {
    var pkg = new Package('jquery', 'http://github.com/satazor/SparkMD5/archive/master.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') === -1);
        assert(files.indexOf('master.zip') === -1);
        assert(files.indexOf('spark-md5.js') !== -1);
        assert(files.indexOf('spark-md5.min.js') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should extract tar and zip files from normal URL packages and move them if the archive only contains a folder', function (next) {
    var pkg = new Package('jquery', 'http://twitter.github.com/bootstrap/assets/bootstrap.zip');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    pkg.on('install', function () {
      fs.readdir(pkg.localPath, function (err, files) {
        if (err) throw new Error(err);

        assert(files.indexOf('index.js') === -1);
        assert(files.indexOf('bootstrap.zip') === -1);
        assert(files.indexOf('js') !== -1);
        assert(files.indexOf('css') !== -1);
        assert(files.indexOf('img') !== -1);
        next();
      });
    });

    pkg.resolve();
  });

  it('Should remove ignored filepaths', function (next) {
    var pkg = new Package('turtles', __dirname + '/assets/package-ignorables');

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      throw new Error(err);
    });

    var pkgInstallPath = path.join(__dirname, '/../components/turtles/');
    pkg.on('install', function () {
      // these files should have been deleted
      assert(!fs.existsSync(pkgInstallPath + 'don.txt'));
      assert(!fs.existsSync(pkgInstallPath + 'leo.txt'));
      assert(!fs.existsSync(pkgInstallPath + '/test/'));
      // this file should still be there
      assert(fs.existsSync(pkgInstallPath + 'index.js'));
      // all ignore file pattern should be removed
      async.forEach(pkg.json.ignore, function (ignorePattern, asyncNext) {
        var pattern = path.join(__dirname, '/../components/turtles/' + ignorePattern);
        glob(pattern, function (err, globPath) {
          assert(globPath.length === 0);
          asyncNext();
        });
      }, next);
    });

    pkg.resolve();
  });

  it('Should remove .git directory', function (next) {
    var dir = __dirname + '/assets/package-repo';

    fs.renameSync(dir + '/git_repo', dir + '/.git');

    var pkg = new Package('spark-md5', dir);

    pkg.on('resolve', function () {
      pkg.install();
    });

    pkg.on('error', function (err) {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      throw new Error(err);
    });

    var pkgInstallPath = path.join(__dirname, '/../components/spark-md5/');
    pkg.on('install', function () {
      fs.renameSync(dir + '/.git', dir + '/git_repo');
      assert(!fs.existsSync(pkgInstallPath + '/.git/'));
      next();
    });

    pkg.resolve();
  });
});
<|endoftext|>


<commit_before>const system = require('system');

/* eslint-disable no-console */
/* globals phantom:false */

if (system.args.length !== 2) {
	console.log('Usage: phantom.js <URL>');
	phantom.exit(1);
}

const page = require('webpage').create();
phantom.onError = page.onError = function(err) {
	console.log(err);
	phantom.exit(1);
};

page.open(system.args[1], function(status) {
	if (status !== 'success') {
		console.log('Cannot load the page');
		phantom.exit(1);
	}
	phantom.exit(0);
});
<commit_msg>Chore: Try to add more logging to PhantomJS script<commit_after>const system = require('system');

/* eslint-disable no-console */
/* globals phantom:false */

if (system.args.length !== 2) {
	console.log('Usage: phantom.js <URL>');
	phantom.exit(1);
}

const page = require('webpage').create();
phantom.onError = page.onError = page.onResourceError = page.onResourceTimeout = function(err) {
	console.log(err);
	phantom.exit(1);
};

page.onConsoleMessage = function(msg) {
	console.log(msg);
};

page.viewportSize = { width: 1024, height: 768 };

page.open(system.args[1], function(status) {
	// page.render('screenshot.png');
	if (status !== 'success') {
		console.log('Cannot load the page');
		phantom.exit(1);
	}
	phantom.exit(0);
});
<|endoftext|>