<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');

var taskListing = require('gulp-task-listing');

var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

var through = require('through2');

var zip = require('gulp-zip');

var git = require('gulp-git');
var bump = require('gulp-bump');
var tag_version = require('gulp-tag-version');

var ncp = require('ncp').ncp;
var del = require('del');
var mkdirp = require('mkdirp');

var yargs = require('yargs');
var runSequence = require('run-sequence');

gulp.task('lint', function() {
	return gulp.src('extension/js/*.js')
		.pipe(jshint())
		.pipe(jshint.reporter(stylish))
		.pipe(jshint.reporter('fail'));
});

gulp.task('package', ['copy', 'clean'], function() {
		return gulp.src('dist/build/**')
			.pipe(zip('extension.zip'))
			.pipe(gulp.dest('dist'))
});

gulp.task('copy', ['clean'], function(cb) {
	console.log('Packaging the extension to the dist folder');

	mkdirp('dist/build', function (mkdirErr) {
		ncp('extension', 'dist/build', function (copyErr) {
			if (mkdirErr || copyErr) return console.error("Unable to copy extension folder", mkdirErr, copyErr);
			cb();
		});
	});
});

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

gulp.task('bump', function () {
	var importance = yargs.argv.ver;
	const possibleImportances = ['patch', 'minor', 'major'];

	if (!importance || possibleImportances.indexOf(importance) == -1) {
		var defaultImportance = possibleImportances[0];
		console.log('No or invalid version type provided. Using ' + defaultImportance + '. To specify your own, specify --ver=[' + possibleImportances.join('|') + ']');
		importance = defaultImportance;
	}

	return inc(importance);
});

gulp.task('release', function (callback) {
	runSequence('lint', 'bump', 'copy', 'permissions', 'package', function () {
		console.log('Done releasing! Nothing has been pushed to Github, so please review the release manually and push or rollback. Remember to delete the tag if you want to roll back the release.');
		if (typeof callback == 'function') callback.apply(this, arguments);
	});
});

gulp.task('permissions', function () {
	return gulp.src('dist/build/manifest.json')
		.pipe(manifest_urls({
				permission_urls: ['https://www.digipost.no/*', 'https://www.digipostdata.no/*'],
				content_script_urls: ['https://www.digipost.no/*']
			}))
		.pipe(gulp.dest('dist/build'));
});

gulp.task('default', taskListing);

function inc(importance) {
	return gulp.src(['extension/manifest.json'])
		// Bump version numbers in files with version
		.pipe(bump({type: importance}))
		.pipe(gulp.dest('./extension'))
		.pipe(git.commit('Released new version'))
		.pipe(tag_version());
}

/**
 * Overrides permission and matching URLs in manifest files to avoid publishing version with development URLs.
 */
function manifest_urls(options) {
	return through.obj(function (file, enc, cb) {
		var manifestJson = JSON.parse(file.contents.toString());

		manifestJson.permissions = manifestJson.permissions.filter(removeUrls).concat(options.permission_urls);

		if (manifestJson.content_scripts.length != 1) {
			return cb(new gutil.PluginError('gulpfile.js', 'We only support exactly one content script block.', {
				fileName: file.path,
				showStack: true
			}));
		}
		manifestJson.content_scripts[0].matches = manifestJson.content_scripts[0].matches.filter(removeUrls).concat(options.content_script_urls);

		file.contents = new Buffer(JSON.stringify(manifestJson, null, '  ') + '\n');

		gutil.log('Set permission URLs to  ' + gutil.colors.cyan(options.permission_urls.join(', ')) + ' and content script URLs to ' + gutil.colors.cyan(options.content_script_urls.join(', ')));
		return cb(null, file);
	});

	function removeUrls(item) {
		return item.indexOf('http://') == -1 && item.indexOf('https://') == -1
	}

}
<commit_msg>Don't depend on clean for multiple other tasks, as it must be run on a very specific point in the build to prevent cleaning the output from earlier tasks<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');

var taskListing = require('gulp-task-listing');

var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

var through = require('through2');

var zip = require('gulp-zip');

var git = require('gulp-git');
var bump = require('gulp-bump');
var tag_version = require('gulp-tag-version');

var ncp = require('ncp').ncp;
var del = require('del');
var mkdirp = require('mkdirp');

var yargs = require('yargs');
var runSequence = require('run-sequence');

gulp.task('lint', function() {
	return gulp.src('extension/js/*.js')
		.pipe(jshint())
		.pipe(jshint.reporter(stylish))
		.pipe(jshint.reporter('fail'));
});

gulp.task('package', function() {
		return gulp.src('dist/build/**')
			.pipe(zip('extension.zip'))
			.pipe(gulp.dest('dist'))
});

gulp.task('copy', function(cb) {
	console.log('Packaging the extension to the dist folder');

	mkdirp('dist/build', function (mkdirErr) {
		ncp('extension', 'dist/build', function (copyErr) {
			if (mkdirErr || copyErr) return console.error("Unable to copy extension folder", mkdirErr, copyErr);
			cb();
		});
	});
});

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

gulp.task('bump', function () {
	var importance = yargs.argv.ver;
	const possibleImportances = ['patch', 'minor', 'major'];

	if (!importance || possibleImportances.indexOf(importance) == -1) {
		var defaultImportance = possibleImportances[0];
		console.log('No or invalid version type provided. Using ' + defaultImportance + '. To specify your own, specify --ver=[' + possibleImportances.join('|') + ']');
		importance = defaultImportance;
	}

	return inc(importance);
});

gulp.task('release', function (callback) {
	runSequence('lint', 'bump', 'clean', 'copy', 'permissions', 'package', function () {
		console.log('Done releasing! Nothing has been pushed to Github, so please review the release manually and push or rollback. Remember to delete the tag if you want to roll back the release.');
		if (typeof callback == 'function') callback.apply(this, arguments);
	});
});

gulp.task('permissions', function () {
	return gulp.src('dist/build/manifest.json')
		.pipe(manifest_urls({
				permission_urls: ['https://www.digipost.no/*', 'https://www.digipostdata.no/*'],
				content_script_urls: ['https://www.digipost.no/*']
			}))
		.pipe(gulp.dest('dist/build'));
});

gulp.task('default', taskListing);

function inc(importance) {
	return gulp.src(['extension/manifest.json'])
		// Bump version numbers in files with version
		.pipe(bump({type: importance}))
		.pipe(gulp.dest('./extension'))
		.pipe(git.commit('Released new version'))
		.pipe(tag_version());
}

/**
 * Overrides permission and matching URLs in manifest files to avoid publishing version with development URLs.
 */
function manifest_urls(options) {
	return through.obj(function (file, enc, cb) {
		var manifestJson = JSON.parse(file.contents.toString());

		manifestJson.permissions = manifestJson.permissions.filter(removeUrls).concat(options.permission_urls);

		if (manifestJson.content_scripts.length != 1) {
			return cb(new gutil.PluginError('gulpfile.js', 'We only support exactly one content script block.', {
				fileName: file.path,
				showStack: true
			}));
		}
		manifestJson.content_scripts[0].matches = manifestJson.content_scripts[0].matches.filter(removeUrls).concat(options.content_script_urls);

		file.contents = new Buffer(JSON.stringify(manifestJson, null, '  ') + '\n');

		gutil.log('Set permission URLs to  ' + gutil.colors.cyan(options.permission_urls.join(', ')) + ' and content script URLs to ' + gutil.colors.cyan(options.content_script_urls.join(', ')));
		return cb(null, file);
	});

	function removeUrls(item) {
		return item.indexOf('http://') == -1 && item.indexOf('https://') == -1
	}

}
<|endoftext|>


<commit_before>// ==[ Dependencies ]======================================
var gulp = require('gulp'),
    _ = require('underscore'),
    less = require('gulp-less'),
    path = require('path'),
    template = require('gulp-template'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    sourcemaps = require('gulp-sourcemaps'),
    vulcanize = require('gulp-vulcanize'),
    webserver = require('gulp-webserver'),
    config = require('./app/config.json'),
    pkg = require('./package.json'),
    yargs = require('yargs'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    del = require('del');

_.str = require('underscore.string');
// ========================================================

// ==[ Error Handling ]====================================
// `gulp --fatal=error` determines what kind of errors should be fatal
// - see for more info: http://www.artandlogic.com/blog/2014/05/error-handling-in-gulp/
// - more examples: http://truongtx.me/2014/07/15/handle-errors-while-using-gulp-watch/

var fatalLevel = yargs.argv.fatal,
    ERROR_LEVELS = ['error', 'warning'];

function isFatal(level) {
  return ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel || 'error');
}

function handleError(level, error) {
  notify.onError({
    title: "Gulp",
    subtitle: level + "!",
    message: "Error: <%= error.message %>",
    sound: "Sosumi"
  })(error);

  gutil.log(error.message);
  gutil.log(error.stack);

  if (isFatal(level)) {
    process.exit(1);
  }

  this.emit('end');
}

function onError(error) {
  handleError.call(this, 'error', error);
}
function onWarning(error) {
  handleError.call(this, 'warning', error);
}

// ========================================================

//TODO: fix path problems in components/build.html (wtf google-code-prettify, marked.js, context-free-parser.js)
//TODO: stream jshint task into js task
//TODO: common piped task for multi-env configuration?
//TODO: generate for multiple environments simultaneously? (multiple output folders)
//TODO: FIX LiveReload
//TODO: setup basic angular app with templates
//TODO: gulp rss?
//TODO: sitemap?
//TODO: asset fingerprinting?
//TODO: jshintrc - look at https://gist.github.com/connor/1597131
//TODO: add 404.html and other templates
//TODO: ensure Polymer.js and Platform.js are included in components/build.html
//TODO: address Angular/Polymer SEO

//gulp-notify defaults for completed tasks
//  official config examples: https://github.com/mikaelbr/gulp-notify/blob/master/examples/gulpfile.js
var notifyConf = {
  title: "Gulp",
  subtitle: "Finished",
  sound: "Tink" // refer to OSX Sound Preferences
};

//merge env config into common config
var node_env = process.env.NODE_ENV || 'development',
    conf = _.extend(
        _.pick(pkg, 'title', 'description'),
        config['common'],
        config[node_env],
        { ustr: _.str } // makes underscore.str available in templates
    );

gulp.task('html', function () {
  return gulp.src('app/pages/**/*.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(template(conf))
      .pipe(gulp.dest('dist'))
      .pipe(notify(_.extend(notifyConf,{message: 'HTML task complete'})));
});

//TODO: update jshint & js tasks so that one streams into the other, for efficiency
gulp.task('jshint', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onWarning}))
      .pipe(template(conf))
      .pipe(jshint('.jshintrc'))
      .pipe(jshint.reporter('default'))
      .pipe(notify(_.extend(notifyConf,{message: 'JSHint task complete'})));
});

gulp.task('js', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(template(conf))
      .pipe(concat('app.js'))
      .pipe(gulp.dest('dist/js'))
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe(notify(_.extend(notifyConf,{message: 'JS task complete'})));
});

gulp.task('less', function () {
  return gulp.src('./app/css/**/*.less')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(less({
        paths: [path.join(__dirname, 'less', 'includes')]
      }))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('./dist/css'))
      .pipe(notify(_.extend(notifyConf,{message: 'LESS task complete'})));
});

gulp.task('img', function () {
  return gulp.src('app/img/**/*')
      .pipe(plumber({errorHandler: onError}))
      .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
      .pipe(gulp.dest('dist/img'))
      .pipe(notify(_.extend(notifyConf,{message: 'Img task complete'})));
});

gulp.task('vulcanize', function () {
  return gulp.src('app/components/build.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(vulcanize({
        // refer here for options: https://github.com/Polymer/grunt-vulcanize#options
        dest: 'dist/components',
        inline: true,
        csp: true
      }))
      .pipe(gulp.dest('dist/components'))
      .pipe(notify(_.extend(notifyConf,{message: 'Vulcanize task complete'})));
});

gulp.task('clean', function (cb) {
  del(['dist/css', 'dist/js', 'dist/img', 'dist/components', 'dist/index.html'], cb)
});

gulp.task('default', ['clean'], function () {
  gulp.start('html', 'less', 'jshint', 'js', 'img', 'vulcanize');
});

gulp.task('watch', function () {
  fatalLevel = fatalLevel || 'off';
  gulp.watch('app/config.json', ['js', 'html']);
  gulp.watch('app/css/**/*.less', ['less']);
  gulp.watch('app/js/**/*.js', ['jshint', 'js']);
  gulp.watch('app/img/**/*', ['img']);
  gulp.watch('app/pages/**/*.html', ['html']);
  gulp.watch('app/components/build.html', ['vulcanize']);
});

gulp.task('webserver', function () {
  gulp.src('dist')
      .pipe(webserver({
        livereload: true,
        directoryListing: {
          enable: true,
          path: 'dist'
        },
        port: 8000,
        //https: true,
        open: true
      }));
});<commit_msg>* vulcanize task: strip out whitespace and comments on production/staging builds<commit_after>// ==[ Dependencies ]======================================
var gulp = require('gulp'),
    _ = require('underscore'),
    less = require('gulp-less'),
    path = require('path'),
    template = require('gulp-template'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    sourcemaps = require('gulp-sourcemaps'),
    vulcanize = require('gulp-vulcanize'),
    webserver = require('gulp-webserver'),
    config = require('./app/config.json'),
    pkg = require('./package.json'),
    yargs = require('yargs'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    del = require('del');

_.str = require('underscore.string');
// ========================================================

// ==[ Error Handling ]====================================
// `gulp --fatal=error` determines what kind of errors should be fatal
// - see for more info: http://www.artandlogic.com/blog/2014/05/error-handling-in-gulp/
// - more examples: http://truongtx.me/2014/07/15/handle-errors-while-using-gulp-watch/

var fatalLevel = yargs.argv.fatal,
    ERROR_LEVELS = ['error', 'warning'];

function isFatal(level) {
  return ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel || 'error');
}

function handleError(level, error) {
  notify.onError({
    title: "Gulp",
    subtitle: level + "!",
    message: "Error: <%= error.message %>",
    sound: "Sosumi"
  })(error);

  gutil.log(error.message);
  gutil.log(error.stack);

  if (isFatal(level)) {
    process.exit(1);
  }

  this.emit('end');
}

function onError(error) {
  handleError.call(this, 'error', error);
}
function onWarning(error) {
  handleError.call(this, 'warning', error);
}

// ========================================================

//TODO: fix path problems in components/build.html (wtf google-code-prettify, marked.js, context-free-parser.js)
//TODO: stream jshint task into js task
//TODO: common piped task for multi-env configuration?
//TODO: generate for multiple environments simultaneously? (multiple output folders)
//TODO: FIX LiveReload
//TODO: setup basic angular app with templates
//TODO: gulp rss?
//TODO: sitemap?
//TODO: asset fingerprinting?
//TODO: jshintrc - look at https://gist.github.com/connor/1597131
//TODO: add 404.html and other templates
//TODO: ensure Polymer.js and Platform.js are included in components/build.html
//TODO: address Angular/Polymer SEO

//gulp-notify defaults for completed tasks
//  official config examples: https://github.com/mikaelbr/gulp-notify/blob/master/examples/gulpfile.js
var notifyConf = {
  title: "Gulp",
  subtitle: "Finished",
  sound: "Tink" // refer to OSX Sound Preferences
};

//merge env config into common config
var node_env = process.env.NODE_ENV || 'development',
    conf = _.extend(
        _.pick(pkg, 'title', 'description'),
        config['common'],
        config[node_env],
        { ustr: _.str } // makes underscore.str available in templates
    );

gulp.task('html', function () {
  return gulp.src('app/pages/**/*.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(template(conf))
      .pipe(gulp.dest('dist'))
      .pipe(notify(_.extend(notifyConf,{message: 'HTML task complete'})));
});

//TODO: update jshint & js tasks so that one streams into the other, for efficiency
gulp.task('jshint', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onWarning}))
      .pipe(template(conf))
      .pipe(jshint('.jshintrc'))
      .pipe(jshint.reporter('default'))
      .pipe(notify(_.extend(notifyConf,{message: 'JSHint task complete'})));
});

gulp.task('js', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(template(conf))
      .pipe(concat('app.js'))
      .pipe(gulp.dest('dist/js'))
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe(notify(_.extend(notifyConf,{message: 'JS task complete'})));
});

gulp.task('less', function () {
  return gulp.src('./app/css/**/*.less')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(less({
        paths: [path.join(__dirname, 'less', 'includes')]
      }))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('./dist/css'))
      .pipe(notify(_.extend(notifyConf,{message: 'LESS task complete'})));
});

gulp.task('img', function () {
  return gulp.src('app/img/**/*')
      .pipe(plumber({errorHandler: onError}))
      .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
      .pipe(gulp.dest('dist/img'))
      .pipe(notify(_.extend(notifyConf,{message: 'Img task complete'})));
});

gulp.task('vulcanize', function () {
  return gulp.src('app/components/build.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(vulcanize({
        // refer here for options: https://github.com/Polymer/grunt-vulcanize#options
        dest: 'dist/components',
        inline: true,
        csp: true,
        strip: (node_env === 'production' || node_env === 'staging')
      }))
      .pipe(gulp.dest('dist/components'))
      .pipe(notify(_.extend(notifyConf,{message: 'Vulcanize task complete'})));
});

gulp.task('clean', function (cb) {
  del(['dist/css', 'dist/js', 'dist/img', 'dist/components', 'dist/index.html'], cb)
});

gulp.task('default', ['clean'], function () {
  gulp.start('html', 'less', 'jshint', 'js', 'img', 'vulcanize');
});

gulp.task('watch', function () {
  fatalLevel = fatalLevel || 'off';
  gulp.watch('app/config.json', ['js', 'html']);
  gulp.watch('app/css/**/*.less', ['less']);
  gulp.watch('app/js/**/*.js', ['jshint', 'js']);
  gulp.watch('app/img/**/*', ['img']);
  gulp.watch('app/pages/**/*.html', ['html']);
  gulp.watch('app/components/build.html', ['vulcanize']);
});

gulp.task('webserver', function () {
  gulp.src('dist')
      .pipe(webserver({
        livereload: true,
        directoryListing: {
          enable: true,
          path: 'dist'
        },
        port: 8000,
        //https: true,
        open: true
      }));
});<|endoftext|>


<commit_before>/**
 * Created by Kelvin on 8/4/2016.
 */
var gulp = require('gulp');
var del = require('del');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var ngAnnotate = require('gulp-ng-annotate');
var gulpif = require('gulp-if');
var revReplace = require('gulp-rev-replace');
var useref = require('gulp-useref');
var rev = require('gulp-rev');
var htmlmin = require('gulp-htmlmin');

// delete everything in the www folder
gulp.task('clean-dist', function () {
    return del([
        'dist/**/*'
    ]);
});

// copy over images, fonts and 3rd party css html
gulp.task('copy-files', function() {
    var imgs = gulp.src('app/images/**/*')
        .pipe(gulp.dest('dist/images'));

    // copy over css files
    var cssFiles = ['app/css/swipebox.css', 'app/css/style-v2.css', 'app/css/style-responsive-v2.css'];

    var css = gulp.src(cssFiles)
        .pipe(minifyCss())
        .pipe(gulp.dest('dist/css'));

    var preMinifiedCss = gulp.src('app/css/animate.min.css')
        .pipe(gulp.dest('dist/css'));

    var fonts = gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'));

    // copy over urip js files
    var minifiedJSArray = ['app/js/minified/SmoothScroll.min.js', 'app/js/minified/classie.min.js',
        'app/js/minified/jquery.nav.min.js', 'app/js/minified/jquery.swipebox.min.js', 'app/js/minified/expandableGallery.min.js',
        'app/js/minified/jquery.counterup.min.js', 'app/js/minified/jquery-css-transform.min.js',
        'app/js/minified/jquery-animate-css-rotate-scale.min.js', 'app/js/minified/jquery.quicksand.min.js',
        'app/js/minified/headhesive.min.js', 'app/js/minified/scrollReveal.min.js',
        'app/js/minified/jquery.countdown.min.js'];

    var preMinifiedJS = gulp.src(minifiedJSArray)
        .pipe(gulp.dest('dist/js/minified'));

    var jsFiles = gulp.src(['app/js/modernizr.js', 'app/js/v2.js', 'app/js/jquery.stellar.js'])
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));

    var templates = gulp.src('app/app/**/*.html')
        .pipe(htmlmin({removeComments: true, collapseWhitespace: true, conservativeCollapse: true}))
        .pipe(gulp.dest('dist/app'));

    return merge(imgs, css, preMinifiedCss,preMinifiedJS,jsFiles,templates, fonts);
});

gulp.task('build-html', function () {

    var condition = function(file) {
        var filesToRev = {
            'vendor.css': true,
            'app.js': true,
            'vendor.js': true,
            'app.css': true
        };
        return filesToRev[file.basename];
    };

    // concatenate, annotate, minify our vendor js files
    // concatenate, annotate, minify our js files
    return gulp.src("app/index.html")
        .pipe(useref())      // Concatenate with gulp-useref
        .pipe(gulpif('js/*.js',ngAnnotate()))
        .pipe(gulpif('js/*.js',uglify()))
        .pipe(gulpif('css/*.css', minifyCss())) // Minify vendor CSS sources
        .pipe(gulpif(condition, rev()))                // Rename the concatenated files
        .pipe(revReplace())         // Substitute in new filenames
        .pipe(htmlmin({removeComments: true}))
        .pipe(gulp.dest('dist'));
});

var imagemin = require('gulp-imagemin');

gulp.task('image-min', function() {
    return gulp.src('app/images/thumbnail-strip/*')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/images'));
});

gulp.task('build', function(callback) {
    runSequence('clean-dist',
        ['copy-files'],
        'build-html',
        callback);
});<commit_msg>build: fix parse errors with useref and copy ui-bootstrap<commit_after>/**
 * Created by Kelvin on 8/4/2016.
 */
var gulp = require('gulp');
var del = require('del');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var ngAnnotate = require('gulp-ng-annotate');
var gulpif = require('gulp-if');
var revReplace = require('gulp-rev-replace');
var useref = require('gulp-useref');
var rev = require('gulp-rev');
var htmlmin = require('gulp-htmlmin');

// delete everything in the www folder
gulp.task('clean-dist', function () {
    return del([
        'dist/**/*'
    ]);
});

// copy over images, fonts and 3rd party css html
gulp.task('copy-files', function() {
    var imgs = gulp.src('app/images/**/*')
        .pipe(gulp.dest('dist/images'));

    // copy over css files
    var cssFiles = ['app/css/swipebox.css', 'app/css/style-v2.css', 'app/css/style-responsive-v2.css'];

    var css = gulp.src(cssFiles)
        .pipe(minifyCss())
        .pipe(gulp.dest('dist/css'));

    var preMinifiedCss = gulp.src('app/css/animate.min.css')
        .pipe(gulp.dest('dist/css'));

    var fonts = gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'));

    // copy over urip js files
    var minifiedJSArray = ['app/js/minified/SmoothScroll.min.js', 'app/js/minified/classie.min.js',
        'app/js/minified/jquery.nav.min.js', 'app/js/minified/jquery.swipebox.min.js', 'app/js/minified/expandableGallery.min.js',
        'app/js/minified/jquery.counterup.min.js', 'app/js/minified/jquery-css-transform.min.js',
        'app/js/minified/jquery-animate-css-rotate-scale.min.js', 'app/js/minified/jquery.quicksand.min.js',
        'app/js/minified/headhesive.min.js', 'app/js/minified/scrollReveal.min.js',
        'app/js/minified/jquery.countdown.min.js'];

    var preMinifiedJS = gulp.src(minifiedJSArray)
        .pipe(gulp.dest('dist/js/minified'));

    var jsFiles = gulp.src(['app/js/modernizr.js', 'app/js/v2.js', 'app/js/jquery.stellar.js'])
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));

    var uiBootstrap = gulp.src('app/js/ui-bootstrap/ui-bootstrap-custom-tpls-2.0.1.min.js')
        .pipe(gulp.dest('dist/js/ui-bootstrap'));

    var templates = gulp.src('app/app/**/*.html')
        .pipe(htmlmin({removeComments: true, collapseWhitespace: true, conservativeCollapse: true}))
        .pipe(gulp.dest('dist/app'));

    return merge(imgs, css, preMinifiedCss,preMinifiedJS,jsFiles,templates, fonts);
});

gulp.task('build-html', function () {

    var condition = function(file) {
        var filesToRev = {
            'vendor.css': true,
            'app.js': true,
            'vendor.js': true,
            'app.css': true
        };
        return filesToRev[file.basename];
    };

    // concatenate, annotate, minify our vendor js files
    // concatenate, annotate, minify our js files
    return gulp.src("app/index.html")
        .pipe(useref())      // Concatenate with gulp-useref
        .pipe(gulpif('js/*.js',ngAnnotate()))
        .pipe(gulpif('js/*.js',uglify()))
        .pipe(gulpif('css/*.css', minifyCss())) // Minify vendor CSS sources
        .pipe(gulpif(condition, rev()))                // Rename the concatenated files
        .pipe(revReplace())         // Substitute in new filenames
        //.pipe(htmlmin({removeComments: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('minify-index-html', function() {
    return gulp.src('dist/index.html')
        .pipe(htmlmin({removeComments: true}))
        .pipe(gulp.dest('dist'));
});

gulp.task('build', function(callback) {
    runSequence('clean-dist',
        ['copy-files'],
        'build-html', 'minify-index-html',
        callback);
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')({
    lazy: true
});
var del = require('del');
var mainBowerFiles = require('main-bower-files');

var config = require('./gulp.config.js')();

/**
 * ----------------------------------------------------------------------------
 * Lazy Loaded Gulp Packages
 * ----------------------------------------------------------------------------
 *
 *      gulp-autoprefixer
 *      gulp-imagemin
 *      gulp-jscs
 *      gulp-jshint
 *      gulp-plumber
 *      gulp-task-listing
 *      gulp-util
 */

/**
 * ----------------------------------------------------------------------------
 * Tasks List
 * ----------------------------------------------------------------------------
 *
 *      gulp default        => Test, build and serve the project.
 *      gulp help           => Display the available tasks.
 *
 *      gulp clean          => Delete the dist folder.
 *      gulp build          => Build the project.
 *      gulp serve          => Serve the project in the browser.
 *
 *      gulp auto           => Run tests continuously.
 *      gulp test           => Run tests in single run mode.
 *
 *      gulp inject         => Inject JS and CSS assets into index.html.
 *                             then Copy to the dist. folder.
 *
 *      gulp lib            => Copy Bower dependencies to the dist. folder.
 *      gulp clean-lib      => Clean the distribued vendor JS & CSS files.
 *
 *      gulp vet            => Run jshint & jscs against all js code.
 *      gulp scripts        => Copy app JS files to the dist. folder.
 *      gulp-clean-scripts  => Clean the distribued JS files.
 *
 *      gulp styles         => Add vendor prefixes to CSS and copy to the dist. folder.
 *      gulp clean-styles   => Clean the distributed CSS files.
 *
 *      gulp images         => Optimize images and copy to the dist. folder.
 *      gulp clean-images   => Clean the distributed image files.
 *
 *      gulp-fonts          => Copy fonts to the dist. folder.
 *      gulp-clean-fonts    => Clean the distributed font files.
 *
 */

gulp.task('help', $.taskListing);

gulp.task('default', ['serve', 'test']);

gulp.task('vet', function (done) {
    log('Checking JS files for errors with JSHINT & JSCS');
    return gulp
        .src(config.js)
        .pipe($.plumber())
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {
            verbose: true
        }))
    //     .pipe($.jshint.reporter('fail'));
});

gulp.task('scripts', ['vet', 'clean-scripts'], function () {
    log('Copying app JS files to the distribution folder');
    return gulp
        .src(config.js)
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'js'));
});

gulp.task('clean-scripts', function (done) {
    clean(config.dist + 'js', done);
});

gulp.task('lib', ['clean-lib'], function () {
    log('Copying vendor JS & CSS files to the distribution folder');
    return gulp
        .src(mainBowerFiles())
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'lib'));
});

gulp.task('clean-lib', function (done) {
    clean(config.dist + 'lib', done);
});

gulp.task('styles', ['clean-styles'], function () {
    log('Adding vendor prefixes to CSS using autoprefixer');
    return gulp
        .src(config.css)
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions', '>5%']
        }))
        .pipe(gulp.dest(config.dist + 'css'));
});

gulp.task('clean-styles', function (done) {
    clean(config.dist + 'css', done);
});

gulp.task('images', ['clean-images'], function () {
    log('Optimizing images and copying them to the distribution folder');
    return gulp
        .src(config.images)
        .pipe($.plumber())
        .pipe($.imagemin({
            optimizationLevel: 4,
            verbose: true //TODO: add cli arguments support for verbose
        }))
        .pipe(gulp.dest(config.dist + 'images'));
});

gulp.task('clean-images', function (done) {
    clean(config.dist + 'images', done);
});

gulp.task('fonts', ['clean-fonts'], function () {
    log('Copying fonts to the distribution folder');
    return gulp
        .src(config.fonts)
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'fonts'));
});

gulp.task('clean-fonts', function (done) {
    clean(config.dist + 'fonts', done);
});

gulp.task('clean', function (done) {
    clean(config.dist, done);
});

gulp.task('inject', ['clean-index'], function () {
    log('Wiring up app/vendor JS and CSS files');
    return gulp
        .src(config.index)
        .pipe($.plumber())
        .pipe($.inject(gulp.src(mainBowerFiles('**/*.js'), {
            read: false
        }), {
            starttag: '<!-- inject:vendorJS -->',
            transform: transformJsPath
        }))
        .pipe($.inject(gulp.src(mainBowerFiles('**/*.css'), {
            read: false
        }), {
            starttag: '<!-- inject:vendorCSS -->',
            transform: transformCssPath
        }))
        .pipe($.inject(gulp.src(config.js, {
            read: false
        }), {
            ignorePath: '/src/',
            relative: true,
            starttag: '<!-- inject:appJS -->',

        }))
        .pipe($.inject(gulp.src(config.css, {
            read: false
        }), {
            ignorePath: '/src/',
            relative: true,
            starttag: '<!-- inject:appCSS -->',
        }))
        .pipe(gulp.dest(config.dist));
});

gulp.task('clean-index', function (done) {
    clean(config.dist + 'index.html', done);
});

gulp.task('build', ['lib', 'scripts', 'test', 'styles', 'images', 'fonts', 'inject']);

gulp.task('serve', ['build'], function () {
    log('Serving the project in the browser');
    gulp.watch(config.js, ['scripts', 'test', 'inject']);
    gulp.watch(config.test, ['test']);
    gulp.watch(config.bowerDir, ['lib', 'inject']);
    gulp.watch(config.css, ['styles', 'inject']);
    gulp.watch(config.css, ['images', 'images']);
    gulp.watch(config.css, ['fonts', 'fonts']);

    var options = {
        server: {
            baseDir: config.dist
        },
        port: 3000,
        files: config.dist,
        ghostMode: {
            clicks: true,
            location: true,
            forms: true,
            scroll: true
        },
        injectChanges: true,
        logFileChanges: true,
        logLevel: 'info',
        logPrefix: 'gulp',
        reloadDelay: 500
    };
    browserSync(options);
});

gulp.task('test', function (done) {
    log('Testing code');
    startTests(true, done);
});

gulp.task('autotest', ['vet'], function (done) {
    log('Testing code in single run mode');
    startTests(false, done);
});

/**
 * ----------------------------------------------------------------------------
 * Helper functions
 * ----------------------------------------------------------------------------
 */

function clean(path, done) {
    log('Cleaning assets in: ' + path, 'warning');
    del(path)
        .then(function fullfilled() {
            return done();
        })
        .catch(function rejected(exception) {
            log(exception, 'error');
        });
}

function log(message, logType) {
    logType = logType || 'info';
    var logTypes = {
        info: 'blue',
        warning: 'yellow',
        error: 'red'
    };
    var color = logTypes[logType] ? logTypes[logType] : 'blue';

    $.util.log($.util.colors[color](message));
}

// Bower files injection helpers

function stripBowerPath(path) {
    return path.replace(/\/bower_components\/(\w+\/)+/, '');
}

function transformJsPath(filePath) {
    var fileName = stripBowerPath(filePath);
    return '<script src="lib/' + fileName + '"></script>';
}

function transformCssPath(filePath) {
    var fileName = stripBowerPath(filePath);
    return '<link rel="stylesheet" href="lib/' + fileName + '">';
}

// Tests Helpers

function startTests(singleRun, done) {
    var Server = require('karma').Server;
    var excludeFiles = [];

    var server = Server.start({
        configFile: __dirname + '/karma.conf.js',
        exclude: excludeFiles,
        singleRun: !!singleRun
    }, karmaCompleted);

    function karmaCompleted(karmaResult) {
        var status = karmaResult === 1 ? 'ERROR' : 'SUCCESS';
        log('karma completed with status: ' + status);
        done();
    }
}
<commit_msg>add browserSync watch task for index.html<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')({
    lazy: true
});
var del = require('del');
var mainBowerFiles = require('main-bower-files');

var config = require('./gulp.config.js')();

/**
 * ----------------------------------------------------------------------------
 * Lazy Loaded Gulp Packages
 * ----------------------------------------------------------------------------
 *
 *      gulp-autoprefixer
 *      gulp-imagemin
 *      gulp-jscs
 *      gulp-jshint
 *      gulp-plumber
 *      gulp-task-listing
 *      gulp-util
 */

/**
 * ----------------------------------------------------------------------------
 * Tasks List
 * ----------------------------------------------------------------------------
 *
 *      gulp default        => Test, build and serve the project.
 *      gulp help           => Display the available tasks.
 *
 *      gulp clean          => Delete the dist folder.
 *      gulp build          => Build the project.
 *      gulp serve          => Serve the project in the browser.
 *
 *      gulp auto           => Run tests continuously.
 *      gulp test           => Run tests in single run mode.
 *
 *      gulp inject         => Inject JS and CSS assets into index.html.
 *                             then Copy to the dist. folder.
 *
 *      gulp lib            => Copy Bower dependencies to the dist. folder.
 *      gulp clean-lib      => Clean the distribued vendor JS & CSS files.
 *
 *      gulp vet            => Run jshint & jscs against all js code.
 *      gulp scripts        => Copy app JS files to the dist. folder.
 *      gulp-clean-scripts  => Clean the distribued JS files.
 *
 *      gulp styles         => Add vendor prefixes to CSS and copy to the dist. folder.
 *      gulp clean-styles   => Clean the distributed CSS files.
 *
 *      gulp images         => Optimize images and copy to the dist. folder.
 *      gulp clean-images   => Clean the distributed image files.
 *
 *      gulp-fonts          => Copy fonts to the dist. folder.
 *      gulp-clean-fonts    => Clean the distributed font files.
 *
 */

gulp.task('help', $.taskListing);

gulp.task('default', ['serve', 'test']);

gulp.task('vet', function (done) {
    log('Checking JS files for errors with JSHINT & JSCS');
    return gulp
        .src(config.js)
        .pipe($.plumber())
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {
            verbose: true
        }))
    //     .pipe($.jshint.reporter('fail'));
});

gulp.task('scripts', ['vet', 'clean-scripts'], function () {
    log('Copying app JS files to the distribution folder');
    return gulp
        .src(config.js)
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'js'));
});

gulp.task('clean-scripts', function (done) {
    clean(config.dist + 'js', done);
});

gulp.task('lib', ['clean-lib'], function () {
    log('Copying vendor JS & CSS files to the distribution folder');
    return gulp
        .src(mainBowerFiles())
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'lib'));
});

gulp.task('clean-lib', function (done) {
    clean(config.dist + 'lib', done);
});

gulp.task('styles', ['clean-styles'], function () {
    log('Adding vendor prefixes to CSS using autoprefixer');
    return gulp
        .src(config.css)
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions', '>5%']
        }))
        .pipe(gulp.dest(config.dist + 'css'));
});

gulp.task('clean-styles', function (done) {
    clean(config.dist + 'css', done);
});

gulp.task('images', ['clean-images'], function () {
    log('Optimizing images and copying them to the distribution folder');
    return gulp
        .src(config.images)
        .pipe($.plumber())
        .pipe($.imagemin({
            optimizationLevel: 4,
            verbose: true //TODO: add cli arguments support for verbose
        }))
        .pipe(gulp.dest(config.dist + 'images'));
});

gulp.task('clean-images', function (done) {
    clean(config.dist + 'images', done);
});

gulp.task('fonts', ['clean-fonts'], function () {
    log('Copying fonts to the distribution folder');
    return gulp
        .src(config.fonts)
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist + 'fonts'));
});

gulp.task('clean-fonts', function (done) {
    clean(config.dist + 'fonts', done);
});

gulp.task('clean', function (done) {
    clean(config.dist, done);
});

gulp.task('inject', ['clean-index'], function () {
    log('Wiring up app/vendor JS and CSS files');
    return gulp
        .src(config.index)
        .pipe($.plumber())
        .pipe($.inject(gulp.src(mainBowerFiles('**/*.js'), {
            read: false
        }), {
            starttag: '<!-- inject:vendorJS -->',
            transform: transformJsPath
        }))
        .pipe($.inject(gulp.src(mainBowerFiles('**/*.css'), {
            read: false
        }), {
            starttag: '<!-- inject:vendorCSS -->',
            transform: transformCssPath
        }))
        .pipe($.inject(gulp.src(config.js, {
            read: false
        }), {
            ignorePath: '/src/',
            relative: true,
            starttag: '<!-- inject:appJS -->',

        }))
        .pipe($.inject(gulp.src(config.css, {
            read: false
        }), {
            ignorePath: '/src/',
            relative: true,
            starttag: '<!-- inject:appCSS -->',
        }))
        .pipe(gulp.dest(config.dist));
});

gulp.task('clean-index', function (done) {
    clean(config.dist + 'index.html', done);
});

gulp.task('build', ['lib', 'scripts', 'test', 'styles', 'images', 'fonts', 'inject']);

gulp.task('serve', ['build'], function () {
    log('Serving the project in the browser');
    gulp.watch(config.index, ['inject']);
    gulp.watch(config.js, ['scripts', 'test', 'inject']);
    gulp.watch(config.test, ['test']);
    gulp.watch(config.bowerDir, ['lib', 'inject']);
    gulp.watch(config.css, ['styles', 'inject']);
    gulp.watch(config.css, ['images', 'images']);
    gulp.watch(config.css, ['fonts', 'fonts']);

    var options = {
        server: {
            baseDir: config.dist
        },
        port: 3000,
        files: config.dist,
        ghostMode: {
            clicks: true,
            location: true,
            forms: true,
            scroll: true
        },
        injectChanges: true,
        logFileChanges: true,
        logLevel: 'info',
        logPrefix: 'gulp',
        reloadDelay: 500
    };
    browserSync(options);
});

gulp.task('test', function (done) {
    log('Testing code');
    startTests(true, done);
});

gulp.task('autotest', ['vet'], function (done) {
    log('Testing code in single run mode');
    startTests(false, done);
});

/**
 * ----------------------------------------------------------------------------
 * Helper functions
 * ----------------------------------------------------------------------------
 */

function clean(path, done) {
    log('Cleaning assets in: ' + path, 'warning');
    del(path)
        .then(function fullfilled() {
            return done();
        })
        .catch(function rejected(exception) {
            log(exception, 'error');
        });
}

function log(message, logType) {
    logType = logType || 'info';
    var logTypes = {
        info: 'blue',
        warning: 'yellow',
        error: 'red'
    };
    var color = logTypes[logType] ? logTypes[logType] : 'blue';

    $.util.log($.util.colors[color](message));
}

// Bower files injection helpers

function stripBowerPath(path) {
    return path.replace(/\/bower_components\/(\w+\/)+/, '');
}

function transformJsPath(filePath) {
    var fileName = stripBowerPath(filePath);
    return '<script src="lib/' + fileName + '"></script>';
}

function transformCssPath(filePath) {
    var fileName = stripBowerPath(filePath);
    return '<link rel="stylesheet" href="lib/' + fileName + '">';
}

// Tests Helpers

function startTests(singleRun, done) {
    var Server = require('karma').Server;
    var excludeFiles = [];

    var server = Server.start({
        configFile: __dirname + '/karma.conf.js',
        exclude: excludeFiles,
        singleRun: !!singleRun
    }, karmaCompleted);

    function karmaCompleted(karmaResult) {
        var status = karmaResult === 1 ? 'ERROR' : 'SUCCESS';
        log('karma completed with status: ' + status);
        done();
    }
}
<|endoftext|>


<commit_before>/*eslint strict: [2, "global"], no-var: 0*/

'use strict';

var packageJson = require('./package.json');
var conventionalChangelog = require('conventional-changelog');
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var eslint = require('gulp-eslint');
var through = require('through2');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');

var MAIN_FILES = './*.js';
var SRC_FILES = './src/**/*.js';
var DIST_DIR = './dist/';

var isMac = process.platform === 'darwin';
var isWin = process.platform === 'win32';

// options for transpiling es6 to es5
// we need to check OS here because Linux doesn't have CEF with generators
var babelOptions = isMac || isWin ? {
  // generators are available in Brackets' shell and also break sourcemaps
  blacklist: ['regenerator', 'strict']
} : {};

// provides pipe to log stuff to console when certain task finishes
function logPipe(str) {
  return through.obj(function (file, enc, cb) {
    cb();
  }, function (cb) {
    gutil.log(str);
    cb();
  });
}

// prevents watch from crashing on errors
function swallowError(error) {
  gutil.log(gutil.colors.red(error.toString()));
  this.emit('end');
}

// helper for transpiling es6 files to es5
function doBabel(globs, singleFile) {
  if (singleFile) {
    gutil.log(gutil.colors.cyan('Start Babel ' + globs[0]));
  }

  var task = gulp.src(globs, {base: path.resolve(__dirname, 'src')})
    .pipe(sourcemaps.init())
    .pipe(babel(babelOptions))
    .on('error', swallowError)
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: path.resolve(__dirname, 'dist') + '/'
    }))
    .pipe(gulp.dest(DIST_DIR));

  return singleFile ?
    task.pipe(logPipe(gutil.colors.cyan('Finish Babel ' + globs[0]))) :
    task;
}

// helper for linting files
function doEslint(globs, singleFile) {
  if (singleFile) {
    gutil.log(gutil.colors.magenta('Start ESLint ' + globs[0]));
  }

  var task = gulp.src(globs)
    .pipe(eslint())
    .pipe(eslint.format());

  return singleFile ?
    task.pipe(logPipe(gutil.colors.magenta('Finish ESLint ' + globs[0]))) :
    task.pipe(eslint.failAfterError());
}

gulp.task('babel', function () {
  return doBabel([SRC_FILES], false);
});

gulp.task('eslint', function () {
  return doEslint([MAIN_FILES, SRC_FILES], false);
});

gulp.task('watch', function () {
  gulp.watch([SRC_FILES]).on('change', function (event) {
    var filePath = path.relative(__dirname, event.path);
    if (fs.statSync(filePath).isFile()) {
      doEslint([filePath], true);
      doBabel([filePath], true);
    }
  });
});

gulp.task('changelog', function () {
  conventionalChangelog({
    repository: packageJson.homepage,
    version: packageJson.version
    //version: '0.1.3',
    //from: 'v0.1.2',
    //to: 'v0.1.3'
  }, function (err, log) {
    if (err) { throw err; }
    fs.writeFileSync(path.resolve(__dirname, 'CHANGELOG.md'), log);
  });
});

gulp.task('build', ['babel']);
gulp.task('test', ['eslint']);
gulp.task('default', ['build', 'test']);
<commit_msg>fixes #9<commit_after>/*eslint strict: [2, "global"], no-var: 0*/

'use strict';

var packageJson = require('./package.json');
var conventionalChangelog = require('conventional-changelog');
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var eslint = require('gulp-eslint');
var through = require('through2');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');

var MAIN_FILES = './*.js';
var SRC_FILES = './src/**/*.js';
var DIST_DIR = './dist/';

var isMac = process.platform === 'darwin';
var isWin = process.platform === 'win32';

// options for transpiling es6 to es5
// we need to check OS here because Linux doesn't have CEF with generators
var babelOptions = isMac || isWin ? {
  // generators are available in Brackets' shell and also break sourcemaps
  blacklist: ['regenerator', 'strict']
} : {};

// provides pipe to log stuff to console when certain task finishes
function logPipe(str) {
  return through.obj(function (file, enc, cb) {
    cb();
  }, function (cb) {
    gutil.log(str);
    cb();
  });
}

// prevents watch from crashing on errors
function swallowError(error) {
  gutil.log(gutil.colors.red(error.toString()));
  this.emit('end');
}

// helper for transpiling es6 files to es5
function doBabel(globs, singleFile) {
  if (singleFile) {
    gutil.log(gutil.colors.cyan('Start Babel ' + globs[0]));
  }

  var task = gulp.src(globs, {base: 'src'})
    .pipe(sourcemaps.init())
    .pipe(babel(babelOptions))
    .on('error', swallowError)
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: path.resolve(__dirname, 'dist') + '/'
    }))
    .pipe(gulp.dest(DIST_DIR));

  return singleFile ?
    task.pipe(logPipe(gutil.colors.cyan('Finish Babel ' + globs[0]))) :
    task;
}

// helper for linting files
function doEslint(globs, singleFile) {
  if (singleFile) {
    gutil.log(gutil.colors.magenta('Start ESLint ' + globs[0]));
  }

  var task = gulp.src(globs)
    .pipe(eslint())
    .pipe(eslint.format());

  return singleFile ?
    task.pipe(logPipe(gutil.colors.magenta('Finish ESLint ' + globs[0]))) :
    task.pipe(eslint.failAfterError());
}

gulp.task('babel', function () {
  return doBabel([SRC_FILES], false);
});

gulp.task('eslint', function () {
  return doEslint([MAIN_FILES, SRC_FILES], false);
});

gulp.task('watch', function () {
  gulp.watch([SRC_FILES]).on('change', function (event) {
    var filePath = path.relative(__dirname, event.path);
    if (fs.statSync(filePath).isFile()) {
      doEslint([filePath], true);
      doBabel([filePath], true);
    }
  });
});

gulp.task('changelog', function () {
  conventionalChangelog({
    repository: packageJson.homepage,
    version: packageJson.version
    //version: '0.1.3',
    //from: 'v0.1.2',
    //to: 'v0.1.3'
  }, function (err, log) {
    if (err) { throw err; }
    fs.writeFileSync(path.resolve(__dirname, 'CHANGELOG.md'), log);
  });
});

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


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

var settings =
{
	functionPrefix: 'PioneerDDJSR',
	filePrefix: 'PIONEER_DDJ-SR',
	name: 'Pioneer DDJ-SR',
	author: 'Hilton Rudham <hiltonrudham@gmail.com>',
	description: 'Pioneer DDJ-SR configuration for 2 decks on midi channels 1 and 2'
};

gulp.task(
	'compile-xml',
	function()
	{
		var mixer = require('./source/mappings/controls/mixer.js');
		var playlist = require('./source/mappings/controls/playlist.js');
		var channel = require('./source/mappings/controls/channel.js');
		var jogWheel = require('./source/mappings/controls/jog-wheel.js');
		var hotCue = require('./source/mappings/controls/performance-pads/hot-cue.js');
		var roll = require('./source/mappings/controls/performance-pads/roll.js');
		var sampler = require('./source/mappings/controls/performance-pads/sampler.js');

		return gulp
			.src('source/mappings/midi-mapping.xml')
			.pipe(
				ejs({
					settings: settings,
					controls: playlist
						.concat(mixer)
						.concat(channel)
						.concat(jogWheel)
						.concat(hotCue)
						.concat(roll)
						.concat(sampler)
					}))
			.pipe(rename(settings.filePrefix + '.midi.xml'))
			.pipe(gulp.dest('bin'));
	});

gulp.task(
	'compile-js',
	function()
	{
		return gulp
			.src('source/scripts/scripts.js')
			.pipe(rename(settings.filePrefix + '-scripts.js'))
			.pipe(gulp.dest('bin'));
	});

gulp.task(
	'default',
	['compile-xml', 'compile-js'],
	function()
	{
		return gulp.src(
			[
				'bin/**/*.*'
			])
			.pipe(gulp.dest(process.env.LOCALAPPDATA + '/Mixxx/controllers'));
	});<commit_msg>Delete gulpfile.js<commit_after><|endoftext|>


<commit_before>/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';
/* eslint-env node */
/* eslint require-jsdoc: 0 */

const del = require('del');
const gulp = require('gulp');
const fs = require('fs-extra');
const semver = require('semver');
const copy = require('gulp-copy');
const csso = require('gulp-csso');
const ghPages = require('gh-pages');
const terser = require('gulp-terser');
const eslint = require('gulp-eslint');
const connect = require('gulp-connect');
const htmlmin = require('gulp-htmlmin');
const replace = require('gulp-replace');
const workbox = require('workbox-build');
const {series, parallel} = require('gulp');
const inlinesource = require('gulp-inline-source');

let _appVersion;

const SRC_DIR = 'src';
const DEST_DIR = 'build';
const TEMP_DIR = '.tmp';
const TERSER_OPTS = {
  compress: {
    drop_console: true,
  },
  output: {
    beautify: false,
    max_line_len: 120,
    indent_level: 2,
  },
};

/** ***************************************************************************
 * Bump Version Number
 *****************************************************************************/

/**
 * Bumps the version number in the package.json file.
 *
 * @param {string} release - Type of release patch|minor|major.
 * @return {Promise}.
 */
function bumpVersion(release) {
  release = release || 'patch';
  return fs.readJson('package.json')
      .then((data) => {
        const currentVersion = data.version;
        const nextVersion = semver.inc(currentVersion, release);
        data.version = nextVersion;
        return fs.writeJson('package.json', data, {spaces: 2});
      });
}

function bumpPatch() {
  return bumpVersion('patch');
}

function bumpMinor() {
  return bumpVersion('patch');
}

function bumpMajor() {
  return bumpVersion('patch');
}

exports.bumpPatch = bumpPatch;
exports.bumpMinor = bumpMinor;
exports.bumpMajor = bumpMajor;

/** ***************************************************************************
 * Clean
 *****************************************************************************/

function clean() {
  return del(['build/**', '.tmp/**']);
}

exports.clean = clean;

/** ***************************************************************************
 * Linting & Doc Generation
 *****************************************************************************/

function lint() {
  const filesToLint = [
    'gulpfile.js',
    'src/index.html',
    'src/inline-scripts/*',
  ];
  const config = {
    useEslintrc: true,
  };
  return gulp.src(filesToLint)
      .pipe(eslint(config))
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
}

exports.lint = lint;

/** ***************************************************************************
 * Generate Service Worker
 *****************************************************************************/

function generateServiceWorker() {
  return workbox.generateSW({
    globDirectory: DEST_DIR,
    globPatterns: [
      '**/*.{html,js,png,ico,mp3,json}',
    ],
    swDest: `${DEST_DIR}/service-worker.js`,
    clientsClaim: true,
    skipWaiting: true,
    offlineGoogleAnalytics: true,
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/fonts\.gstatic\.com/,
        handler: 'CacheFirst',
        options: {
          cacheName: 'googleapis',
          expiration: {maxEntries: 30},
        },
      },
    ],
  }).then(({warnings}) => {
    for (const warning of warnings) {
      // eslint-disable-next-line no-console
      console.log(warning);
    }
  });
}

exports.generateServiceWorker = generateServiceWorker;

/** ***************************************************************************
 * Build
 *****************************************************************************/

function buildCSS() {
  const cssoOpts = {
    sourceMap: true,
  };
  return gulp.src(`${SRC_DIR}/styles/*.css`)
      .pipe(csso(cssoOpts))
      .pipe(gulp.dest(`${TEMP_DIR}/styles/`));
}

function buildJS() {
  return gulp.src(`${SRC_DIR}/inline-scripts/*.js`)
      .pipe(terser(TERSER_OPTS))
      .pipe(gulp.dest(`${TEMP_DIR}/inline-scripts`));
}

function copyHTML() {
  const filesToCopy = [
    `${SRC_DIR}/index.html`,
  ];
  return gulp.src(filesToCopy)
      .pipe(copy(TEMP_DIR, {prefix: 1}));
}

function buildHTML() {
  const inlineOpts = {
    compress: false,
    pretty: false,
  };
  const htmlMinOpts = {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: false,
    removeComments: true,
  };
  const buildDate = new Date().toISOString();
  const packageJSON = fs.readJsonSync('package.json');
  _appVersion = packageJSON.version;
  return gulp.src(`${TEMP_DIR}/index.html`)
      .pipe(inlinesource(inlineOpts))
      .pipe(replace('[[BUILD_DATE]]', buildDate))
      .pipe(replace('[[VERSION]]', _appVersion))
      .pipe(htmlmin(htmlMinOpts))
      .pipe(gulp.dest(TEMP_DIR));
}

function copyStatic() {
  const filesToCopy = [
    `${TEMP_DIR}/index.html`,
    `${SRC_DIR}/icons/**/*`,
    `${SRC_DIR}/images/**/*`,
    `${SRC_DIR}/sounds/**/*`,
    `${SRC_DIR}/manifest.json`,
    `${SRC_DIR}/robots.txt`,
    `${SRC_DIR}/humans.txt`,
  ];
  return gulp.src(filesToCopy)
      .pipe(copy(DEST_DIR, {prefix: 1}));
}

exports.buildCSS = buildCSS;
exports.buildJS = buildJS;
exports.buildHTML = buildHTML;
exports.copyStatic = copyStatic;
exports.build = series(
    clean,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic
);
exports.buildProd = series(
    clean,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic,
    generateServiceWorker
);

/** ***************************************************************************
 * Development - serving
 *****************************************************************************/

function serveDev() {
  return connect.server({root: 'src'});
}
function serveProd() {
  return connect.server({root: 'build'});
}

exports.serve = serveDev;
exports.serveProd = serveProd;

/** ***************************************************************************
 * Deploy
 *****************************************************************************/

function deployToGHPages(cb) {
  const opts = {
    message: 'Auto-generated deploy commit.',
  };
  if (_appVersion) {
    opts.tag = _appVersion;
  }
  return ghPages.publish('build', opts, (err) => {
    if (err) {
      throw err;
    }
    cb();
  });
}

exports.deployProd = series(
    lint,
    clean,
    bumpPatch,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic,
    generateServiceWorker,
    deployToGHPages
);
<commit_msg>Update list of cached files<commit_after>/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';
/* eslint-env node */
/* eslint require-jsdoc: 0 */

const del = require('del');
const gulp = require('gulp');
const fs = require('fs-extra');
const semver = require('semver');
const copy = require('gulp-copy');
const csso = require('gulp-csso');
const ghPages = require('gh-pages');
const terser = require('gulp-terser');
const eslint = require('gulp-eslint');
const connect = require('gulp-connect');
const htmlmin = require('gulp-htmlmin');
const replace = require('gulp-replace');
const workbox = require('workbox-build');
const {series, parallel} = require('gulp');
const inlinesource = require('gulp-inline-source');

let _appVersion;

const SRC_DIR = 'src';
const DEST_DIR = 'build';
const TEMP_DIR = '.tmp';
const TERSER_OPTS = {
  compress: {
    drop_console: true,
  },
  output: {
    beautify: false,
    max_line_len: 120,
    indent_level: 2,
  },
};

/** ***************************************************************************
 * Bump Version Number
 *****************************************************************************/

/**
 * Bumps the version number in the package.json file.
 *
 * @param {string} release - Type of release patch|minor|major.
 * @return {Promise}.
 */
function bumpVersion(release) {
  release = release || 'patch';
  return fs.readJson('package.json')
      .then((data) => {
        const currentVersion = data.version;
        const nextVersion = semver.inc(currentVersion, release);
        data.version = nextVersion;
        return fs.writeJson('package.json', data, {spaces: 2});
      });
}

function bumpPatch() {
  return bumpVersion('patch');
}

function bumpMinor() {
  return bumpVersion('patch');
}

function bumpMajor() {
  return bumpVersion('patch');
}

exports.bumpPatch = bumpPatch;
exports.bumpMinor = bumpMinor;
exports.bumpMajor = bumpMajor;

/** ***************************************************************************
 * Clean
 *****************************************************************************/

function clean() {
  return del(['build/**', '.tmp/**']);
}

exports.clean = clean;

/** ***************************************************************************
 * Linting & Doc Generation
 *****************************************************************************/

function lint() {
  const filesToLint = [
    'gulpfile.js',
    'src/index.html',
    'src/inline-scripts/*',
  ];
  const config = {
    useEslintrc: true,
  };
  return gulp.src(filesToLint)
      .pipe(eslint(config))
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
}

exports.lint = lint;

/** ***************************************************************************
 * Generate Service Worker
 *****************************************************************************/

function generateServiceWorker() {
  return workbox.generateSW({
    globDirectory: DEST_DIR,
    globPatterns: [
      '**/*.{html,js,png,jpg,gif,ico}',
    ],
    swDest: `${DEST_DIR}/service-worker.js`,
    clientsClaim: true,
    skipWaiting: true,
    offlineGoogleAnalytics: true,
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/fonts\.gstatic\.com/,
        handler: 'CacheFirst',
        options: {
          cacheName: 'googleapis',
          expiration: {maxEntries: 30},
        },
      },
    ],
  }).then(({warnings}) => {
    for (const warning of warnings) {
      // eslint-disable-next-line no-console
      console.log(warning);
    }
  });
}

exports.generateServiceWorker = generateServiceWorker;

/** ***************************************************************************
 * Build
 *****************************************************************************/

function buildCSS() {
  const cssoOpts = {
    sourceMap: true,
  };
  return gulp.src(`${SRC_DIR}/styles/*.css`)
      .pipe(csso(cssoOpts))
      .pipe(gulp.dest(`${TEMP_DIR}/styles/`));
}

function buildJS() {
  return gulp.src(`${SRC_DIR}/inline-scripts/*.js`)
      .pipe(terser(TERSER_OPTS))
      .pipe(gulp.dest(`${TEMP_DIR}/inline-scripts`));
}

function copyHTML() {
  const filesToCopy = [
    `${SRC_DIR}/index.html`,
  ];
  return gulp.src(filesToCopy)
      .pipe(copy(TEMP_DIR, {prefix: 1}));
}

function buildHTML() {
  const inlineOpts = {
    compress: false,
    pretty: false,
  };
  const htmlMinOpts = {
    collapseWhitespace: true,
    minifyCSS: true,
    minifyJS: false,
    removeComments: true,
  };
  const buildDate = new Date().toISOString();
  const packageJSON = fs.readJsonSync('package.json');
  _appVersion = packageJSON.version;
  return gulp.src(`${TEMP_DIR}/index.html`)
      .pipe(inlinesource(inlineOpts))
      .pipe(replace('[[BUILD_DATE]]', buildDate))
      .pipe(replace('[[VERSION]]', _appVersion))
      .pipe(htmlmin(htmlMinOpts))
      .pipe(gulp.dest(TEMP_DIR));
}

function copyStatic() {
  const filesToCopy = [
    `${TEMP_DIR}/index.html`,
    `${SRC_DIR}/icons/**/*`,
    `${SRC_DIR}/images/**/*`,
    `${SRC_DIR}/sounds/**/*`,
    `${SRC_DIR}/manifest.json`,
    `${SRC_DIR}/robots.txt`,
    `${SRC_DIR}/humans.txt`,
  ];
  return gulp.src(filesToCopy)
      .pipe(copy(DEST_DIR, {prefix: 1}));
}

exports.buildCSS = buildCSS;
exports.buildJS = buildJS;
exports.buildHTML = buildHTML;
exports.copyStatic = copyStatic;
exports.build = series(
    clean,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic
);
exports.buildProd = series(
    clean,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic,
    generateServiceWorker
);

/** ***************************************************************************
 * Development - serving
 *****************************************************************************/

function serveDev() {
  return connect.server({root: 'src'});
}
function serveProd() {
  return connect.server({root: 'build'});
}

exports.serve = serveDev;
exports.serveProd = serveProd;

/** ***************************************************************************
 * Deploy
 *****************************************************************************/

function deployToGHPages(cb) {
  const opts = {
    message: 'Auto-generated deploy commit.',
  };
  if (_appVersion) {
    opts.tag = _appVersion;
  }
  return ghPages.publish('build', opts, (err) => {
    if (err) {
      throw err;
    }
    cb();
  });
}

exports.deployProd = series(
    lint,
    clean,
    bumpPatch,
    parallel(copyHTML, buildCSS, buildJS),
    buildHTML,
    copyStatic,
    generateServiceWorker,
    deployToGHPages
);
<|endoftext|>


<commit_before>const assembler = require('fabricator-assemble');
const browserSync = require('browser-sync');
const csso = require('gulp-csso');
const del = require('del');
const gulp = require('gulp');
const gutil = require('gulp-util');
const gulpif = require('gulp-if');
const imagemin = require('gulp-imagemin');
const prefix = require('gulp-autoprefixer');
const rename = require('gulp-rename');
const reload = browserSync.reload;
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const webpack = require('webpack');

// configuration
const config = {
  dev: gutil.env.dev,
  styles: {
    browsers: 'last 1 version',
    fabricator: {
      src: 'src/assets/fabricator/styles/fabricator.scss',
      dest: 'dist/assets/fabricator/styles',
      watch: 'src/assets/fabricator/styles/**/*.scss',
    },
    toolkit: {
      src: 'src/assets/toolkit/styles/toolkit.scss',
      dest: 'dist/assets/toolkit/styles',
      watch: 'src/assets/toolkit/styles/**/*.scss',
    },
  },
  scripts: {
    fabricator: {
      src: './src/assets/fabricator/scripts/fabricator.js',
      dest: 'dist/assets/fabricator/scripts',
      watch: 'src/assets/fabricator/scripts/**/*',
    },
    toolkit: {
      src: './src/assets/toolkit/scripts/toolkit.js',
      dest: 'dist/assets/toolkit/scripts',
      watch: 'src/assets/toolkit/scripts/**/*',
    },
  },
  images: {
    toolkit: {
      src: ['src/assets/toolkit/images/**/*', 'src/favicon.ico'],
      dest: 'dist/assets/toolkit/images',
      watch: 'src/assets/toolkit/images/**/*',
    },
  },
  templates: {
    watch: 'src/**/*.{html,md,json,yml}',
  },
  dest: 'dist',
};

// clean
gulp.task('clean', del.bind(null, [config.dest]));

// styles
gulp.task('styles:fabricator', () => {
  gulp.src(config.styles.fabricator.src)
  .pipe(sourcemaps.init())
  .pipe(sass().on('error', sass.logError))
  .pipe(prefix('last 1 version'))
  .pipe(gulpif(!config.dev, csso()))
  .pipe(rename('f.css'))
  .pipe(sourcemaps.write())
  .pipe(gulp.dest(config.styles.fabricator.dest))
  .pipe(gulpif(config.dev, reload({ stream: true })));
});

gulp.task('styles:toolkit', () => {
  gulp.src(config.styles.toolkit.src)
  .pipe(gulpif(config.dev, sourcemaps.init()))
  .pipe(sass({
    includePaths: './node_modules',
  }).on('error', sass.logError))
  .pipe(prefix('last 1 version'))
  .pipe(gulpif(!config.dev, csso()))
  .pipe(gulpif(config.dev, sourcemaps.write()))
  .pipe(gulp.dest(config.styles.toolkit.dest))
  .pipe(gulpif(config.dev, reload({ stream: true })));
});

gulp.task('styles', ['styles:fabricator', 'styles:toolkit']);

// scripts
const webpackConfig = require('./webpack.config')(config);

gulp.task('scripts', (done) => {
  webpack(webpackConfig, (err, stats) => {
    if (err) {
      gutil.log(gutil.colors.red(err()));
    }
    const result = stats.toJson();
    if (result.errors.length) {
      result.errors.forEach((error) => {
        gutil.log(gutil.colors.red(error));
      });
    }
    done();
  });
});

// images
gulp.task('images', ['favicon'], () => {
  return gulp.src(config.images.toolkit.src)
    .pipe(imagemin())
    .pipe(gulp.dest(config.images.toolkit.dest));
});

gulp.task('favicon', () => {
  return gulp.src('src/favicon.ico')
  .pipe(gulp.dest(config.dest));
});

// assembler
gulp.task('assembler', (done) => {
  assembler({
    logErrors: config.dev,
    dest: config.dest,
  });
  done();
});

// server
gulp.task('serve', () => {

  browserSync({
    server: {
      baseDir: config.dest,
    },
    notify: false,
    logPrefix: 'FABRICATOR',
    open: false
  });

  gulp.task('assembler:watch', ['assembler'], browserSync.reload);
  gulp.watch(config.templates.watch, ['assembler:watch']);

  gulp.task('styles:watch', ['styles']);
  gulp.watch([config.styles.fabricator.watch, config.styles.toolkit.watch], ['styles:watch']);

  gulp.task('scripts:watch', ['scripts'], browserSync.reload);
  gulp.watch([config.scripts.fabricator.watch, config.scripts.toolkit.watch], ['scripts:watch']);

  gulp.task('images:watch', ['images'], browserSync.reload);
  gulp.watch(config.images.toolkit.watch, ['images:watch']);

});

// default build task
gulp.task('default', ['clean'], () => {

  // define build tasks
  const tasks = [
    'styles',
    'scripts',
    'images',
    'assembler',
  ];

  // run build
  runSequence(tasks, () => {
    if (config.dev) {
      gulp.start('serve');
    }
  });

});
<commit_msg>gulp fonts task added<commit_after>const assembler = require('fabricator-assemble');
const browserSync = require('browser-sync');
const csso = require('gulp-csso');
const del = require('del');
const gulp = require('gulp');
const gutil = require('gulp-util');
const gulpif = require('gulp-if');
const imagemin = require('gulp-imagemin');
const prefix = require('gulp-autoprefixer');
const rename = require('gulp-rename');
const reload = browserSync.reload;
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const webpack = require('webpack');

// configuration
const config = {
  dev: gutil.env.dev,
  styles: {
    browsers: 'last 1 version',
    fabricator: {
      src: 'src/assets/fabricator/styles/fabricator.scss',
      dest: 'dist/assets/fabricator/styles',
      watch: 'src/assets/fabricator/styles/**/*.scss',
    },
    toolkit: {
      src: 'src/assets/toolkit/styles/toolkit.scss',
      dest: 'dist/assets/toolkit/styles',
      watch: 'src/assets/toolkit/styles/**/*.scss',
    },
  },
  scripts: {
    fabricator: {
      src: './src/assets/fabricator/scripts/fabricator.js',
      dest: 'dist/assets/fabricator/scripts',
      watch: 'src/assets/fabricator/scripts/**/*',
    },
    toolkit: {
      src: './src/assets/toolkit/scripts/toolkit.js',
      dest: 'dist/assets/toolkit/scripts',
      watch: 'src/assets/toolkit/scripts/**/*',
    },
  },
  images: {
    toolkit: {
      src: ['src/assets/toolkit/images/**/*', 'src/favicon.ico'],
      dest: 'dist/assets/toolkit/images',
      watch: 'src/assets/toolkit/images/**/*',
    },
  },
  templates: {
    watch: 'src/**/*.{html,md,json,yml}',
  },
  fonts: {
    toolkit: {
      src: 'src/assets/toolkit/fonts/**/*',
      dest: 'dist/assets/toolkit/fonts',
      watch: 'src/assets/toolkit/fonts/**/*',
    },
  },
  dest: 'dist',
};

// clean
gulp.task('clean', del.bind(null, [config.dest]));

// styles
gulp.task('styles:fabricator', () => {
  gulp.src(config.styles.fabricator.src)
  .pipe(sourcemaps.init())
  .pipe(sass().on('error', sass.logError))
  .pipe(prefix('last 1 version'))
  .pipe(gulpif(!config.dev, csso()))
  .pipe(rename('f.css'))
  .pipe(sourcemaps.write())
  .pipe(gulp.dest(config.styles.fabricator.dest))
  .pipe(gulpif(config.dev, reload({ stream: true })));
});

gulp.task('styles:toolkit', () => {
  gulp.src(config.styles.toolkit.src)
  .pipe(gulpif(config.dev, sourcemaps.init()))
  .pipe(sass({
    includePaths: './node_modules',
  }).on('error', sass.logError))
  .pipe(prefix('last 1 version'))
  .pipe(gulpif(!config.dev, csso()))
  .pipe(gulpif(config.dev, sourcemaps.write()))
  .pipe(gulp.dest(config.styles.toolkit.dest))
  .pipe(gulpif(config.dev, reload({ stream: true })));
});

gulp.task('styles', ['styles:fabricator', 'styles:toolkit']);

// scripts
const webpackConfig = require('./webpack.config')(config);

gulp.task('scripts', (done) => {
  webpack(webpackConfig, (err, stats) => {
    if (err) {
      gutil.log(gutil.colors.red(err()));
    }
    const result = stats.toJson();
    if (result.errors.length) {
      result.errors.forEach((error) => {
        gutil.log(gutil.colors.red(error));
      });
    }
    done();
  });
});

// fonts
gulp.task('fonts', () => {
  return gulp.src(config.fonts.toolkit.src)
    .pipe(gulp.dest(config.fonts.toolkit.dest));
});

gulp.task('favicon', () => {
  return gulp.src('src/favicon.ico')
  .pipe(gulp.dest(config.dest));
});

// images
gulp.task('images', ['favicon'], () => {
  return gulp.src(config.images.toolkit.src)
    .pipe(imagemin())
    .pipe(gulp.dest(config.images.toolkit.dest));
});

// assembler
gulp.task('assembler', (done) => {
  assembler({
    logErrors: config.dev,
    dest: config.dest,
  });
  done();
});

// server
gulp.task('serve', () => {

  browserSync({
    server: {
      baseDir: config.dest,
    },
    notify: false,
    logPrefix: 'FABRICATOR',
    open: false,
  });

  gulp.task('assembler:watch', ['assembler'], browserSync.reload);
  gulp.watch(config.templates.watch, ['assembler:watch']);

  gulp.task('styles:watch', ['styles']);
  gulp.watch([config.styles.fabricator.watch, config.styles.toolkit.watch], ['styles:watch']);

  gulp.task('scripts:watch', ['scripts'], browserSync.reload);
  gulp.watch([config.scripts.fabricator.watch, config.scripts.toolkit.watch], ['scripts:watch']);

  gulp.task('images:watch', ['images'], browserSync.reload);
  gulp.watch(config.images.toolkit.watch, ['images:watch']);

  gulp.task('fonts:watch', ['fonts'], browserSync.reload);
  gulp.watch(config.fonts.toolkit.watch, ['fonts:watch']);

});

// default build task
gulp.task('default', ['clean'], () => {

  // define build tasks
  const tasks = [
    'styles',
    'scripts',
    'images',
    'fonts',
    'assembler',
  ];

  // run build
  runSequence(tasks, () => {
    if (config.dev) {
      gulp.start('serve');
    }
  });

});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    jade = require('gulp-jade'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    minify = require('gulp-minify');

var templates = './src/templates/**/*.jade';
var styles = './src/sass/**/*.scss';
var images = [
  './img/**/*.jpg',
  './img/**/*.png'
];

gulp.task('templates', function() {
  gulp.src(templates)
    .pipe(jade())
    .pipe(minify())
    .pipe(gulp.dest('./build/'));
});

gulp.task('styles', function() {
  gulp.src(styles)
    .pipe(sass().on('error', sass.logError))
    .pipe(minify())
    .pipe(gulp.dest('./build/css/'));
});

gulp.task('images', function() {
  gulp.src(images)
    .pipe(gulp.dest('./build/img/'));
});

gulp.task('watch', function() {
  var sources = [templates, styles];
  gulp.src(sources)
    .pipe(watch(sources));
});

gulp.task('dev', function() {
  gulp.src(templates)
    .pipe(watch(templates, {verbose: true}))
    .pipe(jade())
    .pipe(gulp.dest('./build/'));
  gulp.src(styles)
    .pipe(watch(styles, {verbose: true}))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./build/css/'));
});

gulp.task('default', ['templates', 'styles', 'images']);
<commit_msg>Copy Bootstrap files to ./build<commit_after>var gulp = require('gulp'),
    jade = require('gulp-jade'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    minify = require('gulp-minify');

var templates = './src/templates/**/*.jade';
var styles = './src/sass/**/*.scss';
var images = [
  './img/**/*.jpg',
  './img/**/*.png'
];

gulp.task('templates', function() {
  gulp.src(templates)
    .pipe(jade())
    .pipe(minify())
    .pipe(gulp.dest('./build/'));
});

gulp.task('styles', function() {
  // Bootstrap base
  gulp.src('./lib/bootstrap-theme/dist/toolkit-startup.min.*')
    .pipe(gulp.dest('./build/css/'));
  gulp.src('./lib/bootstrap-theme/dist/toolkit.min.js*')
    .pipe(gulp.dest('./build/js/'));

  // Customisations
  gulp.src(styles)
    .pipe(sass().on('error', sass.logError))
    .pipe(minify())
    .pipe(gulp.dest('./build/css/'));
});

gulp.task('images', function() {
  gulp.src(images)
    .pipe(gulp.dest('./build/img/'));
});

gulp.task('watch', function() {
  var sources = [templates, styles];
  gulp.src(sources)
    .pipe(watch(sources));
});

gulp.task('dev', function() {
  gulp.src(templates)
    .pipe(watch(templates, {verbose: true}))
    .pipe(jade())
    .pipe(gulp.dest('./build/'));
  gulp.src(styles)
    .pipe(watch(styles, {verbose: true}))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./build/css/'));
});

gulp.task('default', ['templates', 'styles', 'images']);
<|endoftext|>


<commit_before>var gulp = require("gulp");

var sourcemaps = require("gulp-sourcemaps");

var sass = require("gulp-sass");
var autoprefixer = require("gulp-autoprefixer");
var plumber = require("gulp-plumber"); // Error handling for sass

var concat = require("gulp-concat");
var babel = require("gulp-babel");
var uglify = require("gulp-uglify");

var browserSync = require('browser-sync').create();

// SASS compilation and minification

gulp.task("sass", function() {
  gulp.src("./sass/main.sass")
    .pipe(sourcemaps.init())
    .pipe(plumber())
    .pipe(sass({outputStyle: "compressed"}))
    .pipe(sourcemaps.write())
    .pipe(autoprefixer({browsers: "last 5 versions"}))
    .pipe(gulp.dest("./dist"))
    .pipe(browserSync.reload({stream: true}));
});

// JS compilation and minification

gulp.task("js", function() {
  // Build all the scripts from a directory into a file.
  function buildScriptsForPage(dir, path) {
    gulp.src(dir+"/*.js")
      .pipe(sourcemaps.init())
      .pipe(babel({
        presets: ["es2015"]
      }))
      .pipe(concat(path))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest("./dist"))
      .pipe(browserSync.reload({stream: true}));
  }

  // Scripts for the front page
  buildScriptsForPage("js/home", "home.js");
  // Scrips for the "email sent" page
  buildScriptsForPage("js/emailsent", "emailsent.js");
});

// Compile everything at once
gulp.task("build", ["sass", "js"]);

// Watching

gulp.task("watch", ["build"], function() {
  gulp.watch("./sass/**/*.sass", ["sass"]);
  gulp.watch("./js/**/*.js", ["js"]);
});

// Serving

gulp.task('serve', function() {
  browserSync.init({
    server: {
      baseDir: '.'
    },
  });
  gulp.watch(
    ["./*.html", "./dist/**/*.js"],
    browserSync.reload
  );
});

gulp.task("default", ["watch", "serve"]);
<commit_msg>gulpfile to ES6<commit_after>const gulp = require("gulp");

const sourcemaps = require("gulp-sourcemaps");

const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const plumber = require("gulp-plumber"); // Error handling for sass

const concat = require("gulp-concat");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");

const browserSync = require("browser-sync").create();

// SASS compilation and minification

gulp.task("sass", () => {
  gulp.src("./sass/main.sass")
    .pipe(sourcemaps.init())
    .pipe(plumber())
    .pipe(sass({outputStyle: "compressed"}))
    .pipe(sourcemaps.write())
    .pipe(autoprefixer({browsers: "last 5 versions"}))
    .pipe(gulp.dest("./dist"))
    .pipe(browserSync.reload({stream: true}));
});

// JS compilation and minification

gulp.task("js", () => {
  // Build all the scripts from a directory into a file.
  function buildScriptsForPage(dir, path) {
    gulp.src(dir + "/*.js")
      .pipe(sourcemaps.init())
      .pipe(babel({
        presets: ["es2015"]
      }))
      .pipe(concat(path))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest("./dist"))
      .pipe(browserSync.reload({stream: true}));
  }

  // Scripts for the front page
  buildScriptsForPage("js/home", "home.js");
  // Scrips for the "email sent" page
  buildScriptsForPage("js/emailsent", "emailsent.js");
});

// Compile everything at once
gulp.task("build", ["sass", "js"]);

// Watching

gulp.task("watch", ["build"], () => {
  gulp.watch("./sass/**/*.sass", ["sass"]);
  gulp.watch("./js/**/*.js", ["js"]);
});

// Serving

gulp.task("serve", () => {
  browserSync.init({
    server: {
      baseDir: "."
    }
  });
  gulp.watch(
    ["./*.html", "./dist/**/*.js"],
    browserSync.reload
  );
});

gulp.task("default", ["watch", "serve"]);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')({camelize: true});
var del = require('del');

var currentPath = __dirname;
var config = require('./config.js');

// =============================================================================
// Main tasks
// =============================================================================
gulp.task('watch', ['front:watch', 'server:watch', 'server:nodemon']);

gulp.task('assets:build', ['assets:images-build', 'assets:fonts-build', 'assets:vendorlocal-build']);
gulp.task('assets:clean', ['assets:images-clean', 'assets:fonts-clean', 'assets:vendorlocal-clean']);

gulp.task('front:build', ['front:css-build', 'front:js-build']);
gulp.task('front:watch', ['front:css-watch', 'front:js-watch']);
gulp.task('front:clean', ['front:css-clean', 'front:js-clean']);

gulp.task('server:build', ['server:es6']);
gulp.task('server:watch', ['server:es6-watch']);
gulp.task('server:clean', ['server:es6-clean']);

// =============================================================================
// Style teasks
// =============================================================================
gulp.task('front:css-build', function() {
  var src = config.paths.style.src;
  var dist = config.paths.style.dist;
  return gulp.src(src + '/*.less', { base : src })
    .pipe($.less(config.compilation.style))
    .pipe($.autoprefixer(config.compilation.autoprefixer))
    .pipe(gulp.dest(dist));
});
gulp.task('front:css-watch', function() {
  var src = config.paths.style.src;
  gulp.watch(src + '/**/*.less', ['front:css-build']);
});
gulp.task('front:css-clean', function(cb) {
  var dist = config.paths.style.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Js tasks
// =============================================================================
gulp.task('front:js-build', function() {
  var src= config.paths.js.src;
  var dist= config.paths.js.dist;
  return gulp.src(src + '/*.js', { base : src })
    .pipe($.babel(config.compilation.babel))
    .pipe(
      $.browserify(config.compilation.browserify)
      .on('error', function(err) {
          console.error('js browserify error: ' + err.message);
          this.emit('end');
      })
    )
    .pipe($.uglify(config.compilation.uglify))
    .pipe(gulp.dest(dist));
});
gulp.task('front:js-watch', function() {
  var src= config.paths.js.src;
  gulp.watch(src + '/**/*.js', ['front:js-build']);
});

gulp.task('front:js-clean', function(cb) {
  var dist= config.paths.js.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Browsersync
// =============================================================================
gulp.task('browsersync', function() {
  setTimeout( function() {
    var browserSync = require('browser-sync');
    browserSync.create();
    browserSync.init(config.dev.browsersync);

    gulp.watch([
      config.paths.js.dist + '/**/*.js',
      config.paths.style.dist + '/**/*.css',
      config.paths.views.src + '/**/*.html'
    ]).on('change', browserSync.reload);
  }, 2000);
});

// =============================================================================
// Assets
// =============================================================================
gulp.task('assets:images-build', function() {
  var src= config.paths.assets.src;
  var dist= config.paths.assets.dist;
  return gulp.src(src + '/**/*', { base : src })
    .pipe($.imagemin(config.compilation.images))
    .pipe(gulp.dest(dist));
});
gulp.task('assets:images-clean', function(cb) {
  var dist= config.paths.assets.dist;
  del(dist + '/**/*', cb);
});

gulp.task('assets:vendorlocal-build', function() {
  var src= config.paths.vendorlocal.src;
  var dist= config.paths.vendorlocal.dist;
  return gulp.src(src + '/**/*', { base : src })
    .pipe(gulp.dest(dist));
});
gulp.task('assets:vendorlocal-clean', function(cb) {
  var dist= config.paths.vendorlocal.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Fonts
// =============================================================================
gulp.task('assets:fonts-build', function() {
  var src= config.paths.fonts.src;
  var dist= config.paths.fonts.dist;
  return gulp.src(src + '/**/*')
    .pipe(gulp.dest(dist));
});
gulp.task('assets:fonts-clean', function(cb) {
  var dist= config.paths.fonts.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Server
// =============================================================================
gulp.task('server:es6', function() {
  var src= config.paths.server.src;
  var dist= config.paths.server.dist;
  return gulp.src(src + '/**/*.js')
    .pipe($.babel(config.compilation.server.babel))
    .pipe(gulp.dest(dist));

});
gulp.task('server:es6-watch', function(fileStatus) {
  var src= config.paths.server.src;
  var dist= config.paths.server.dist;

  return gulp.watch(src + '/**/*.js', function(fileStatus) {
    console.log('[ES6 watcher] ' + fileStatus.path.replace(currentPath, '') + ' (' + fileStatus.type + ') ' + ' => transpile it into ' + dist.replace(currentPath, ''));
    return gulp.src(fileStatus.path, { base : src })
      .pipe($.babel(config.compilation.server.babel))
      .pipe(gulp.dest(dist));
  });
});
gulp.task('server:es6-clean', function(cb) {
  var dist= config.paths.server.dist;
  del(dist + '/**/*', cb);
});

gulp.task('server:nodemon', function() {
  var dist= config.paths.server.dist;
  $.nodemon({
    script: dist + 'site.js',
    ext: 'js html',
    verbose: false,
    watch: [
      dist + '**/*.js'
    ],
    delay: 150,
  })
  .on('restart', function (files) {
    var filesStr = files ? 'Files changed: ' + files.join(', ') : 'user request';
    filesStr = filesStr.replace(currentPath, '');
    console.log('[Server restarted]', filesStr);
  });
});
<commit_msg>Less compilation does not break gulp anymore<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')({camelize: true});
var del = require('del');

var currentPath = __dirname;
var config = require('./config.js');

// =============================================================================
// Main tasks
// =============================================================================
gulp.task('watch', ['front:watch', 'server:watch', 'server:nodemon']);

gulp.task('assets:build', ['assets:images-build', 'assets:fonts-build', 'assets:vendorlocal-build']);
gulp.task('assets:clean', ['assets:images-clean', 'assets:fonts-clean', 'assets:vendorlocal-clean']);

gulp.task('front:build', ['front:css-build', 'front:js-build']);
gulp.task('front:watch', ['front:css-watch', 'front:js-watch']);
gulp.task('front:clean', ['front:css-clean', 'front:js-clean']);

gulp.task('server:build', ['server:es6']);
gulp.task('server:watch', ['server:es6-watch']);
gulp.task('server:clean', ['server:es6-clean']);

// =============================================================================
// Style teasks
// =============================================================================
gulp.task('front:css-build', function() {
  var src = config.paths.style.src;
  var dist = config.paths.style.dist;
  return gulp.src(src + '/*.less', { base : src })
    .pipe(
      $.less(config.compilation.style)
      .on('error', function(err) {
        console.error('Less compilation error: ' + err.message);
        this.emit('end');
      })
    )
    .pipe($.autoprefixer(config.compilation.autoprefixer))
    .pipe(gulp.dest(dist));
});
gulp.task('front:css-watch', function() {
  var src = config.paths.style.src;
  gulp.watch(src + '/**/*.less', ['front:css-build']);
});
gulp.task('front:css-clean', function(cb) {
  var dist = config.paths.style.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Js tasks
// =============================================================================
gulp.task('front:js-build', function() {
  var src= config.paths.js.src;
  var dist= config.paths.js.dist;
  return gulp.src(src + '/*.js', { base : src })
    .pipe($.babel(config.compilation.babel))
    .pipe(
      $.browserify(config.compilation.browserify)
      .on('error', function(err) {
          console.error('js browserify error: ' + err.message);
          this.emit('end');
      })
    )
    .pipe($.uglify(config.compilation.uglify))
    .pipe(gulp.dest(dist));
});
gulp.task('front:js-watch', function() {
  var src= config.paths.js.src;
  gulp.watch(src + '/**/*.js', ['front:js-build']);
});

gulp.task('front:js-clean', function(cb) {
  var dist= config.paths.js.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Browsersync
// =============================================================================
gulp.task('browsersync', function() {
  setTimeout( function() {
    var browserSync = require('browser-sync');
    browserSync.create();
    browserSync.init(config.dev.browsersync);

    gulp.watch([
      config.paths.js.dist + '/**/*.js',
      config.paths.style.dist + '/**/*.css',
      config.paths.views.src + '/**/*.html'
    ]).on('change', browserSync.reload);
  }, 2000);
});

// =============================================================================
// Assets
// =============================================================================
gulp.task('assets:images-build', function() {
  var src= config.paths.assets.src;
  var dist= config.paths.assets.dist;
  return gulp.src(src + '/**/*', { base : src })
    .pipe($.imagemin(config.compilation.images))
    .pipe(gulp.dest(dist));
});
gulp.task('assets:images-clean', function(cb) {
  var dist= config.paths.assets.dist;
  del(dist + '/**/*', cb);
});

gulp.task('assets:vendorlocal-build', function() {
  var src= config.paths.vendorlocal.src;
  var dist= config.paths.vendorlocal.dist;
  return gulp.src(src + '/**/*', { base : src })
    .pipe(gulp.dest(dist));
});
gulp.task('assets:vendorlocal-clean', function(cb) {
  var dist= config.paths.vendorlocal.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Fonts
// =============================================================================
gulp.task('assets:fonts-build', function() {
  var src= config.paths.fonts.src;
  var dist= config.paths.fonts.dist;
  return gulp.src(src + '/**/*')
    .pipe(gulp.dest(dist));
});
gulp.task('assets:fonts-clean', function(cb) {
  var dist= config.paths.fonts.dist;
  del(dist + '/**/*', cb);
});

// =============================================================================
// Server
// =============================================================================
gulp.task('server:es6', function() {
  var src= config.paths.server.src;
  var dist= config.paths.server.dist;
  return gulp.src(src + '/**/*.js')
    .pipe($.babel(config.compilation.server.babel))
    .pipe(gulp.dest(dist));

});
gulp.task('server:es6-watch', function(fileStatus) {
  var src= config.paths.server.src;
  var dist= config.paths.server.dist;

  return gulp.watch(src + '/**/*.js', function(fileStatus) {
    console.log('[ES6 watcher] ' + fileStatus.path.replace(currentPath, '') + ' (' + fileStatus.type + ') ' + ' => transpile it into ' + dist.replace(currentPath, ''));
    return gulp.src(fileStatus.path, { base : src })
      .pipe($.babel(config.compilation.server.babel))
      .pipe(gulp.dest(dist));
  });
});
gulp.task('server:es6-clean', function(cb) {
  var dist= config.paths.server.dist;
  del(dist + '/**/*', cb);
});

gulp.task('server:nodemon', function() {
  var dist= config.paths.server.dist;
  $.nodemon({
    script: dist + 'site.js',
    ext: 'js html',
    verbose: false,
    watch: [
      dist + '**/*.js'
    ],
    delay: 150,
  })
  .on('restart', function (files) {
    var filesStr = files ? 'Files changed: ' + files.join(', ') : 'user request';
    filesStr = filesStr.replace(currentPath, '');
    console.log('[Server restarted]', filesStr);
  });
});
<|endoftext|>