<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var to5 = require('gulp-6to5');
var react = require('gulp-react');
var browserify = require('browserify');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var source = require('vinyl-source-stream');
var nodemon = require('gulp-nodemon');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }
		return path.join.apply(path, items);
	};
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.build.client = pathItem('client');

PATHS.client.scssLib = pathItem('scss_lib');
PATHS.client.components = pathItem('scss');

PATHS.client.js = pathItem('js');
PATHS.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* -- Actions -- */

/** BUild all js transpiling from ES6 to ES5 */
function buildJs() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(to5({ sourceRoot: PATHS.server() }))
    .pipe(gulp.dest(PATHS.build.server()));
}

/** Performs all unit tests */
function testUnit() {

  return gulp.src([
      // './node_modules/gulp-6to5/node_modules/6to5/register.js',
      PATHS.specs('env.js'),
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.build.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true, verbose: true}));

}

function cleanCache() {
  // Clear all caches to perform a full actions
  cached.caches = {};
}

/* --  Build tasks -- */

gulp.task('build:js', buildJs);

// Special task to order properly tasks
gulp.task('watch:js:test', ['build:js'], testUnit);

gulp.task('watch:js', function() {
  gulp.watch([
      PATHS.server('**/*.js'),
      PATHS.specs('**/*.js')
    ], ['build:js', 'watch:js:test']);
});

gulp.task('build:sass', function () {
  return gulp.src([
        PATHS.client.components('*.scss'),
        PATHS.client.scssLib('**/*.scss')
      ])
  		.pipe(sass({
  			includePaths: [ PATHS.client.scssLib() ]
  		}))
      .pipe(gulp.dest(PATHS.build.client('css')));
});

gulp.task('build:jsx', function() {
  return gulp.src(PATHS.client.js('components/**/*.jsx'))
      .pipe(plumber({errorHandler: notify.onError("Build:jsx : <%= error.message %>")}))
      .pipe(react({harmony: true}))
      .pipe(plumber.stop())
      .pipe(gulp.dest(PATHS.build.client('js/compiled')));
});

gulp.task('build:browserify', ['build:jsx'], function(){
  var b = browserify('./' + PATHS.build.client('js/compiled/main.js'))
  var stream = b.bundle()
    .pipe(source('main.js')) // the output filename
    .pipe(gulp.dest(PATHS.build.client('js'))); // the output directory
  return stream;
});

gulp.task('build', ['build:js', 'build:sass', 'build:browserify']);

/* -- Watcher -- */
gulp.task('watch:jsx', function() {
  gulp.watch(PATHS.client.js('components/**/*.jsx'), ['build:browserify']);
});

gulp.task('watch:sass', function() {
  gulp.watch(PATHS.client.components('*.scss'), ['build:sass']);
});

gulp.task('watch', ['watch:js', 'watch:jsx', 'watch:sass']);

//watch + server

gulp.task('develop', ['watch', 'server']);

/* -- Test task -- */

gulp.task('test:unit', ['server'], testUnit);
gulp.task('test:unit:kill', ['test:unit'], function() {
  process.exit();
});

gulp.task('test:lint', function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.build.client('js/compiled/**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(plumber({errorHandler: notify.onError("test:lint : <%= error.message %>")}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber.stop());
});

gulp.task('test', ['test:unit', 'test:lint']);

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/* -- Launch server -- */
gulp.task('server', function(done) {
  var isDone = false;

  nodemon({
    script: 'bin/catane',
    ignore: [
      PATHS.docs('libs/*'),
      PATHS.specs('**/*'),
      PATHS('**/*.spec.js')
    ],
    stderr: false,
    stdout: false
  }).on('start', function() {
      if(!isDone) {
        isDone = true;
        done();
      }
    })
    .on('crash', function() {
      console.log('Server already launched, just failing');
    });

});

gulp.task('clean:cache', cleanCache);

gulp.task('clean', [ 'clean:cache' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  var runSequence = require('run-sequence');
  runSequence('clean', 'build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
    process.exit();
  });
});
<commit_msg>Improve gulp watches.<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var babel = require('gulp-babel');
var react = require('gulp-react');
var browserify = require('browserify');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var source = require('vinyl-source-stream');
var nodemon = require('gulp-nodemon');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }
		return path.join.apply(path, items);
	};
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.build.client = pathItem('client');

PATHS.client.scssLib = pathItem('scss_lib');
PATHS.client.components = pathItem('scss');

PATHS.client.js = pathItem('js');
PATHS.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* -- Actions -- */

/** BUild all js transpiling from ES6 to ES5 */
function buildJs() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(babel({ sourceRoot: PATHS.server() }))
    .pipe(gulp.dest(PATHS.build.server()));
}

/** Performs all unit tests */
function testUnit() {
  return gulp.src([
      PATHS.specs('env.js'),
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.build.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true, verbose: true}));
}

function cleanCache() {
  // Clear all caches to perform a full actions
  cached.caches = {};
}

/* --  Build tasks -- */

gulp.task('build:js', buildJs);

// Special task to order properly tasks
gulp.task('watch:js:test', ['build:js'], testUnit);

gulp.task('watch:js', function() {
  gulp.watch([
      PATHS.server('**/*.js'),
      PATHS.specs('**/*.js')
    ], ['build:js', 'watch:js:test']);
});

gulp.task('build:sass', function () {
  return gulp.src([
        PATHS.client.components('*.scss'),
        PATHS.client.scssLib('**/*.scss')
      ])
  		.pipe(sass({
  			includePaths: [ PATHS.client.scssLib() ]
  		}))
      .pipe(gulp.dest(PATHS.build.client('css')));
});

gulp.task('build:jsx', function() {
  return gulp.src(PATHS.client.js('components/**/*.jsx'))
      .pipe(plumber({errorHandler: notify.onError("Build:jsx : <%= error.message %>")}))
      .pipe(react({harmony: true}))
      .pipe(plumber.stop())
      .pipe(gulp.dest(PATHS.build.client('js/compiled')));
});

gulp.task('build:browserify', ['build:jsx'], function(){
  var b = browserify('./' + PATHS.build.client('js/compiled/main.js'))
  var stream = b.bundle()
    .pipe(source('main.js')) // the output filename
    .pipe(gulp.dest(PATHS.build.client('js'))); // the output directory
  return stream;
});

gulp.task('build', ['build:js', 'build:sass', 'build:browserify']);

/* -- Watcher -- */
gulp.task('watch:jsx', function() {
  gulp.watch(PATHS.client.js('components/**/*.jsx'), ['watch:jsx:test']);
});

gulp.task('watch:jsx:test', ['build:browserify'], testUnit);

gulp.task('watch:sass', function() {
  gulp.watch(PATHS.client.components('*.scss'), ['build:sass']);
});

gulp.task('watch', ['watch:js', 'watch:jsx', 'watch:sass']);

//watch + server

gulp.task('develop', ['watch', 'server']);

/* -- Test task -- */

gulp.task('test:jsx', testUnit);
gulp.task('test:unit', ['server'], testUnit);
gulp.task('test:unit:kill', ['test:unit'], function() {
  process.exit();
});

gulp.task('test:lint', function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.build.client('js/compiled/**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(plumber({errorHandler: notify.onError("test:lint : <%= error.message %>")}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber.stop());
});

gulp.task('test', ['test:unit', 'test:lint']);

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/* -- Launch server -- */
gulp.task('server', function(done) {
  var isDone = false;

  nodemon({
    script: 'bin/catane',
    ignore: [
      PATHS.docs('libs/*'),
      PATHS.specs('**/*'),
      PATHS('**/*.spec.js')
    ],
    stderr: false,
    stdout: false
  }).on('start', function() {
      if(!isDone) {
        isDone = true;
        done();
      }
    })
    .on('crash', function() {
      console.log('Server already launched, just failing');
    });

});

gulp.task('clean:cache', cleanCache);

gulp.task('clean', [ 'clean:cache' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  var runSequence = require('run-sequence');
  runSequence('clean', 'build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
    process.exit();
  });
});
<|endoftext|>


<commit_before>/**********************************************************************************/
/*                                                                                */
/*                                   LIBRARIES                                    */
/*                                                                                */
/**********************************************************************************/

var fs = require('fs');
var ts = require('gulp-typescript');
var del = require('del');
var zip = require('gulp-zip');
var gulp = require('gulp');
var path = require('path');
var merge = require('merge2');
var mocha = require('gulp-spawn-mocha');
var spawn = require('child_process').spawn;
var bunyan = require('bunyan');
var mkdirp = require('mkdirp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var tslint = require('gulp-tslint');
var nodemon = require('gulp-nodemon');
var typedoc = require('gulp-typedoc');

var paths = {
    ts: ['ts/**/*.ts'],
    js: ['src/release/**/*.js'],
    tests: ['tests/server/**/*.js']
};

/**********************************************************************************/
/*                                                                                */
/*                                     TASKS                                      */
/*                                                                                */
/**********************************************************************************/

gulp.task('zip', gulp.series(_zip));
gulp.task('mkdirp', gulp.series(_mkdirp));
gulp.task('tslint', gulp.series(_tslint));
gulp.task('scratch', gulp.series(_scratch));
gulp.task('typedoc', gulp.series(_typedoc));

gulp.task('ts', gulp.series('tslint', _ts));
gulp.task('hook', gulp.series('ts', _hook));
gulp.task('test', gulp.series('scratch', 'mkdirp', 'ts', _test));
gulp.task('serve', gulp.series('mkdirp', 'ts', _serve));
gulp.task('minify', gulp.series('hook', _minify));

gulp.task('build', gulp.series('scratch', 'minify', 'zip'));
gulp.task('default', gulp.series('scratch', 'serve'));

/**********************************************************************************/
/*                                                                                */
/*                                     HOOKS                                      */
/*                                                                                */
/**********************************************************************************/

function _typedoc() {
    return gulp
        .src(paths.ts)
        .pipe(typedoc({
            out: 'docs/',
            name: 'battleship2.0-server',
            module: 'commonjs',
            target: 'es5'
        }));
}

function _tslint() {
    return gulp.src(paths.ts)
        .pipe(tslint({
            formatter: 'verbose',
            configuration: 'tslint.json'
        }))
        .pipe(tslint.report({
            emitError: false
        }));
}

function _mkdirp(done) {
    mkdirp.sync('logs');
    return done();
}

function _ts() {
    var tsResult = gulp.src(paths.ts)
        .pipe(ts({
            module: 'commonjs',
            declaration: true,
            removeComments: false,
            moduleResolution: 'node'
        }));

    return merge(
        tsResult.dts.pipe(gulp.dest('src/definitions')),
        tsResult.js.pipe(gulp.dest('src/release'))
    );
}

function _minify() {
    return gulp.src(paths.js)
        .pipe(concat('server.js'))
        .pipe(gulp.dest('src/dist/min'))
        .pipe(rename('server.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('src/dist/min'));
}

function _hook(done) {
    var environment = (process.argv[3] || 'dev').replace(/--/g, ''),
        filePath = __dirname + '/src/release',
        configFile = path.join('config', 'environments.json'),
        JSONConfigObject = JSON.parse(fs.readFileSync(configFile, 'utf8')),
        filesToReplace = Object.keys(JSONConfigObject.hooks),
        distFilenames = _getFiles(filePath);

    console.log('[+] On environment:', environment);

    filesToReplace.forEach(
        function (filePatternToReplace) {

            var realFile = filePatternToReplace;

            for (var i = 0; i < distFilenames.length; ++i) {

                var pattern = new RegExp(filePatternToReplace),
                    filename = distFilenames[i];

                if (pattern.test(filename)) {
                    realFile = filename;
                    break;
                }

            }

            if (fs.existsSync(realFile)) {

                console.log('[+] Interpolating ', realFile);

                Object.keys(JSONConfigObject.hooks[filePatternToReplace]).forEach(
                    function (variable) {

                        var conf = JSONConfigObject.hooks[filePatternToReplace][variable],
                            obj = {
                                value: conf.environments[environment],
                                pattern: conf.pattern
                            };

                        console.log('[+] Working on:', variable, '=', obj.value);
                        _replaceStringInFile(realFile, obj.pattern, obj.value);

                    }
                );

            } else {
                console.error('[ERROR] MISSING:', realFile);
            }

        }
    );

    return done();
}

function _getFiles(dirPath) {
    var files = [],
        dir = fs.readdirSync(dirPath);

    dir.forEach(function (object) {
        var _path = path.join(dirPath, object);
        if (fs.lstatSync(_path).isDirectory()) {
            files = files.concat(_getFiles(_path));
        } else files.push(_path);
    });

    return files;
}

function _replaceStringInFile(filename, toReplace, replaceWith) {
    fs.writeFileSync(filename, _replace(fs.readFileSync(filename, 'utf8'), toReplace, replaceWith), 'utf8');
}

function _replace(data, from, to) {
    return data.replace(new RegExp(from, 'g'), to);
}

function _scratch(error, toDelete) {
    toDelete = toDelete || ['src', 'logs'];
    return del(toDelete);
}

function _zip() {
    var timestamp = new Date().toJSON().substring(0, 20).replace(/-|:/g, '').replace('T', '_');
    return gulp.src('src/dist/**/*.js')
        .pipe(zip('battleship_server_' + timestamp + 'zip'))
        .pipe(gulp.dest('src/dist'));
}

function _serve(done) {
    var stream = nodemon({
        script: 'src/release/server.js',
        ext: 'ts',
        watch: paths.ts,
        tasks: ['ts'],
        stdout:   false,
        readable: false
    });

    stream.on('crash', function () {
        console.error('Application has crashed, restarting...');
        stream.emit('restart', 1);
    });

    stream.on('readable', function() {
        var bunyanPath = './node_modules/.bin/bunyan';

        if (/^win/.test(process.platform)) {
            bunyanPath = '.\\node_modules\\.bin\\bunyan.cmd';
        }

        bunyan = spawn(bunyanPath, ['-L', '-o', 'short', '--color'])
            .on('error', function( err ){ throw err });

        bunyan.stdout.pipe(process.stdout);
        bunyan.stderr.pipe(process.stderr);

        this.stdout.pipe(bunyan.stdin);
        this.stderr.pipe(bunyan.stdin);
    });

    return done();
}

function _test(done) {
    gulp.src(paths.tests)
        .pipe(mocha({reporter: 'dot'}))
        .once('end', done);
}
<commit_msg>Adding TypeDoc<commit_after>/**********************************************************************************/
/*                                                                                */
/*                                   LIBRARIES                                    */
/*                                                                                */
/**********************************************************************************/

var fs = require('fs');
var ts = require('gulp-typescript');
var del = require('del');
var zip = require('gulp-zip');
var gulp = require('gulp');
var path = require('path');
var merge = require('merge2');
var mocha = require('gulp-spawn-mocha');
var spawn = require('child_process').spawn;
var bunyan = require('bunyan');
var mkdirp = require('mkdirp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var tslint = require('gulp-tslint');
var nodemon = require('gulp-nodemon');
var typedoc = require('gulp-typedoc');

var paths = {
    ts: ['ts/**/*.ts'],
    js: ['src/release/**/*.js'],
    tests: ['tests/server/**/*.js']
};

/**********************************************************************************/
/*                                                                                */
/*                                     TASKS                                      */
/*                                                                                */
/**********************************************************************************/

gulp.task('zip', gulp.series(_zip));
gulp.task('mkdirp', gulp.series(_mkdirp));
gulp.task('tslint', gulp.series(_tslint));
gulp.task('scratch', gulp.series(_scratch));
gulp.task('typedoc', gulp.series(_typedoc));

gulp.task('ts', gulp.series('tslint', _ts));
gulp.task('hook', gulp.series('ts', _hook));
gulp.task('test', gulp.series('scratch', 'mkdirp', 'ts', _test));
gulp.task('serve', gulp.series('mkdirp', 'ts', _serve));
gulp.task('minify', gulp.series('hook', _minify));

gulp.task('build', gulp.series('scratch', 'minify', 'zip'));
gulp.task('default', gulp.series('scratch', 'serve'));

/**********************************************************************************/
/*                                                                                */
/*                                     HOOKS                                      */
/*                                                                                */
/**********************************************************************************/

function _typedoc() {
    return gulp
        .src(paths.ts)
        .pipe(typedoc({
            out: 'docs/',
            name: 'battleship2.0-server',
            module: 'commonjs',
            target: 'es5',
            hideGenerator: true,
            includeDeclarations: true
        }));
}

function _tslint() {
    return gulp.src(paths.ts)
        .pipe(tslint({
            formatter: 'verbose',
            configuration: 'tslint.json'
        }))
        .pipe(tslint.report({
            emitError: false
        }));
}

function _mkdirp(done) {
    mkdirp.sync('logs');
    return done();
}

function _ts() {
    var tsResult = gulp.src(paths.ts)
        .pipe(ts({
            module: 'commonjs',
            declaration: true,
            removeComments: false,
            moduleResolution: 'node'
        }));

    return merge(
        tsResult.dts.pipe(gulp.dest('src/definitions')),
        tsResult.js.pipe(gulp.dest('src/release'))
    );
}

function _minify() {
    return gulp.src(paths.js)
        .pipe(concat('server.js'))
        .pipe(gulp.dest('src/dist/min'))
        .pipe(rename('server.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('src/dist/min'));
}

function _hook(done) {
    var environment = (process.argv[3] || 'dev').replace(/--/g, ''),
        filePath = __dirname + '/src/release',
        configFile = path.join('config', 'environments.json'),
        JSONConfigObject = JSON.parse(fs.readFileSync(configFile, 'utf8')),
        filesToReplace = Object.keys(JSONConfigObject.hooks),
        distFilenames = _getFiles(filePath);

    console.log('[+] On environment:', environment);

    filesToReplace.forEach(
        function (filePatternToReplace) {

            var realFile = filePatternToReplace;

            for (var i = 0; i < distFilenames.length; ++i) {

                var pattern = new RegExp(filePatternToReplace),
                    filename = distFilenames[i];

                if (pattern.test(filename)) {
                    realFile = filename;
                    break;
                }

            }

            if (fs.existsSync(realFile)) {

                console.log('[+] Interpolating ', realFile);

                Object.keys(JSONConfigObject.hooks[filePatternToReplace]).forEach(
                    function (variable) {

                        var conf = JSONConfigObject.hooks[filePatternToReplace][variable],
                            obj = {
                                value: conf.environments[environment],
                                pattern: conf.pattern
                            };

                        console.log('[+] Working on:', variable, '=', obj.value);
                        _replaceStringInFile(realFile, obj.pattern, obj.value);

                    }
                );

            } else {
                console.error('[ERROR] MISSING:', realFile);
            }

        }
    );

    return done();
}

function _getFiles(dirPath) {
    var files = [],
        dir = fs.readdirSync(dirPath);

    dir.forEach(function (object) {
        var _path = path.join(dirPath, object);
        if (fs.lstatSync(_path).isDirectory()) {
            files = files.concat(_getFiles(_path));
        } else files.push(_path);
    });

    return files;
}

function _replaceStringInFile(filename, toReplace, replaceWith) {
    fs.writeFileSync(filename, _replace(fs.readFileSync(filename, 'utf8'), toReplace, replaceWith), 'utf8');
}

function _replace(data, from, to) {
    return data.replace(new RegExp(from, 'g'), to);
}

function _scratch(error, toDelete) {
    toDelete = toDelete || ['src', 'logs'];
    return del(toDelete);
}

function _zip() {
    var timestamp = new Date().toJSON().substring(0, 20).replace(/-|:/g, '').replace('T', '_');
    return gulp.src('src/dist/**/*.js')
        .pipe(zip('battleship_server_' + timestamp + 'zip'))
        .pipe(gulp.dest('src/dist'));
}

function _serve(done) {
    var stream = nodemon({
        script: 'src/release/server.js',
        ext: 'ts',
        watch: paths.ts,
        tasks: ['ts'],
        stdout:   false,
        readable: false
    });

    stream.on('crash', function () {
        console.error('Application has crashed, restarting...');
        stream.emit('restart', 1);
    });

    stream.on('readable', function() {
        var bunyanPath = './node_modules/.bin/bunyan';

        if (/^win/.test(process.platform)) {
            bunyanPath = '.\\node_modules\\.bin\\bunyan.cmd';
        }

        bunyan = spawn(bunyanPath, ['-L', '-o', 'short', '--color'])
            .on('error', function( err ){ throw err });

        bunyan.stdout.pipe(process.stdout);
        bunyan.stderr.pipe(process.stderr);

        this.stdout.pipe(bunyan.stdin);
        this.stderr.pipe(bunyan.stdin);
    });

    return done();
}

function _test(done) {
    gulp.src(paths.tests)
        .pipe(mocha({reporter: 'dot'}))
        .once('end', done);
}
<|endoftext|>


<commit_before>var exec = require('child_process').exec;

var argv = require('yargs').argv;  // Using instead of deprecated `gulp.env`.
var inquirer = require('inquirer');
var Promise = require('es6-promise').Promise;
var stylish = require('jshint-stylish');

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var runSequence = require('run-sequence');
var shell = require('gulp-shell');

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

var internals = {
  dbUrl: settings.POSTGRES_URL,
  dbName: settings.POSTGRES_URL.substring(
    settings.POSTGRES_URL.lastIndexOf('/') + 1
  ),
  sources: {
    scripts: [
      '*.js',
      'api/**/*.js',
      'lib/**/*.js'
    ]
  }
};

gulp.task('lint', function () {
  return gulp.src(internals.sources.scripts)
    .pipe(jshint({esnext: true}))
    .pipe(jshint.reporter(stylish));
});

gulp.task('createdb', shell.task([
  'createdb ' + internals.dbName
]));

gulp.task('dropdb', shell.task([
  'dropdb --if-exists ' + internals.dbName
]));

gulp.task('migratedb', ['migratedb-up']);

// Sample usage:
//
//   gulp migrate-up
//   gulp migrate-up --num 3
//
gulp.task('migratedb-up', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate up ' +
  (argv.num || argv.number || argv.n || '')
]));

// Sample usage:
//
//   gulp migrate-down
//   gulp migrate-down --num 3
//
gulp.task('migratedb-down', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate down ' +
  (argv.num || argv.number || argv.n || '')
]));

// Sample usage:
//
//   gulp migrate-down
//   gulp migrate-down --name addTimestampColumn
//
gulp.task('migratedb-create', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate create ' +
  (argv.name || argv.n || '')
]));

gulp.task('refreshdb', function (cb) {
  var runNow = function () {
    return runSequence(
      'dropdb',
      'createdb',
      'migratedb',
      cb
    );
  };

  if (process.argv.indexOf('--no-prompt') !== -1) {
    return runNow();
  }

  inquirer.prompt({
    type: 'confirm',
    name: 'val',
    message: 'Are you sure you want to drop the database?',
    default: false
  }, function (res) {
    if (!res.val) {
      return cb();
    }

    runNow();
  });
});
<commit_msg>improve pattern for jshint-able files<commit_after>var exec = require('child_process').exec;

var argv = require('yargs').argv;  // Using instead of deprecated `gulp.env`.
var inquirer = require('inquirer');
var Promise = require('es6-promise').Promise;
var stylish = require('jshint-stylish');

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var runSequence = require('run-sequence');
var shell = require('gulp-shell');

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

var internals = {
  dbUrl: settings.POSTGRES_URL,
  dbName: settings.POSTGRES_URL.substring(
    settings.POSTGRES_URL.lastIndexOf('/') + 1
  ),
  sources: {
    scripts: [
      '**/*.js',
      '!./node_modules/**/*.js',
    ]
  }
};

gulp.task('lint', function () {
  return gulp.src(internals.sources.scripts)
    .pipe(jshint({esnext: true}))
    .pipe(jshint.reporter(stylish));
});

gulp.task('createdb', shell.task([
  'createdb ' + internals.dbName
]));

gulp.task('dropdb', shell.task([
  'dropdb --if-exists ' + internals.dbName
]));

gulp.task('migratedb', ['migratedb-up']);

// Sample usage:
//
//   gulp migrate-up
//   gulp migrate-up --num 3
//
gulp.task('migratedb-up', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate up ' +
  (argv.num || argv.number || argv.n || '')
]));

// Sample usage:
//
//   gulp migrate-down
//   gulp migrate-down --num 3
//
gulp.task('migratedb-down', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate down ' +
  (argv.num || argv.number || argv.n || '')
]));

// Sample usage:
//
//   gulp migrate-down
//   gulp migrate-down --name addTimestampColumn
//
gulp.task('migratedb-create', shell.task([
  'DATABASE_URL="' + internals.dbUrl + '" ' +
  'node node_modules/.bin/pg-migrate create ' +
  (argv.name || argv.n || '')
]));

gulp.task('refreshdb', function (cb) {
  var runNow = function () {
    return runSequence(
      'dropdb',
      'createdb',
      'migratedb',
      cb
    );
  };

  if (process.argv.indexOf('--no-prompt') !== -1) {
    return runNow();
  }

  inquirer.prompt({
    type: 'confirm',
    name: 'val',
    message: 'Are you sure you want to drop the database?',
    default: false
  }, function (res) {
    if (!res.val) {
      return cb();
    }

    runNow();
  });
});
<|endoftext|>


<commit_before>/**
 * Created by Julien Verhaeghe => jverhaeghe.dev@gmail.com  on 3/12/2015.
 */

// --------- VARIABLES
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),

    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');

    server = require('gulp-server-livereload');

// --------- SERVER
gulp.task('webserver', function() {
    gulp.src('dist')
        .pipe(server({
            livereload: true,
            directoryListing: false,
            open: true
        }));
});

// --------- BUILDER
gulp.task('compile-js', function () {
    gulp.src(['!app/**/*test.js','!app/bower_components/**/*.js','app/*.js','app/*/*.js'])
        .pipe(concat('app.js'))
        .pipe(gulp.dest('dist/assets/js/'))
        .pipe(uglify())
        .pipe(notify({ message: 'JS are compiled' }));
});

gulp.task('compile-scss', function() {
    return gulp.src('app/assets/scss/main.scss')
        .pipe(sass({ style: 'expanded' }))
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/assets/css/'))
        .pipe(notify({ message: 'compile-scss task complete' }));
});

gulp.task('compile-html', function() {
    return gulp.src('app/**/*.html')

        .pipe(gulp.dest('dist/'))
        .pipe(notify({ message: 'All html are in place' }));
});

// --------- IMAGE
gulp.task('compress-images', function() {
    return gulp.src('app/asset/images/**/*')
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest('dist/asset/images'))
        .pipe(notify({ message: 'Images are compressed' }));
});

// --------- WATCHER
gulp.task('watch', function() {

    gulp.watch('app/assets/scss/**/*.scss', ['compile-scss']);

    gulp.watch('app/**/*.js', ['compile-js']);

    gulp.watch('app/**/*.html', ['compile-html']);

    gulp.watch('app/assets/images/**/*', ['compress-images']);

});

// --------- CLEAN
gulp.task('clean', function(cb) {
    del(['app/assets/css', 'app/assets/js', 'app/assets/images'], cb)
});

// --------- DEFAULT
gulp.task('default', ['clean'], function() {
    gulp.start('compile-scss', 'compile-js', 'compile-html','compress-images','watch','webserver')

});<commit_msg>Amelioration du gulpfile concernant les fichiers js à compiler<commit_after>/**
 * Created by Julien Verhaeghe => jverhaeghe.dev@gmail.com  on 3/12/2015.
 */

// --------- VARIABLES
var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),

    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');

    server = require('gulp-server-livereload');

// --------- SERVER
gulp.task('webserver', function() {
    gulp.src('dist')
        .pipe(server({
            livereload: true,
            directoryListing: false,
            open: true
        }));
});

// --------- BUILDER
gulp.task('compile-js', function () {
    gulp.src(['!app/**/*test.js','!app/dist/*.js','app/**/*.module.js','app/**/*.js'])
        .pipe(concat('app.js'))
        .pipe(gulp.dest('dist/assets/js/'))
        .pipe(uglify())
        .pipe(notify({ message: 'JS are compiled' }));
});

gulp.task('compile-scss', function() {
    return gulp.src('app/assets/scss/main.scss')
        .pipe(sass({ style: 'expanded' }))
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/assets/css/'))
        .pipe(notify({ message: 'compile-scss task complete' }));
});

gulp.task('compile-html', function() {
    return gulp.src('app/**/*.html')

        .pipe(gulp.dest('dist/'))
        .pipe(notify({ message: 'All html are in place' }));
});

// --------- IMAGE
gulp.task('compress-images', function() {
    return gulp.src('app/asset/images/**/*')
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest('dist/asset/images'))
        .pipe(notify({ message: 'Images are compressed' }));
});

// --------- WATCHER
gulp.task('watch', function() {

    gulp.watch('app/assets/scss/**/*.scss', ['compile-scss']);

    gulp.watch('app/**/*.js', ['compile-js']);

    gulp.watch('app/**/*.html', ['compile-html']);

    gulp.watch('app/assets/images/**/*', ['compress-images']);

});

// --------- CLEAN
gulp.task('clean', function(cb) {
    del(['app/assets/css', 'app/assets/js', 'app/assets/images'], cb)
});

// --------- DEFAULT
gulp.task('default', ['clean'], function() {
    gulp.start('compile-scss', 'compile-js', 'compile-html','compress-images','watch','webserver')

});<|endoftext|>


<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var polybuild = require('polybuild');
var dom = require('gulp-dom');
var babel = require('gulp-babel');

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var styleTask = function(stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.cssmin())
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function() {
  return styleTask('elements', ['**/*.css']);
});

gulp.task('scripts:es6', function() {
  return gulp.src('app/**/*.es6.js')
    .pipe(babel())
    .pipe(gulp.dest('.tmp'))
    .pipe(gulp.dest('dist'));
});

// Lint JavaScript
gulp.task('jshint', function() {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html',
      '!app/elements/_template-element',
      '!app/elements/automata-parser/parser.js',
      '!app/elements/**/test/**/*'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize images
gulp.task('images', function() {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src([
    'app/elements/**/*.html',
    'app/elements/**/*.css',
    'app/elements/**/*.js',
    '!app/elements/_template-element',
    '!app/elements/**/test/**/*'
  ]).pipe(gulp.dest('dist/elements'));

  // var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
  //   .pipe(gulp.dest('dist/elements/bootstrap'));
  //
  // var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
  //   .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized)//, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy web fonts to dist
gulp.task('fonts', function() {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    .pipe(dom(function() {
      var bsb = this.querySelector('#browser-sync-binding');
      if (bsb) {
        this.body.removeChild(bsb);
      }
      return this;
    }))
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace(
      'elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Polybuild will take care of inlining HTML imports,
// scripts and CSS for you.
gulp.task('vulcanize', function() {
  return gulp.src('dist/index.html')
    .pipe(polybuild({maximumCrush: true}))
    .pipe(gulp.dest('dist/'));
});

// If you require more granular configuration of Vulcanize
// than polybuild provides, follow instructions from readme at:
// https://github.com/PolymerElements/polymer-starter-kit/#if-you-require-more-granular-configuration-of-vulcanize-than-polybuild-provides-you-an-option-by

// Rename Polybuild's index.build.html to index.html
gulp.task('rename-index', function() {
  gulp.src('dist/index.build.html')
    .pipe($.rename('index.html'))
    .pipe(gulp.dest('dist/'));
  return del(['dist/index.build.html']);
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = 'dist';
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './',
        'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean output directory
gulp.task('clean', function(cb) {
  del(['.tmp', 'dist'], cb);
});

// Watch files for changes & reload
gulp.task('serve', ['styles', 'elements', 'scripts:es6', 'images'], function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()],
      routes: {
        '/bower_components': 'bower_components',
        '**/*.es6.js': 'dist/**/*.es6.js'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/**/*.es6.js'], ['scripts:es6', reload]);
  gulp.watch(['app/{scripts,elements}/**/{*.js,*.html}'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    https: true,
    server: 'dist'
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' after 'rename-index' if you are going to use service workers.
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['jshint', 'images', 'fonts', 'html'],
    'vulcanize','rename-index', // 'cache-config',
    cb);
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>updated build process<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

'use strict';

// Include Gulp & tools we'll use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');
var packageJson = require('./package.json');
var crypto = require('crypto');
var polybuild = require('polybuild');
var dom = require('gulp-dom');
var babel = require('gulp-babel');

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var styleTask = function(stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.cssmin())
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and automatically prefix stylesheets
gulp.task('styles', function() {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function() {
  return styleTask('elements', ['**/*.css']);
});

gulp.task('scripts:es6', function() {
  return gulp.src('app/**/*.es6.js')
    .pipe(babel())
    .pipe(gulp.dest('.tmp'))
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe(gulp.dest('dist'));
});

gulp.task('scripts', function() {
  return gulp.src(['app/scripts/*.js', '!app/**/*.es6.js'])
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe(gulp.dest('dist/scripts'));
});

// Lint JavaScript
gulp.task('jshint', function() {
  return gulp.src([
      'app/scripts/**/*.js',
      'app/elements/**/*.js',
      'app/elements/**/*.html',
      '!app/elements/_template-element',
      '!app/elements/automata-parser/parser.js',
      '!app/elements/**/test/**/*'
    ])
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint.extract()) // Extract JS from .html files
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize images
gulp.task('images', function() {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy all files at the root level (app)
gulp.task('copy', function() {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/cache-config.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src([
    'app/elements/**/*.html',
    'app/elements/**/*.css',
    'app/elements/**/*.js',
    '!app/elements/_template-element',
    '!app/elements/**/test/**/*'
  ]).pipe(gulp.dest('dist/elements'));

  // var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
  //   .pipe(gulp.dest('dist/elements/bootstrap'));
  //
  // var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
  //   .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized)//, swBootstrap, swToolbox)
    .pipe($.size({title: 'copy'}));
});

// Copy web fonts to dist
gulp.task('fonts', function() {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: ['.tmp', 'app', 'dist']});

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    .pipe(dom(function() {
      var bsb = this.querySelector('#browser-sync-binding');
      if (bsb) {
        this.body.removeChild(bsb);
      }
      return this;
    }))
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace(
      'elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Polybuild will take care of inlining HTML imports,
// scripts and CSS for you.
gulp.task('vulcanize', function() {
  return gulp.src('dist/index.html')
    .pipe(polybuild({maximumCrush: true}))
    .pipe($.uglify({preserveComments: 'some'}))
    .pipe(gulp.dest('dist/'));
});

// If you require more granular configuration of Vulcanize
// than polybuild provides, follow instructions from readme at:
// https://github.com/PolymerElements/polymer-starter-kit/#if-you-require-more-granular-configuration-of-vulcanize-than-polybuild-provides-you-an-option-by

// Rename Polybuild's index.build.html to index.html
gulp.task('rename-index', function() {
  gulp.src('dist/index.build.html')
    .pipe($.rename('index.html'))
    .pipe(gulp.dest('dist/'));
  return del(['dist/index.build.html']);
});

// Generate config data for the <sw-precache-cache> element.
// This include a list of files that should be precached, as well as a (hopefully unique) cache
// id that ensure that multiple PSK projects don't share the same Cache Storage.
// This task does not run by default, but if you are interested in using service worker caching
// in your project, please enable it within the 'default' task.
// See https://github.com/PolymerElements/polymer-starter-kit#enable-service-worker-support
// for more context.
gulp.task('cache-config', function(callback) {
  var dir = 'dist';
  var config = {
    cacheId: packageJson.name || path.basename(__dirname),
    disabled: false
  };

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './',
        'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      config.precache = files;

      var md5 = crypto.createHash('md5');
      md5.update(JSON.stringify(config.precache));
      config.precacheFingerprint = md5.digest('hex');

      var configPath = path.join(dir, 'cache-config.json');
      fs.writeFile(configPath, JSON.stringify(config), callback);
    }
  });
});

// Clean output directory
gulp.task('clean', function(cb) {
  del(['.tmp', 'dist'], cb);
});

// Watch files for changes & reload
gulp.task('serve', ['styles', 'elements', 'scripts:es6', 'images'], function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [historyApiFallback()],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/**/*.es6.js'], ['scripts:es6', reload]);
  gulp.watch(['app/{scripts,elements}/**/{*.js,*.html}'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', function() {
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'PSK',
    https: true,
    server: 'dist'
  });
});

// Build production files, the default task
gulp.task('default', ['clean'], function(cb) {
  // Uncomment 'cache-config' after 'rename-index' if you are going to use service workers.
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['scripts', 'scripts:es6', 'images', 'fonts', 'html'],
    'vulcanize','rename-index', // 'cache-config',
    cb);
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>var path = require('path')

var gulp = require('gulp')
  , concat = require('gulp-concat')
  , cssmin = require('gulp-cssmin')
  , gutil = require('gulp-util')
  , less = require('gulp-less')
  , rename = require('gulp-rename')
  , uglify = require('gulp-uglify')
  , watch = require('gulp-watch')

var bowerComponents = './bower_components'

gulp.task('default', ['less', 'js', 'vendor'])

gulp.task('less', function () {
  return compileLess()
})

gulp.task('js', function () {
  return compileJs()
})

gulp.task('vendor', ['vendor-css', 'vendor-js', 'vendor-assets'])

gulp.task('vendor-css', ['vendor-less'], function () {
  var prettify = path.join(bowerComponents, 'google-code-prettify', 'styles', 'desert.css')
  var vendorLess = path.join('tmp', 'vendor-less.css')

  return gulp.src([prettify, vendorLess])
    .pipe(concat('vendor.css'))
    .pipe(cssmin())
    .pipe(gulp.dest('assets/vendor'))
})

gulp.task('vendor-less', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome', 'less')

  return gulp.src(path.join('vendor-less', 'fontawesome.less'))
    .pipe(less({paths: [fontawesome]}))
    .pipe(rename({basename: 'vendor-less'}))
    .pipe(gulp.dest('tmp'))
})

gulp.task('vendor-js', function () {
  var prettify = path.join(bowerComponents, 'google-code-prettify', 'bin', 'prettify.min.js')
  return gulp.src([prettify])
    .pipe(concat('vendor.js'))
    .pipe(uglify())
    .pipe(gulp.dest('assets/vendor'))
})

gulp.task('vendor-assets', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome')

  return gulp.src(path.join(fontawesome, 'fonts/*.*'), {base: fontawesome})
    .pipe(gulp.dest('assets/vendor'))
})

gulp.task('watch', function () {
  watch('less/*.less', compileLess)
  watch('js/*.js', compileJs)
})

function compileJs() {
  gutil.log('Compiling js files.')
  return gulp.src('js/*.js')
    .pipe(uglify())
    .pipe(rename({basename: 'all', suffix:'.min'}))
    .pipe(gulp.dest('assets/js'))
}

function compileLess() {
  gutil.log('Compiling less files.')
  return gulp.src('less/app.less')
    .pipe(less({
      paths: [path.join(__dirname, 'less')]
    }))
    .pipe(cssmin())
    .pipe(rename({basename: 'style'}))
    .pipe(gulp.dest('assets/css'))
}<commit_msg>Fix path prefix for dist and src paths.<commit_after>var path = require('path')

var gulp = require('gulp')
  , concat = require('gulp-concat')
  , cssmin = require('gulp-cssmin')
  , gutil = require('gulp-util')
  , less = require('gulp-less')
  , rename = require('gulp-rename')
  , uglify = require('gulp-uglify')
  , watch = require('gulp-watch')

var bowerComponents = './bower_components'
  , dist = './assets'
  , src  = './src'

gulp.task('default', ['less', 'js', 'vendor'])

gulp.task('less', function () {
  return compileLess()
})

gulp.task('js', function () {
  return compileJs()
})

gulp.task('vendor', ['vendor-css', 'vendor-js', 'vendor-assets'])

gulp.task('vendor-css', ['vendor-less'], function () {
  var prettify = path.join(bowerComponents, 'google-code-prettify', 'styles', 'desert.css')
  var vendorLess = path.join('tmp', 'vendor-less.css')

  return gulp.src([prettify, vendorLess])
    .pipe(concat('vendor.css'))
    .pipe(cssmin())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-less', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome', 'less')

  return gulp.src(path.join('vendor-less', 'fontawesome.less'))
    .pipe(less({paths: [fontawesome]}))
    .pipe(rename({basename: 'vendor-less'}))
    .pipe(gulp.dest('tmp'))
})

gulp.task('vendor-js', function () {
  var prettify = path.join(bowerComponents, 'google-code-prettify', 'bin', 'prettify.min.js')
  return gulp.src([prettify])
    .pipe(concat('vendor.js'))
    .pipe(uglify())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-assets', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome')

  return gulp.src(path.join(fontawesome, 'fonts/*.*'), {base: fontawesome})
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('watch', function () {
  watch(path.join(src, 'less/*.less'), compileLess)
  watch(path.join(src, 'js/*.js'), compileJs)
})

function compileJs() {
  gutil.log('Compiling js files.')
  return gulp.src(path.join(src, 'js/*.js'))
    .pipe(uglify())
    .pipe(rename({basename: 'all', suffix:'.min'}))
    .pipe(gulp.dest(path.join(dist, 'js')))
}

function compileLess() {
  gutil.log('Compiling less files.')
  return gulp.src(path.join(src, 'less/app.less'))
    .pipe(less({
      paths: [path.join(src, 'less')]
    }))
    .pipe(cssmin())
    .pipe(rename({basename: 'style'}))
    .pipe(gulp.dest(path.join(dist, 'css')))
}<|endoftext|>


<commit_before>// Single var pattern of gulp (require) stuff in full effect!!!

var gulp = require("gulp"), // "require" gulp
    jade = require("gulp-jade"), // Jade task
    uncss = require("gulp-uncss"), // Remove unused css task
    minifyCSS = require("gulp-minify-css"), // Minify CSS
    concatCss = require("gulp-concat-css"), // Concatenate CSS
    csslint = require("gulp-csslint"), // Lint CSS
    concat = require("gulp-concat"), // For concatenating stuff(?)
    watch = require("gulp-watch"), // For watching files changes
    imagemin = require('gulp-imagemin'),

    // Live Reload stuff
    livereload = require("gulp-livereload"),
    lr = require("tiny-lr"),
    server = lr();

// End single var pattern

// Needed to run grunt tasks through gulp
require("gulp-grunt")(gulp);

/*
 *  ===================================================================
 *  | STORE PREPROCESSOR FILE REFERENCES IN VARIABLES |
 *  ===================================================================
 */
var jadeFiles = ["jade/index.jade", "jade/**/*.jade"], // Jade
    lessFiles = ["css-build/*.less", "css-build/**/*.less"], // LESS
    coffeeFiles = ["coffee/*.coffee"], // Coffeescript
    jsonFile = "build/js/playersInfo.json", // JSON files
    ignoreArray = [
                    ".cycle-slide"
                  ];

    /*
     * IGNORE ARRAY
     * ============
     * Selectors NOT to be removed when "gulp uncss" task runs.
     * Try to list them alphabetically and in the following order:
     *
     * 1. Page elements first (<nav>, <aside>, etc.)
     * 2. IDs second
     * 3. Classes third
     */
     ignoreArray = [
     "img.cycle-slide"
     ];

/*
 *  ===================================================================
 *  | JADE TASK |
 *  ===================================================================
 */
// Output Jade Files to build "index.html" & send it to "build/"
gulp.task("jade", function () {
  return gulp.src("jade/index.jade")
  .pipe(jade({
    pretty: true
  }))
  .pipe(gulp.dest("build"));
});

/*
 *  ===================================================================
 *  | CSS BUILD TASK |
 *
 * Running "gulp buildcss" performs the following sequence of tasks...
 *
 * 1. Runs the "gulp less" task that"s passed as a "hint"(*)
 * 2. Concatenate selected .css files listed in "gulp.src"
 * 3. Remove unused CSS
 * 4. Minify CSS
 * 5. Lint CSS
 *
 * (*) gulp "hints" are cool...read more about them at:
 * https://github.com/gulpjs/gulp/blob/master/docs/API.md
 *  ===================================================================
 */
gulp.task("buildcss", ['less'],function () {
  gulp.src(['css-build/bootstrap.css', 'css-build/styles.css'])
  .pipe(concatCss("styles.min.css"))
  .pipe(uncss({
    html: ["build/index.html"],
    ignore: ignoreArray
  })).pipe(minifyCSS({
    keepBreaks: true
  })).pipe(gulp.dest("build/css/"))
  .pipe(csslint({
    "important": false,
    "duplicate-background-images": false,
    "ids": false,
    "text-indent": false
  }))
  .pipe(csslint.reporter());
});

/*
*  ===================================================================
*  | IMAGE MINIFICATION TASK |
*
*  Take all images in "imagemin/" & minify them out to "build/img/"
*  ===================================================================
*/
gulp.task('images', function () {
  return gulp.src('imagemin/*')
  .pipe(imagemin({
    progressive: true,
    svgoPlugins: [{removeViewBox: false}]
  }))
  .pipe(gulp.dest('build/img'));
});

/*
 *  ===================================================================
 *  | "gulp-grunt" TASKS...RUN GRUNT TASKS VIA GULP!!!! |
 *  ===================================================================
 */
// Run the "grunt less" task
gulp.task("less", function () {
  gulp.run("grunt-shell");
});

// Run the "grunt jsonlint" task
gulp.task("jsonlint", function () {
  gulp.run("grunt-jsonlint");
});

// Run the "grunt coffee" task
gulp.task("coffee", function () {
  gulp.run("grunt-coffee");
});

// BOWERCOPY TASKS
// Copy over ALL the Bower Components!!!
gulp.task("bowercopy", function () {
  gulp.run("grunt-bowercopy");
});

// Copy over Bootstrap core .css only
gulp.task("bowerbscss", function () {
  gulp.run("grunt-bowercopy:bscss");
});

// Copy over jQuery Cycle2 plugin only
gulp.task("bowercycle", function () {
  gulp.run("grunt-bowercopy:cycle2");
});

// Copy over jQuery v.1.11.1 only
gulp.task("bowerjq", function () {
  gulp.run("grunt-bowercopy:jq");
});

/*
 *  ===================================================================
 *  | START WATCH TASK |
 *
 *  Be careful of watching a lot of files because that may eat up
 *  computer memory...at least, it does in Grunt.
 *  ===================================================================
 */
gulp.task("watch", function () {

  /*
   * If either preprocesser files or "build/" files change and the site
   * is currently running in the browser, refresh it in the browser via
   * livereload.
   */
  var server = livereload();
  gulp.watch(jadeFiles, ["jade"]);
  gulp.watch(lessFiles, ["buildcss"]);
  gulp.watch(coffeeFiles, ["coffee"]);
  gulp.watch(jsonFile, ["jsonlint"]);
  gulp.watch(["build/index.html", "build/css/*.css", "build/js/*.js", "build/js/*.json"],
  function (e) {
    server.changed(e.path);
  });
});
<commit_msg>list autoprefixer & clean up comments in gulpfile.js<commit_after>// Single var pattern of gulp (require) stuff in full effect!!!

var gulp = require("gulp"), // "require" gulp
    jade = require("gulp-jade"), // Jade task
    uncss = require("gulp-uncss"), // Remove unused css selectors
    minifyCSS = require("gulp-minify-css"), // Minify CSS
    concatCss = require("gulp-concat-css"), // Concatenate CSS only
    csslint = require("gulp-csslint"), // Lint CSS
    concat = require("gulp-concat"), // Concatenating stuff(?)
    watch = require("gulp-watch"), // Watch files changes
    imagemin = require('gulp-imagemin'), // Minifying images
    autoprefixer = require('gulp-autoprefixer'); // Add vendor prefixes

    // Live Reload stuff
    livereload = require("gulp-livereload"),
    lr = require("tiny-lr"),
    server = lr();

// End single var pattern

// Needed to run grunt tasks through gulp
require("gulp-grunt")(gulp);

/*
 *  ===================================================================
 *  | STORE PREPROCESSOR FILE REFERENCES IN VARIABLES |
 *  ===================================================================
 */
var jadeFiles = ["jade/index.jade", "jade/**/*.jade"], // Jade
    lessFiles = ["css-build/*.less", "css-build/**/*.less"], // LESS
    coffeeFiles = ["coffee/*.coffee"], // Coffeescript
    jsonFile = "build/js/playersInfo.json", // JSON files
    ignoreArray = [
                    ".cycle-slide"
                  ];

    /*
     * IGNORE ARRAY
     * ============
     * Selectors NOT to be removed when "gulp uncss" task runs.
     * Try to list them alphabetically and in the following order:
     *
     * 1. Page elements first (<nav>, <aside>, etc.)
     * 2. IDs second
     * 3. Classes third
     */
     ignoreArray = [
     "img.cycle-slide"
     ];

/*
 *  ===================================================================
 *  | JADE TASK |
 *  ===================================================================
 */
// Output Jade Files to build "index.html" & send it to "build/"
gulp.task("jade", function () {
  return gulp.src("jade/index.jade")
  .pipe(jade({
    pretty: true
  }))
  .pipe(gulp.dest("build"));
});

/*
 *  ===================================================================
 *  | CSS BUILD TASK |
 *
 * Running "gulp buildcss" performs the following sequence of tasks...
 *
 * 1. Runs the "gulp less" task that"s passed as a "hint"(*)
 * 2. Concatenate selected .css files listed in "gulp.src"
 * 3. Remove unused CSS
 * 4. Minify CSS
 * 5. Lint CSS
 *
 * (*) gulp "hints" are cool...read more about them at:
 * https://github.com/gulpjs/gulp/blob/master/docs/API.md
 *  ===================================================================
 */
gulp.task("buildcss", ['less'],function () {
  gulp.src(['css-build/bootstrap.css', 'css-build/styles.css'])
  .pipe(concatCss("styles.min.css"))
  .pipe(uncss({
    html: ["build/index.html"],
    ignore: ignoreArray
  })).pipe(minifyCSS({
    keepBreaks: true
  })).pipe(gulp.dest("build/css/"))
  .pipe(csslint({
    "important": false,
    "duplicate-background-images": false,
    "ids": false,
    "text-indent": false
  }))
  .pipe(csslint.reporter());
});

/*
*  ===================================================================
*  | IMAGE MINIFICATION TASK |
*
*  Take all images in "imagemin/" & minify them out to "build/img/"
*  ===================================================================
*/
gulp.task('images', function () {
  return gulp.src('imagemin/*')
  .pipe(imagemin({
    progressive: true,
    svgoPlugins: [{removeViewBox: false}]
  }))
  .pipe(gulp.dest('build/img'));
});

/*
 *  ===================================================================
 *  | "gulp-grunt" TASKS...RUN GRUNT TASKS VIA GULP!!!! |
 *  ===================================================================
 */
// Run the "grunt less" task
gulp.task("less", function () {
  gulp.run("grunt-shell");
});

// Run the "grunt jsonlint" task
gulp.task("jsonlint", function () {
  gulp.run("grunt-jsonlint");
});

// Run the "grunt coffee" task
gulp.task("coffee", function () {
  gulp.run("grunt-coffee");
});

// BOWERCOPY TASKS
// Copy over ALL the Bower Components!!!
gulp.task("bowercopy", function () {
  gulp.run("grunt-bowercopy");
});

// Copy over Bootstrap core .css only
gulp.task("bowerbscss", function () {
  gulp.run("grunt-bowercopy:bscss");
});

// Copy over jQuery Cycle2 plugin only
gulp.task("bowercycle", function () {
  gulp.run("grunt-bowercopy:cycle2");
});

// Copy over jQuery v.1.11.1 only
gulp.task("bowerjq", function () {
  gulp.run("grunt-bowercopy:jq");
});

/*
 *  ===================================================================
 *  | START WATCH TASK |
 *
 *  Be careful of watching a lot of files because that may eat up
 *  computer memory...at least, it does in Grunt.
 *  ===================================================================
 */
gulp.task("watch", function () {

  /*
   * If either preprocesser files or "build/" files change and the site
   * is currently running in the browser, refresh it in the browser via
   * livereload.
   */
  var server = livereload();
  gulp.watch(jadeFiles, ["jade"]);
  gulp.watch(lessFiles, ["buildcss"]);
  gulp.watch(coffeeFiles, ["coffee"]);
  gulp.watch(jsonFile, ["jsonlint"]);
  gulp.watch(["build/index.html", "build/css/*.css", "build/js/*.js", "build/js/*.json"],
  function (e) {
    server.changed(e.path);
  });
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var gulpIf = require('gulp-if');
var browserSync = require('browser-sync');
var size = require('gulp-size');

var reload = browserSync.reload;

gulp.task('jshint', function() {
  var jshint = require('gulp-jshint');

  return gulp.src(['txlege84/static/scripts/**/*.js', '!txlege84/static/scripts/jquery/{,/**}', '!txlege84/static/scripts/slick/{,/**}'])
    .pipe(reload({stream: true, once: true}))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpIf(!browserSync.active, jshint.reporter('fail')));
});

// gulp.task('images', function() {
//   var cache = require('gulp-cache');
//   var imagemin = require('gulp-imagemin');

//   return gulp.src('source/images/**/*')
//     .pipe(cache(imagemin({
//       progressive: true,
//       interlaced: true
//     })))
//     .pipe(gulp.dest('build/images'))
//     .pipe(size({title: 'images'}));
// });

gulp.task('styles', function() {
  var autoprefixer = require('gulp-autoprefixer');
  var changed = require('gulp-changed');
  var csso = require('gulp-csso');
  var sass = require('gulp-ruby-sass');

  return gulp.src('txlege84/static/scss/*.scss')
    .pipe(changed('styles', {
      extension: '.scss'
    }))
    .pipe(sass({
      loadPath: 'bower_components',
      precision: 10,
      style: 'expanded',
      // this is nasty, but currently broken otherwise
      // https://github.com/sindresorhus/gulp-autoprefixer/issues/20
      'sourcemap=none': true
    }))
    .on('error', console.error.bind(console))
    .pipe(autoprefixer({
      browsers: ['last 2 versions', 'IE 9'],
      cascade: false
    }))
    .pipe(gulpIf('*.css', csso()))
    .pipe(gulp.dest('txlege84/static/css'))
    .pipe(size({title: 'styles'}));
});

gulp.task('clean', function() {
  var del = require('del');

  del(['txlege84/static/css/*.css']);
});

gulp.task('serve', ['styles'], function() {
  browserSync({
    notify: false,
    logPrefix: 'NEWSAPPS',
    open: false,
    proxy: 'localhost:8000'
  });

  gulp.watch(['txlege84/templates/**/*.html'], reload);
  gulp.watch(['txlege84/static/scss/**/*.scss'], ['styles', reload]);
  gulp.watch(['txlege84/static/scripts/**/*.js'], ['jshint']);
});

gulp.task('serve:build', ['default'], function() {
  browserSync({
    notify: false,
    logPrefix: 'NEWSAPPS',
    open: true,
    proxy: 'localhost:8000'
  });
});

gulp.task('default', ['clean'], function(cb) {
  var runSequence = require('run-sequence');

  runSequence(['styles'], ['jshint'], cb);
});

gulp.task('build', ['default']);
<commit_msg>Ignore jshint for the libs folder<commit_after>'use strict';

var gulp = require('gulp');
var gulpIf = require('gulp-if');
var browserSync = require('browser-sync');
var size = require('gulp-size');

var reload = browserSync.reload;

gulp.task('jshint', function() {
  var jshint = require('gulp-jshint');

  return gulp.src(['txlege84/static/scripts/**/*.js', '!txlege84/static/scripts/jquery/{,/**}', '!txlege84/static/scripts/slick/{,/**}', '!txlege84/static/scripts/libs/{,/**}'])
    .pipe(reload({stream: true, once: true}))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpIf(!browserSync.active, jshint.reporter('fail')));
});

// gulp.task('images', function() {
//   var cache = require('gulp-cache');
//   var imagemin = require('gulp-imagemin');

//   return gulp.src('source/images/**/*')
//     .pipe(cache(imagemin({
//       progressive: true,
//       interlaced: true
//     })))
//     .pipe(gulp.dest('build/images'))
//     .pipe(size({title: 'images'}));
// });

gulp.task('styles', function() {
  var autoprefixer = require('gulp-autoprefixer');
  var changed = require('gulp-changed');
  var csso = require('gulp-csso');
  var sass = require('gulp-ruby-sass');

  return gulp.src('txlege84/static/scss/*.scss')
    .pipe(changed('styles', {
      extension: '.scss'
    }))
    .pipe(sass({
      loadPath: 'bower_components',
      precision: 10,
      style: 'expanded',
      // this is nasty, but currently broken otherwise
      // https://github.com/sindresorhus/gulp-autoprefixer/issues/20
      'sourcemap=none': true
    }))
    .on('error', console.error.bind(console))
    .pipe(autoprefixer({
      browsers: ['last 2 versions', 'IE 9'],
      cascade: false
    }))
    .pipe(gulpIf('*.css', csso()))
    .pipe(gulp.dest('txlege84/static/css'))
    .pipe(size({title: 'styles'}));
});

gulp.task('clean', function() {
  var del = require('del');

  del(['txlege84/static/css/*.css']);
});

gulp.task('serve', ['styles'], function() {
  browserSync({
    notify: false,
    logPrefix: 'NEWSAPPS',
    open: false,
    proxy: 'localhost:8000'
  });

  gulp.watch(['txlege84/templates/**/*.html'], reload);
  gulp.watch(['txlege84/static/scss/**/*.scss'], ['styles', reload]);
  gulp.watch(['txlege84/static/scripts/**/*.js'], ['jshint']);
});

gulp.task('serve:build', ['default'], function() {
  browserSync({
    notify: false,
    logPrefix: 'NEWSAPPS',
    open: true,
    proxy: 'localhost:8000'
  });
});

gulp.task('default', ['clean'], function(cb) {
  var runSequence = require('run-sequence');

  runSequence(['styles'], ['jshint'], cb);
});

gulp.task('build', ['default']);
<|endoftext|>


<commit_before>var gulp   = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('default', function() {
    return gulp.src('bootstrap-hover-dropdown.js')

        // minifiy preserving preserved comments
        .pipe(uglify({
            preserveComments: 'some'
        }))

        // rename to .min.
        .pipe(rename('bootstrap-hover-dropdown.min.js'))

        .pipe(gulp.dest('.'));
});

var fs         = require('fs');
var bump       = require('gulp-bump');
var filter     = require('gulp-filter');
var git        = require('gulp-git');
var tagVersion = require('gulp-tag-version');
var replace    = require('gulp-replace');

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */
function increment(importance) {
    var currentVersion = JSON.parse(fs.readFileSync('bower.json')).version;

    // get all the files to bump version in
    gulp.src(['package.json', 'bower.json', 'composer.json'])
        // bump the version number in those files
        .pipe(bump({ type: importance }))

        // save it back to filesystem
        .pipe(gulp.dest('.'))

        // // commit the changed version number
        // .pipe(git.commit('bump packages\' version'))

        // // read only one file to get the version number
        // .pipe(filter('bower.json'))

        // // **tag it in the repository**
        // .pipe(tagVersion())

        .on('end', function () {
            var newVersion = JSON.parse(fs.readFileSync('bower.json')).version;

            gulp.src(['bootstrap-hover-dropdown.js', 'bootstrap-hover-dropdown.min.js'])
                // replace version # in the JS files
                .pipe(replace('Version: v' + currentVersion, 'Version: v' + newVersion))
                .pipe(gulp.dest('.'));
        });
}

gulp.task('patch',   ['default'], function() { return increment('patch'); });
gulp.task('feature', ['default'], function() { return increment('minor'); });
gulp.task('release', ['default'], function() { return increment('major'); });
<commit_msg>Uncomment stuff in gulp that I didn't mean to leave commented.<commit_after>var gulp   = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

gulp.task('default', function() {
    return gulp.src('bootstrap-hover-dropdown.js')

        // minifiy preserving preserved comments
        .pipe(uglify({
            preserveComments: 'some'
        }))

        // rename to .min.
        .pipe(rename('bootstrap-hover-dropdown.min.js'))

        .pipe(gulp.dest('.'));
});

var fs         = require('fs');
var bump       = require('gulp-bump');
var filter     = require('gulp-filter');
var git        = require('gulp-git');
var tagVersion = require('gulp-tag-version');
var replace    = require('gulp-replace');

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */
function increment(importance) {
    var currentVersion = JSON.parse(fs.readFileSync('bower.json')).version;

    // get all the files to bump version in
    gulp.src(['package.json', 'bower.json', 'composer.json'])
        // bump the version number in those files
        .pipe(bump({ type: importance }))

        // save it back to filesystem
        .pipe(gulp.dest('.'))

        // commit the changed version number
        .pipe(git.commit('bump packages\' version'))

        // read only one file to get the version number
        .pipe(filter('bower.json'))

        // **tag it in the repository**
        .pipe(tagVersion())

        .on('end', function () {
            var newVersion = JSON.parse(fs.readFileSync('bower.json')).version;

            gulp.src(['bootstrap-hover-dropdown.js', 'bootstrap-hover-dropdown.min.js'])
                // replace version # in the JS files
                .pipe(replace('Version: v' + currentVersion, 'Version: v' + newVersion))
                .pipe(gulp.dest('.'));
        });
}

gulp.task('patch',   ['default'], function() { return increment('patch'); });
gulp.task('feature', ['default'], function() { return increment('minor'); });
gulp.task('release', ['default'], function() { return increment('major'); });
<|endoftext|>


<commit_before>var gulp   = require('gulp')
  , uglify = require('gulp-uglify')
  , rename = require('gulp-rename')
  , jshint = require('gulp-jshint')
  , jscs   = require('gulp-jscs')
  , mocha  = require('gulp-mocha')
  , stylish = require('jshint-stylish');

/**
 * LINT
 * Ensures that the library code obeys hinting and
 * style guide rules.
 */
gulp.task('lint', function () {
  return gulp.src('./**/*.js')
    .pipe(jscs())
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

/**
 * TEST
 * Run tests on file change.
 */
gulp.task('test', function () {
  return gulp.src('./test/**/*.js', {read: false})
    .pipe(mocha({
      timeout: 5000
    }));
});

/**
 * BUILD
 * Minifies the portals.js file.
 */
gulp.task('build', function () {
  return gulp.src('./portals.js')
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./'));
});

/**
 * WATCH
 * Watches for file changes.
 */
gulp.task('watch', ['build'], function () {
  gulp.watch('./**/*.js', ['lint']);
  gulp.watch('./portals.js', ['compile']);
});

/**
 * DEFAULT
 */
gulp.task('default', ['watch']);
<commit_msg>Forgot to limit linting targets in order to avoid linting node_modules<commit_after>var gulp   = require('gulp')
  , uglify = require('gulp-uglify')
  , rename = require('gulp-rename')
  , jshint = require('gulp-jshint')
  , jscs   = require('gulp-jscs')
  , mocha  = require('gulp-mocha')
  , stylish = require('jshint-stylish');

/**
 * LINT
 * Ensures that the library code obeys hinting and
 * style guide rules.
 */
gulp.task('lint', function () {
  return gulp.src(['./portals.js', './test/**/*.js'])
    .pipe(jscs())
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

/**
 * TEST
 * Run tests on file change.
 */
gulp.task('test', function () {
  return gulp.src('./test/**/*.js', {read: false})
    .pipe(mocha({
      timeout: 5000
    }));
});

/**
 * BUILD
 * Minifies the portals.js file.
 */
gulp.task('build', function () {
  return gulp.src('./portals.js')
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./'));
});

/**
 * WATCH
 * Watches for file changes.
 */
gulp.task('watch', ['build'], function () {
  gulp.watch(['./portals.js', './test/**/*.js'], ['lint']);
  gulp.watch('./portals.js', ['compile']);
});

/**
 * DEFAULT
 */
gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>require('postcss-neat/es6-reg');

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    postcss = require('gulp-postcss'),
    cssmin = require('gulp-cssmin'),
    replace = require('gulp-replace'),
    cssnext = require("gulp-cssnext"),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    notify = require('gulp-notify')

// compile CSS
  gulp.task('styles', function() {
    return gulp.src('src/css/style.css')
      .pipe(postcss([
        // require('postcss-simple-vars'),
        require('postcss-import')({path: ['bower_components'], from: 'src/css/style.css'}),
        require('postcss-mixins')({mixins: require('postcss-neat')()}),
        require('postcss-nested')
      ]))
      .pipe(cssnext()) // Autoprefixer is included in cssnext
      .pipe(cssmin())
      .pipe(gulp.dest('build/css/'))
      .pipe(notify({ message: 'Styles task complete' }))
  });

// compile HTML
  gulp.task('minify', function() {
    return gulp.src('src/**/*.php')
      .pipe(gulp.dest('build'))
      .pipe(notify({ message: 'HTML compile finished' }))
  });

// Images
  gulp.task('images', function() {
    return gulp.src('src/img/**/*')
      .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
      .pipe(gulp.dest('build/img'))
      .pipe(notify({ message: 'Images task complete' }));
  });

// Compile scripts
  gulp.task('scripts', function() {
    return gulp.src([
      'bower_components/**/*.min.js',
      'src/js/scripts.js'])
      .pipe(concat('scripts.min.js'))
      .pipe(gulp.dest('build/js'))
      .pipe(notify({ message: 'Javascript compiled' }));
  });

// Replace
  gulp.task('replace', ['minify'], function(){

  });
// Watch
  gulp.task('watch', function() {

    // Watch .scss files
    gulp.watch('src/css/**/*.css', ['styles']);

    //Watch .js files
    gulp.watch('src/js/**/*.js', ['scripts']);

    // Watch image files
    gulp.watch('src/img/**/*', ['images']);

    // Watch php files
    gulp.watch('src/*.php', ['replace']);

    // Create LiveReload server
    // livereload.listen();

    // Watch any files in build/, reload on change
    // gulp.watch(['/']).on('change', livereload.changed);

  });
 // Build project
  gulp.task('build', [
    'styles',
    'minify',
    'scripts',
    'images'
  ]);<commit_msg>Remove unused lines<commit_after>require('postcss-neat/es6-reg');

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    postcss = require('gulp-postcss'),
    cssmin = require('gulp-cssmin'),
    replace = require('gulp-replace'),
    cssnext = require("gulp-cssnext"),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    notify = require('gulp-notify')

// compile CSS
  gulp.task('styles', function() {
    return gulp.src('src/css/style.css')
      .pipe(postcss([
        require('postcss-import')({path: ['bower_components'], from: 'src/css/style.css'}),
        require('postcss-mixins')({mixins: require('postcss-neat')()}),
        require('postcss-nested')
      ]))
      .pipe(cssnext()) // Autoprefixer is included in cssnext
      .pipe(cssmin())
      .pipe(gulp.dest('build/css/'))
      .pipe(notify({ message: 'Styles task complete' }))
  });

// compile HTML
  gulp.task('minify', function() {
    return gulp.src('src/**/*.php')
      .pipe(gulp.dest('build'))
      .pipe(notify({ message: 'HTML compile finished' }))
  });

// Images
  gulp.task('images', function() {
    return gulp.src('src/img/**/*')
      .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
      .pipe(gulp.dest('build/img'))
      .pipe(notify({ message: 'Images task complete' }));
  });

// Compile scripts
  gulp.task('scripts', function() {
    return gulp.src([
      'bower_components/**/*.min.js',
      'src/js/scripts.js'])
      .pipe(concat('scripts.min.js'))
      .pipe(gulp.dest('build/js'))
      .pipe(notify({ message: 'Javascript compiled' }));
  });

// Replace
  gulp.task('replace', ['minify'], function(){

  });
// Watch
  gulp.task('watch', function() {

    // Watch .scss files
    gulp.watch('src/css/**/*.css', ['styles']);

    //Watch .js files
    gulp.watch('src/js/**/*.js', ['scripts']);

    // Watch image files
    gulp.watch('src/img/**/*', ['images']);

    // Watch php files
    gulp.watch('src/*.php', ['replace']);

    // Create LiveReload server
    // livereload.listen();

    // Watch any files in build/, reload on change
    // gulp.watch(['/']).on('change', livereload.changed);

  });
 // Build project
  gulp.task('build', [
    'styles',
    'minify',
    'scripts',
    'images'
  ]);<|endoftext|>