<commit_before>var gulp = require('gulp');
var webserver = require('gulp-webserver'); // https://www.npmjs.com/package/gulp-webserver
var inject = require('gulp-inject'); // https://www.npmjs.com/package/gulp-inject
var util = require('gulp-util'); // https://www.npmjs.com/package/gulp-util
var debug = require('gulp-debug'); // https://www.npmjs.com/package/gulp-debug
var jshint = require('gulp-jshint'); // https://github.com/spalger/gulp-jshint
var jscs = require('gulp-jscs'); // https://github.com/jscs-dev/gulp-jscs
var map = require('map-stream'); // https://github.com/dominictarr/map-stream
var yargs = require('yargs').argv; // https://www.npmjs.com/package/yargs
var gulpif = require('gulp-if'); // https://github.com/robrich/gulp-if
var annotate = require('gulp-ng-annotate'); // https://www.npmjs.com/package/gulp-ng-annotate
var filter = require('gulp-filter'); // https://www.npmjs.com/package/gulp-filter
var uglify = require('gulp-uglify'); // https://github.com/terinjokes/gulp-uglify
var useref = require('gulp-useref'); // https://www.npmjs.com/package/gulp-useref
var minify = require('gulp-minify-css'); // https://www.npmjs.com/package/gulp-minify-css
var imagemin = require('gulp-imagemin'); // https://github.com/sindresorhus/gulp-imagemin
var listing = require('gulp-task-listing'); // https://www.npmjs.com/package/gulp-task-listing
var templatecache = require('gulp-angular-templatecache'); // https://www.npmjs.com/package/gulp-angular-templatecache
var htmlmin = require('gulp-htmlmin'); // https://github.com/jonschlinkert/gulp-htmlmin
var config = require('./gulp.config.js');
var runsequence = require('run-sequence'); // https://www.npmjs.com/package/run-sequence

/**
 * Prepares everything to serve the development build
 */
gulp.task('serve', ['inject', 'webserver', 'watchers'], function() {
    util.log(util.colors.bgBlue('Serving Development'));
});

/**
 * Starts a webserver to launch the development build
 */
gulp.task('webserver', ['dev-settings'], function() {
    gulp.src(config.root)
        .pipe(webserver({
            // https://github.com/schickling/gulp-webserver
            // http://stephenradford.me/gulp-angularjs-and-html5mode/
            fallback: config.index,
            livereload: true,
            open: true
        }));
});

/**
 * Launch a webserver to serve the production build
 */
gulp.task('serve-production', ['build'], function() {
    util.log(util.colors.bgBlue('Serving Production Build'));
    gulp.src(config.build)
        .pipe(webserver({
            // https://github.com/schickling/gulp-webserver
            // http://stephenradford.me/gulp-angularjs-and-html5mode/
            fallback: config.index,
            livereload: true,
            open: true
        }));
});

/**
 * Watcher setup, watch for changes in js, css and html files
 * ignore changes to the templates.js file since it is auto-generated
 *
 *  @bug when adding folders gulp might crash, at least in linux
 *  the problem seems to be with gaze, and has no easy solution
 */
gulp.task('watchers', function(){
    util.log(util.colors.bgBlue('Setting Up Watchers'));
    gulp.watch([config.jsfiles, config.cssfiles, config.htmlfiles, '!/app/core/templates.js'], ['html-inject']);
    gulp.watch([config.checkfiles], ['check']);
    // we could set up here a watcher for the bower files, but that means the task
    // will run twice on install, and none on uninstall since there appears
    // to be some issues with the watch task and also with the gaze dependency
    // so we decided to go back and use bower hooks, unfortunately bower does not
    // have a postuninstall hook, so we are f... well, i've discover that it supports preuninstall
    // so we are going that route, see the .bowerrc file
});

/*
 * Injects css and js files in index.html file
 */
gulp.task('inject', function(){
    return runsequence('bower-html-inject', 'html-inject');
});

/**
 *  Read the index.html file and inject css and js files using gulp-inject
 */
gulp.task('html-inject', ['templatecache'], function() {
    // gulp util uses chalk, see reference
    // https://github.com/chalk/chalk
    util.log(util.colors.bgBlue('Custom Code HTML Inject'));
    return gulp
.src(config.index)
        // gulp src options: https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpsrcglobs-options
        // we do not need to read the file content, all we need here are the paths
        // gulp inject options: https://github.com/klei/gulp-inject#optionsrelative
.pipe(inject(gulp.src(config.jsfiles.concat(config.cssfiles), {read: false}), {relative: false, addRootSlash: false}))
.pipe(gulp.dest(config.root));
});

/**
 *  Uses Wiredep to read dependencies from bower.json file
 *  and inject them in the index.html file
 *  this task is also called by the hooks defined in .bowerrc
 */
gulp.task('bower-html-inject', function() {
    util.log(util.colors.bgBlue('Bower Dependencies HTML Inject'));
    var wiredep = require('wiredep').stream;

    var options = {
        bowerJson: require(config.bowerjson),
        directory: config.libs
    };

    return gulp
   .src(config.index)
   .pipe(wiredep(options))
   .pipe(gulp.dest(config.root));
});

/**
 * Lints JavaScript code and enforces coding style. Rules are
 * defined in .jshintrc and .jscsrc respectively
 */
gulp.task('check', function(){
    runsequence('check-jshint', 'check-jscs');
});

/**
 * Code linting using jshint
 */
gulp.task('check-jshint', function() {
    util.log(util.colors.bgBlue('Code check using JSHint'));
    return gulp
   .src(config.checkfiles)
   .pipe(jshint())
   .pipe(jshint.reporter('jshint-stylish'), {verbose: true}) //stylish reporter https://github.com/sindresorhus/jshint-stylish
   .pipe(JSHintBeepReporter());
});

/**
 * Custom jshint reporterer
 *
 * This will beep to warn about jshint fails
 */
var JSHintBeepReporter = function(file, cb) {
    return map(function (file, cb) {
        if (!file.jshint.success) {
            util.beep();
        }
        cb(null, file);
    })
};

/**
 * Check code style using jscs
 */
gulp.task('check-jscs', function() {
    util.log(util.colors.bgBlue('Code check using JSCS'));
    return gulp
   .src(config.checkfiles)
   .pipe(jscs())
   .pipe(jscs.reporter())
   .pipe(JSCSBeepReporter());
});

/**
 * Custom jscs reporterer
 *
 * This will beep to warn about jscs fails
 */
var JSCSBeepReporter = function () {
    return map(function (file) {
        if (!file.jscs.success) {
            util.beep();
        }
    });
};

/**
 * Creates a build to prepare the app for production
 * reads the index.html and picks the required css and js
 * files using useref
 */
gulp.task('build', ['inject', 'images', 'icons', 'production-settings'], function() {
    util.log(util.colors.bgBlue('Building App for Production'));
    return gulp
    .src(config.index)
    .pipe(useref())
    .pipe(gulpif('*.js', annotate()))
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.css', minify()))
    // the index.html minification step must be the last one since the useref plugin
    // depends on the comments to know where to find and inject files
    .pipe(gulpif('index.html', htmlmin({collapseWhitespace: true, removeComments: true})))
    .pipe(gulp.dest(config.build));
});

/**
 * Compresses images and copies them to the build folder
 */
gulp.task('images', function() {
    util.log(util.colors.bgBlue('Compressing and Copying Images to Build Folder'));
    return gulp
   .src(config.images)
   .pipe(imagemin())
   .pipe(gulp.dest(config.build + 'images'));
});

/**
 * Copies icons to build folder
 */
gulp.task('icons', function() {
    var dest = config.build + 'content/icons';
    util.log(util.colors.bgBlue('Copying Icons to Build Folder'));
    return gulp
        .src(config.icons)
        .pipe(gulp.dest(dest));
});

/**
 * Copies development settings file to app folder
 */
gulp.task('dev-settings',function(){
    util.log(util.colors.bgBlue('Copying Development Settings File'));
    return gulp
   .src('dist/angular/development/settings.js')
   .pipe(gulp.dest(config.core));
});

/**
 * Copies production settings file to app folder
 */
gulp.task('production-settings',function(){
    util.log(util.colors.bgBlue('Copying Production Settings File'));
    return gulp
   .src('dist/angular/production/settings.js')
   .pipe(gulp.dest(config.core));
});

/**
 * Creates $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    util.log(util.colors.bgBlue('Create an Angular Template Cache'));
    return gulp
        .src(config.htmlfiles)
        // http://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(config.core));
});

/**
 * Lists all available tasks
 * @todo customize list by overring filters
 * By default, is is defined as the regular expression /[-_:]/
 * which means that any task with a hyphen, underscore, or colon in it's name is assumed to be a subtask
 */
gulp.task('help', listing);

/**
 * Sets up the default task, this just calls the help task
 */
gulp.task('default', ['help']);
<commit_msg>Fixed JSCS warnings for gulpfile file<commit_after>var gulp = require('gulp');
var webserver = require('gulp-webserver'); // https://www.npmjs.com/package/gulp-webserver
var inject = require('gulp-inject'); // https://www.npmjs.com/package/gulp-inject
var util = require('gulp-util'); // https://www.npmjs.com/package/gulp-util
var debug = require('gulp-debug'); // https://www.npmjs.com/package/gulp-debug
var jshint = require('gulp-jshint'); // https://github.com/spalger/gulp-jshint
var jscs = require('gulp-jscs'); // https://github.com/jscs-dev/gulp-jscs
var map = require('map-stream'); // https://github.com/dominictarr/map-stream
var yargs = require('yargs').argv; // https://www.npmjs.com/package/yargs
var gulpif = require('gulp-if'); // https://github.com/robrich/gulp-if
var annotate = require('gulp-ng-annotate'); // https://www.npmjs.com/package/gulp-ng-annotate
var filter = require('gulp-filter'); // https://www.npmjs.com/package/gulp-filter
var uglify = require('gulp-uglify'); // https://github.com/terinjokes/gulp-uglify
var useref = require('gulp-useref'); // https://www.npmjs.com/package/gulp-useref
var minify = require('gulp-minify-css'); // https://www.npmjs.com/package/gulp-minify-css
var imagemin = require('gulp-imagemin'); // https://github.com/sindresorhus/gulp-imagemin
var listing = require('gulp-task-listing'); // https://www.npmjs.com/package/gulp-task-listing
var templatecache = require('gulp-angular-templatecache'); // https://www.npmjs.com/package/gulp-angular-templatecache
var htmlmin = require('gulp-htmlmin'); // https://github.com/jonschlinkert/gulp-htmlmin
var config = require('./gulp.config.js');
var runsequence = require('run-sequence'); // https://www.npmjs.com/package/run-sequence

/**
 * Prepares everything to serve the development build
 */
gulp.task('serve', ['inject', 'webserver', 'watchers'], function() {
    util.log(util.colors.bgBlue('Serving Development'));
});

/**
 * Starts a webserver to launch the development build
 */
gulp.task('webserver', ['dev-settings'], function() {
    gulp.src(config.root)
        .pipe(webserver({
            // https://github.com/schickling/gulp-webserver
            // http://stephenradford.me/gulp-angularjs-and-html5mode/
            fallback: config.index,
            livereload: true,
            open: true
        }));
});

/**
 * Launch a webserver to serve the production build
 */
gulp.task('serve-production', ['build'], function() {
    util.log(util.colors.bgBlue('Serving Production Build'));
    gulp.src(config.build)
        .pipe(webserver({
            // https://github.com/schickling/gulp-webserver
            // http://stephenradford.me/gulp-angularjs-and-html5mode/
            fallback: config.index,
            livereload: true,
            open: true
        }));
});

/**
 * Watcher setup, watch for changes in js, css and html files
 * ignore changes to the templates.js file since it is auto-generated
 *
 *  @bug when adding folders gulp might crash, at least in linux
 *  the problem seems to be with gaze, and has no easy solution
 */
gulp.task('watchers', function() {
    util.log(util.colors.bgBlue('Setting Up Watchers'));
    gulp.watch([
        config.jsfiles,
        config.cssfiles,
        config.htmlfiles,
        '!/app/core/templates.js'
    ], ['html-inject']);
    gulp.watch([config.checkfiles], ['check']);
    // we could set up here a watcher for the bower files, but that means the task
    // will run twice on install, and none on uninstall since there appears
    // to be some issues with the watch task and also with the gaze dependency
    // so we decided to go back and use bower hooks, unfortunately bower does not
    // have a postuninstall hook, so we are f... well, i've discover that it supports preuninstall
    // so we are going that route, see the .bowerrc file
});

/*
 * Injects css and js files in index.html file
 */
gulp.task('inject', function() {
    return runsequence('bower-html-inject', 'html-inject');
});

/**
 *  Read the index.html file and inject css and js files using gulp-inject
 */
gulp.task('html-inject', ['templatecache'], function() {
    // gulp util uses chalk, see reference
    // https://github.com/chalk/chalk
    util.log(util.colors.bgBlue('Custom Code HTML Inject'));
    return gulp
.src(config.index)
        // gulp src options: https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpsrcglobs-options
        // we do not need to read the file content, all we need here are the paths
        // gulp inject options: https://github.com/klei/gulp-inject#optionsrelative
.pipe(inject(gulp.src(config.jsfiles.concat(config.cssfiles), {
            read: false
        }), {
            relative: false,
            addRootSlash: false
        }))
.pipe(gulp.dest(config.root));
});

/**
 *  Uses Wiredep to read dependencies from bower.json file
 *  and inject them in the index.html file
 *  this task is also called by the hooks defined in .bowerrc
 */
gulp.task('bower-html-inject', function() {
    util.log(util.colors.bgBlue('Bower Dependencies HTML Inject'));
    var wiredep = require('wiredep').stream;

    var options = {
        bowerJson: require(config.bowerjson),
        directory: config.libs
    };

    return gulp
   .src(config.index)
   .pipe(wiredep(options))
   .pipe(gulp.dest(config.root));
});

/**
 * Lints JavaScript code and enforces coding style. Rules are
 * defined in .jshintrc and .jscsrc respectively
 */
gulp.task('check', function() {
    runsequence('check-jshint', 'check-jscs');
});

/**
 * Code linting using jshint
 */
gulp.task('check-jshint', function() {
    util.log(util.colors.bgBlue('Code check using JSHint'));
    return gulp
   .src(config.checkfiles)
   .pipe(jshint())
   .pipe(jshint.reporter('jshint-stylish'), {verbose: true}) //stylish reporter https://github.com/sindresorhus/jshint-stylish
   .pipe(JSHintBeepReporter());
});

/**
 * Custom jshint reporterer
 *
 * This will beep to warn about jshint fails
 */
var JSHintBeepReporter = function(file, cb) {
    return map(function (file, cb) {
        if (!file.jshint.success) {
            util.beep();
        }
        cb(null, file);
    })
};

/**
 * Check code style using jscs
 */
gulp.task('check-jscs', function() {
    util.log(util.colors.bgBlue('Code check using JSCS'));
    return gulp
   .src(config.checkfiles)
   .pipe(jscs())
   .pipe(jscs.reporter())
   .pipe(JSCSBeepReporter());
});

/**
 * Custom jscs reporterer
 *
 * This will beep to warn about jscs fails
 */
var JSCSBeepReporter = function () {
    return map(function (file) {
        if (!file.jscs.success) {
            util.beep();
        }
    });
};

/**
 * Creates a build to prepare the app for production
 * reads the index.html and picks the required css and js
 * files using useref
 */
gulp.task('build', ['inject', 'images', 'icons', 'production-settings'], function() {
    util.log(util.colors.bgBlue('Building App for Production'));
    return gulp
    .src(config.index)
    .pipe(useref())
    .pipe(gulpif('*.js', annotate()))
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.css', minify()))
    // the index.html minification step must be the last one since the useref plugin
    // depends on the comments to know where to find and inject files
    .pipe(gulpif('index.html', htmlmin({collapseWhitespace: true, removeComments: true})))
    .pipe(gulp.dest(config.build));
});

/**
 * Compresses images and copies them to the build folder
 */
gulp.task('images', function() {
    util.log(util.colors.bgBlue('Compressing and Copying Images to Build Folder'));
    return gulp
   .src(config.images)
   .pipe(imagemin())
   .pipe(gulp.dest(config.build + 'images'));
});

/**
 * Copies icons to build folder
 */
gulp.task('icons', function() {
    var dest = config.build + 'content/icons';
    util.log(util.colors.bgBlue('Copying Icons to Build Folder'));
    return gulp
        .src(config.icons)
        .pipe(gulp.dest(dest));
});

/**
 * Copies development settings file to app folder
 */
gulp.task('dev-settings',function() {
    util.log(util.colors.bgBlue('Copying Development Settings File'));
    return gulp
   .src('dist/angular/development/settings.js')
   .pipe(gulp.dest(config.core));
});

/**
 * Copies production settings file to app folder
 */
gulp.task('production-settings',function() {
    util.log(util.colors.bgBlue('Copying Production Settings File'));
    return gulp
   .src('dist/angular/production/settings.js')
   .pipe(gulp.dest(config.core));
});

/**
 * Creates $templateCache from the html templates
 */
gulp.task('templatecache', function() {
    util.log(util.colors.bgBlue('Create an Angular Template Cache'));
    return gulp
        .src(config.htmlfiles)
        // http://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(templatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(config.core));
});

/**
 * Lists all available tasks
 * @todo customize list by overring filters
 * By default, is is defined as the regular expression /[-_:]/
 * which means that any task with a hyphen, underscore, or colon in it's name is assumed to be a subtask
 */
gulp.task('help', listing);

/**
 * Sets up the default task, this just calls the help task
 */
gulp.task('default', ['help']);
<|endoftext|>


<commit_before>/* eslint-disable no-console */

const autoprefixer = require('autoprefixer');
const fs = require('fs');
const gulp = require('gulp');
const babel = require('gulp-babel');
const changed = require('gulp-changed-smart');
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const gulpCount = require('gulp-count');
const gulpErrorHandler = require('gulp-error-handle');
const filelog = require('gulp-filelog');
const header = require('gulp-header');
const gulpif = require('gulp-if');
const optimizejs = require('gulp-optimize-js');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const cssvariables = require('postcss-css-variables');
const rimraf = require('gulp-rimraf');
const sass = require('gulp-sass');
const sassGrapher = require('gulp-sass-grapher');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const path = require('path');
const named = require('vinyl-named');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const nodemon = require('gulp-nodemon');
const browserSync = require('browser-sync');
const webpackConfig = require('./webpack.config');

const baseScripts = [
	'./static/scripts/jquery/jquery.min.js',
	'./static/scripts/jquery/jquery.serialize-object.js',
	'./static/scripts/tether/tether.min.js',
	'./static/scripts/bootstrap/bootstrap.min.js',
	'./static/scripts/chosen/chosen.jquery.min.js',
	'./static/scripts/base.js',
	'./static/scripts/toggle/bootstrap-toggle.min.js',
	'./static/scripts/mailchimp/mailchimp.js',
	'./static/scripts/qrcode/kjua-0.1.1.min.js',
	'./static/scripts/ajaxconfig.js',
];

function themeName() {
	return process.env.SC_THEME || 'default';
}

const EXIT_ON_ERROR = process.env.GULP_EXIT_ON_ERROR
	? process.env.GULP_EXIT_ON_ERROR === 'true'
	: process.env.NODE_ENV !== 'development';

const nonBaseScripts = [
	'./static/scripts/**/*.js',
].concat(baseScripts.map(script => `!${script}`));
// used by almost all gulp tasks instead of gulp.src(...)
// plumber prevents pipes from stopping when errors occur
// changed only passes on files that were modified since last time
// filelog logs and counts all processed files

function withTheme(src) {
	if (typeof src === 'string') {
		return [src, `./theme/${themeName()}/${src.slice(2)}`];
	}
	return src.concat(src
		.map(e => `./theme/${themeName()}/${e.slice(2)}`));
}

const handleError = (error) => {
	console.error(error);
	process.exit(1);
};

const beginPipe = src => gulp
	.src(withTheme(src))
	.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
	.pipe(changed(gulp))
	.pipe(filelog());

const beginPipeAll = src => gulp
	.src(withTheme(src))
	.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
	.pipe(filelog());

// copy images
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('images', () => gulp
	.src(withTheme('./static/images/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/images`)));

// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other', () => gulp
	.src(withTheme('./static/other/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/other`)));

// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other-with-theme', ['other'], () => gulp
	.src(withTheme('./static/other/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/other`)));

const loadPaths = path.resolve('./static/styles/');
sassGrapher.init('./static/styles/', {
	loadPaths,
});
let firstRun = true;
gulp.task('styles', () => {
	const themeFile = `./theme/${themeName()}/style.scss`;
	return beginPipe('./static/styles/**/*.{css,sass,scss}')
		.pipe(gulpif(!firstRun, sassGrapher.ancestors()))
		.pipe(header(fs.readFileSync(themeFile, 'utf8')))
		.pipe(filelog('PROCESS: '))
		.pipe(sourcemaps.init())
		.pipe(sass({
			sourceMap: true,
			includePaths: ['node_modules'],
		}).on('error', handleError))
		.pipe(postcss([
			cssvariables({
				preserve: true,
			}),
			autoprefixer({
				browsers: ['> 1%', 'not dead'],
			}),
		]))
		.pipe(cleanCSS({
			compatibility: 'ie9',
		}))
		.pipe(sourcemaps.write('./sourcemaps'))
		.pipe(gulp.dest(`./build/${themeName()}/styles`))
		.pipe(browserSync.stream());
});

gulp.task('styles-done', ['styles'], () => {
	firstRun = false;
});

// copy fonts
gulp.task('fonts', () => beginPipe('./static/fonts/**/*.*')
	.pipe(gulp.dest(`./build/${themeName()}/fonts`)));

// copy static assets
gulp.task('static', () => beginPipe('./static/*')
	.pipe(gulp.dest(`./build/${themeName()}/`)));

// compile/transpile JSX and ES6 to ES5 and minify scripts
gulp.task('scripts', () => beginPipeAll(nonBaseScripts)
	.pipe(
		named((file) => {
			// As a preparation for webpack stream: Transform nonBaseScripts paths
			// e.g. '/static/scripts/schics/schicEdit.blub.min.js' -> 'schics/schicEdit.blub.min'
			const initialPath = file.history[0].split('scripts')[1];
			const pathSegments = initialPath.split('.');
			const concretePath = pathSegments
				.slice(0, pathSegments.length - 1)
				.join('.');
			const fileName = concretePath
				.split('')
				.slice(1)
				.join('');

			return fileName;
		}),
	)
	.pipe(webpackStream(webpackConfig, webpack))
	.pipe(gulp.dest(`./build/${themeName()}/scripts`))
	.pipe(browserSync.stream()));

// compile/transpile JSX and ES6 to ES5, minify and concatenate base scripts into all.js
gulp.task('base-scripts', () => beginPipeAll(baseScripts)
	.pipe(gulpCount('## js-files selected'))
	.pipe(babel({
		presets: [
			[
				'@babel/preset-env',
				{
					modules: false,
					targets: '> 1%, not dead',
				},
			],
		],
	}))
	.pipe(optimizejs())
	.pipe(uglify())
	.pipe(concat('all.js'))
	.pipe(gulp.dest(`./build/${themeName()}/scripts`)));

// compile vendor SASS/SCSS to CSS and minify it
gulp.task('vendor-styles', () => beginPipe('./static/vendor/**/*.{css,sass,scss}')
	.pipe(sourcemaps.init())
	.pipe(sass({
		sourceMap: true,
	}))
	.pipe(postcss([
		autoprefixer({
			browsers: ['> 1%', 'not dead'],
		}),
	]))
	.pipe(cleanCSS({
		compatibility: 'ie9',
	}))
	.pipe(sourcemaps.write('./sourcemaps'))
	.pipe(gulp.dest(`./build/${themeName()}/vendor`))
	.pipe(browserSync.stream()));

// compile/transpile vendor JSX and ES6 to ES5 and minify scripts
gulp.task('vendor-scripts', () => beginPipe('./static/vendor/**/*.js')
	.pipe(babel({
		compact: false,
		presets: [
			[
				'@babel/preset-env',
				{
					modules: false,
					targets: '> 1%, not dead',
				},
			],
		],
		plugins: ['@babel/plugin-transform-react-jsx'],
	}))
	.pipe(optimizejs())
	.pipe(uglify())
	.pipe(gulp.dest(`./build/${themeName()}/vendor`)));

// copy other vendor files
gulp.task('vendor-assets', () => beginPipe([
	'./static/vendor/**/*.*',
	'!./static/vendor/**/*.js',
	'!./static/vendor/**/*.{css,sass,scss}',
]).pipe(gulp.dest(`./build/${themeName()}/vendor`)));

// copy vendor-optimized files
gulp.task('vendor-optimized-assets', () => beginPipe(['./static/vendor-optimized/**/*.*'])
	.pipe(gulp.dest(`./build/${themeName()}/vendor-optimized`)));

// copy node modules
const nodeModules = ['mathjax', 'font-awesome/fonts'];
gulp.task('node-modules', () => Promise.all(nodeModules
	// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
	.map(module => gulp.src([`./node_modules/${module}/**/*.*`])
		.pipe(gulp.dest(`./build/${themeName()}/vendor-optimized/${module}`)))));

// clear build folder + smart cache
gulp.task('clear', () => gulp
	.src(
		[
			'./build/*',
			'./.gulp-changed-smart.json',
			'./.webpack-changed-plugin-cache/*',
		],
		{
			read: false,
		},
	)
	.pipe(rimraf()));

// run all tasks, processing changed files
gulp.task('build-all', [
	'images',
	'other',
	'other-with-theme',
	'styles',
	'styles-done',
	'fonts',
	'scripts',
	'base-scripts',
	'vendor-styles',
	'vendor-scripts',
	'vendor-assets',
	'vendor-optimized-assets',
	'node-modules',
	'static',
]);

gulp.task('build-theme-files', ['styles', 'styles-done', 'images', 'static']);

// watch and run corresponding task on change, process changed files only
gulp.task('watch', ['build-all'], () => {
	const watchOptions = { interval: 1000 };
	gulp.watch(baseScripts, watchOptions, ['base-scripts']);
	gulp.watch(
		withTheme('./static/styles/**/*.{css,sass,scss}'),
		watchOptions,
		['styles', 'styles-done'],
	);
	gulp.watch(withTheme('./static/images/**/*.*'), watchOptions, [
		'images',
	]).on('change', browserSync.reload);
	gulp.watch(withTheme(nonBaseScripts), watchOptions, [
		'scripts',
	]);

	gulp.watch(withTheme('./static/vendor-optimized/**/*.*'), watchOptions, [
		'vendor-optimized-assets',
	]);
	gulp.watch(withTheme('./static/*.*'), watchOptions, ['static']);
});

gulp.task('watch-reload', ['watch', 'browser-sync']);

gulp.task('browser-sync', ['nodemon'], () => {
	browserSync.init(null, {
		proxy: 'http://localhost:3100',
		open: false,
		port: 7000,
		ghostMode: false,
		reloadOnRestart: false,
		socket: {
			clients: {
				heartbeatTimeout: 60000,
			},
		},
	});
});

gulp.task('nodemon', (cb) => {
	let started = false;
	return nodemon({
		ext: 'js hbs json',
		script: './bin/www',
		watch: ['views/', 'controllers/', 'helpers'],
		exec: 'node --inspect=9310',
	}).on('start', () => {
		if (!started) {
			cb();
			started = true;
		}
		setTimeout(browserSync.reload, 3000); // server-start takes some time
	});
});

// run this if only 'gulp' is run on the commandline with no task specified
gulp.task('default', ['build-all']);
<commit_msg>added gulp clear-cache<commit_after>/* eslint-disable no-console */

const autoprefixer = require('autoprefixer');
const fs = require('fs');
const gulp = require('gulp');
const babel = require('gulp-babel');
const changed = require('gulp-changed-smart');
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const gulpCount = require('gulp-count');
const gulpErrorHandler = require('gulp-error-handle');
const filelog = require('gulp-filelog');
const header = require('gulp-header');
const gulpif = require('gulp-if');
const optimizejs = require('gulp-optimize-js');
const plumber = require('gulp-plumber');
const postcss = require('gulp-postcss');
const cssvariables = require('postcss-css-variables');
const rimraf = require('gulp-rimraf');
const sass = require('gulp-sass');
const sassGrapher = require('gulp-sass-grapher');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const path = require('path');
const named = require('vinyl-named');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const nodemon = require('gulp-nodemon');
const browserSync = require('browser-sync');
const webpackConfig = require('./webpack.config');

const baseScripts = [
	'./static/scripts/jquery/jquery.min.js',
	'./static/scripts/jquery/jquery.serialize-object.js',
	'./static/scripts/tether/tether.min.js',
	'./static/scripts/bootstrap/bootstrap.min.js',
	'./static/scripts/chosen/chosen.jquery.min.js',
	'./static/scripts/base.js',
	'./static/scripts/toggle/bootstrap-toggle.min.js',
	'./static/scripts/mailchimp/mailchimp.js',
	'./static/scripts/qrcode/kjua-0.1.1.min.js',
	'./static/scripts/ajaxconfig.js',
];

function themeName() {
	return process.env.SC_THEME || 'default';
}

const EXIT_ON_ERROR = process.env.GULP_EXIT_ON_ERROR
	? process.env.GULP_EXIT_ON_ERROR === 'true'
	: process.env.NODE_ENV !== 'development';

const nonBaseScripts = [
	'./static/scripts/**/*.js',
].concat(baseScripts.map(script => `!${script}`));
// used by almost all gulp tasks instead of gulp.src(...)
// plumber prevents pipes from stopping when errors occur
// changed only passes on files that were modified since last time
// filelog logs and counts all processed files

function withTheme(src) {
	if (typeof src === 'string') {
		return [src, `./theme/${themeName()}/${src.slice(2)}`];
	}
	return src.concat(src
		.map(e => `./theme/${themeName()}/${e.slice(2)}`));
}

const handleError = (error) => {
	console.error(error);
	process.exit(1);
};

const beginPipe = src => gulp
	.src(withTheme(src))
	.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
	.pipe(changed(gulp))
	.pipe(filelog());

const beginPipeAll = src => gulp
	.src(withTheme(src))
	.pipe(gulpif(EXIT_ON_ERROR, gulpErrorHandler(handleError), plumber()))
	.pipe(filelog());

// copy images
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('images', () => gulp
	.src(withTheme('./static/images/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/images`)));

// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other', () => gulp
	.src(withTheme('./static/other/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/other`)));

// minify static/other
// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
gulp.task('other-with-theme', ['other'], () => gulp
	.src(withTheme('./static/other/**/*.*'))
	.pipe(gulp.dest(`./build/${themeName()}/other`)));

const loadPaths = path.resolve('./static/styles/');
sassGrapher.init('./static/styles/', {
	loadPaths,
});
let firstRun = true;
gulp.task('styles', () => {
	const themeFile = `./theme/${themeName()}/style.scss`;
	return beginPipe('./static/styles/**/*.{css,sass,scss}')
		.pipe(gulpif(!firstRun, sassGrapher.ancestors()))
		.pipe(header(fs.readFileSync(themeFile, 'utf8')))
		.pipe(filelog('PROCESS: '))
		.pipe(sourcemaps.init())
		.pipe(sass({
			sourceMap: true,
			includePaths: ['node_modules'],
		}).on('error', handleError))
		.pipe(postcss([
			cssvariables({
				preserve: true,
			}),
			autoprefixer({
				browsers: ['> 1%', 'not dead'],
			}),
		]))
		.pipe(cleanCSS({
			compatibility: 'ie9',
		}))
		.pipe(sourcemaps.write('./sourcemaps'))
		.pipe(gulp.dest(`./build/${themeName()}/styles`))
		.pipe(browserSync.stream());
});

gulp.task('styles-done', ['styles'], () => {
	firstRun = false;
});

// copy fonts
gulp.task('fonts', () => beginPipe('./static/fonts/**/*.*')
	.pipe(gulp.dest(`./build/${themeName()}/fonts`)));

// copy static assets
gulp.task('static', () => beginPipe('./static/*')
	.pipe(gulp.dest(`./build/${themeName()}/`)));

// compile/transpile JSX and ES6 to ES5 and minify scripts
gulp.task('scripts', () => beginPipeAll(nonBaseScripts)
	.pipe(
		named((file) => {
			// As a preparation for webpack stream: Transform nonBaseScripts paths
			// e.g. '/static/scripts/schics/schicEdit.blub.min.js' -> 'schics/schicEdit.blub.min'
			const initialPath = file.history[0].split('scripts')[1];
			const pathSegments = initialPath.split('.');
			const concretePath = pathSegments
				.slice(0, pathSegments.length - 1)
				.join('.');
			const fileName = concretePath
				.split('')
				.slice(1)
				.join('');

			return fileName;
		}),
	)
	.pipe(webpackStream(webpackConfig, webpack))
	.pipe(gulp.dest(`./build/${themeName()}/scripts`))
	.pipe(browserSync.stream()));

// compile/transpile JSX and ES6 to ES5, minify and concatenate base scripts into all.js
gulp.task('base-scripts', () => beginPipeAll(baseScripts)
	.pipe(gulpCount('## js-files selected'))
	.pipe(babel({
		presets: [
			[
				'@babel/preset-env',
				{
					modules: false,
					targets: '> 1%, not dead',
				},
			],
		],
	}))
	.pipe(optimizejs())
	.pipe(uglify())
	.pipe(concat('all.js'))
	.pipe(gulp.dest(`./build/${themeName()}/scripts`)));

// compile vendor SASS/SCSS to CSS and minify it
gulp.task('vendor-styles', () => beginPipe('./static/vendor/**/*.{css,sass,scss}')
	.pipe(sourcemaps.init())
	.pipe(sass({
		sourceMap: true,
	}))
	.pipe(postcss([
		autoprefixer({
			browsers: ['> 1%', 'not dead'],
		}),
	]))
	.pipe(cleanCSS({
		compatibility: 'ie9',
	}))
	.pipe(sourcemaps.write('./sourcemaps'))
	.pipe(gulp.dest(`./build/${themeName()}/vendor`))
	.pipe(browserSync.stream()));

// compile/transpile vendor JSX and ES6 to ES5 and minify scripts
gulp.task('vendor-scripts', () => beginPipe('./static/vendor/**/*.js')
	.pipe(babel({
		compact: false,
		presets: [
			[
				'@babel/preset-env',
				{
					modules: false,
					targets: '> 1%, not dead',
				},
			],
		],
		plugins: ['@babel/plugin-transform-react-jsx'],
	}))
	.pipe(optimizejs())
	.pipe(uglify())
	.pipe(gulp.dest(`./build/${themeName()}/vendor`)));

// copy other vendor files
gulp.task('vendor-assets', () => beginPipe([
	'./static/vendor/**/*.*',
	'!./static/vendor/**/*.js',
	'!./static/vendor/**/*.{css,sass,scss}',
]).pipe(gulp.dest(`./build/${themeName()}/vendor`)));

// copy vendor-optimized files
gulp.task('vendor-optimized-assets', () => beginPipe(['./static/vendor-optimized/**/*.*'])
	.pipe(gulp.dest(`./build/${themeName()}/vendor-optimized`)));

// copy node modules
const nodeModules = ['mathjax', 'font-awesome/fonts'];
gulp.task('node-modules', () => Promise.all(nodeModules
	// uses gulp.src instead of beginPipe for performance reasons (logging is slow)
	.map(module => gulp.src([`./node_modules/${module}/**/*.*`])
		.pipe(gulp.dest(`./build/${themeName()}/vendor-optimized/${module}`)))));

// clear build folder + smart cache
gulp.task('clear', () => gulp
	.src(
		[
			'./build/*',
			'./.gulp-changed-smart.json',
			'./.webpack-changed-plugin-cache/*',
		],
		{
			read: false,
		},
	)
	.pipe(rimraf()));

// clear gulp cache without removing current build
gulp.task('clear-cache', () => gulp
	.src(
		[
			'./.gulp-changed-smart.json',
			'./.webpack-changed-plugin-cache/*',
		],
		{
			read: false,
		},
	)
	.pipe(rimraf()));

// run all tasks, processing changed files
gulp.task('build-all', [
	'images',
	'other',
	'other-with-theme',
	'styles',
	'styles-done',
	'fonts',
	'scripts',
	'base-scripts',
	'vendor-styles',
	'vendor-scripts',
	'vendor-assets',
	'vendor-optimized-assets',
	'node-modules',
	'static',
]);

gulp.task('build-theme-files', ['styles', 'styles-done', 'images', 'static']);

// watch and run corresponding task on change, process changed files only
gulp.task('watch', ['build-all'], () => {
	const watchOptions = { interval: 1000 };
	gulp.watch(baseScripts, watchOptions, ['base-scripts']);
	gulp.watch(
		withTheme('./static/styles/**/*.{css,sass,scss}'),
		watchOptions,
		['styles', 'styles-done'],
	);
	gulp.watch(withTheme('./static/images/**/*.*'), watchOptions, [
		'images',
	]).on('change', browserSync.reload);
	gulp.watch(withTheme(nonBaseScripts), watchOptions, [
		'scripts',
	]);

	gulp.watch(withTheme('./static/vendor-optimized/**/*.*'), watchOptions, [
		'vendor-optimized-assets',
	]);
	gulp.watch(withTheme('./static/*.*'), watchOptions, ['static']);
});

gulp.task('watch-reload', ['watch', 'browser-sync']);

gulp.task('browser-sync', ['nodemon'], () => {
	browserSync.init(null, {
		proxy: 'http://localhost:3100',
		open: false,
		port: 7000,
		ghostMode: false,
		reloadOnRestart: false,
		socket: {
			clients: {
				heartbeatTimeout: 60000,
			},
		},
	});
});

gulp.task('nodemon', (cb) => {
	let started = false;
	return nodemon({
		ext: 'js hbs json',
		script: './bin/www',
		watch: ['views/', 'controllers/', 'helpers'],
		exec: 'node --inspect=9310',
	}).on('start', () => {
		if (!started) {
			cb();
			started = true;
		}
		setTimeout(browserSync.reload, 3000); // server-start takes some time
	});
});

// run this if only 'gulp' is run on the commandline with no task specified
gulp.task('default', ['build-all']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var plugins = require('gulp-load-plugins')();
var del = require('del');
var cssBase64 = require('gulp-css-base64');
var glob = require('glob');
var path = require('path');
var marked = require('marked');
var minifyCss = require('gulp-minify-css');
var swig = require('swig');
var through2 = require('through2');
var uglify = require('gulp-uglify')
var promisify = require('es6-promisify');
var mergeStream = require('merge-stream');
var parseRecipes = require('./parseRecipes.js');
var renderFile = promisify(swig.renderFile);
var fsWriteFile = promisify(fs.writeFile);
var fsReadFile = promisify(fs.readFile);

var ignore = ['!./dist', '!./dist', '!./dist/**', '!./node_modules', '!./node_modules/**'];
var recipeSlugs = glob.sync('./!(dist|node_modules|src|_recipe_template)/').map(function toBase(dir) {
  return path.basename(dir);
});
var srcRecipes = recipeSlugs.map(function makePath(name) {
  return './' + name + '/**';
});
var recipes = parseRecipes(recipeSlugs);

var template = (function() {
  function renderContent(content, options) {
    var newOptions = options || {};
    return renderFile('./src/tpl/layout.html', {
      content: content,
      package: require('./package.json'),
      recipes: recipes,
      ghBase: 'https://github.com/digitarald/serviceworker-cookbook/blob/master/',
      currentRecipe: newOptions.currentRecipe,
    });
  }

  /**
   * Write content into the layout file.
   * @param {string} outputFile - filename
   * @param {string} content - put in the main body, NOT ESCAPED
   * @param {Object} options -
   *    'currentRecipe' - if the page needs the recipe's header
   * @returns {Promise}
   */
  function writeFile(outputFile, content, options) {
    return renderContent(content, options)
    .then(function(output) {
      return fsWriteFile(outputFile, output);
    });
  }

  /**
   * Same as writeFile but works with streams
   * @returns Stream transform.
   */
  function transform(options) {
    return through2.obj(function(file, enc, next) {
      var self = this;
      renderContent(file.contents.toString('utf8'), options)
      .then(function(output) {
        file.contents = new Buffer(output);
        self.push(file);
        next();
      });
    });
  }

  return {
    transform: transform,
    writeFile: writeFile
  };
})();

gulp.task('clean', function clean(done) {
  del(['./dist']).then(function delThen() {
    fs.mkdir('./dist', function() {
      done();
    });
  });
});

gulp.task('lint', function lint() {
  return gulp
    .src(['./*.js', './*/*.js'].concat(ignore))
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError());
});

gulp.task('build:docs', ['clean'], function buildDocs() {
  var streams = recipes.map(function(recipe) {
    return gulp
    .src(recipe.srcs.map(function(src) {
      return recipe.slug + '/' + src.filename;
    }), {
      base: './'
    })
    .pipe(plugins.docco({
      template: './src/tpl/docco/docco.jst'
    }))
    .pipe(template.transform({ currentRecipe: recipe }))
    .pipe(plugins.rename(function(renamePath) {
      renamePath.dirname = '';
      renamePath.basename = recipe.slug + '_' + renamePath.basename + '_doc';
    }))
    .pipe(gulp.dest('./dist/'));
  });

  return mergeStream.apply(null, streams);
});

gulp.task('build:index', ['clean'], function buildIndex() {
  var intros = recipes.map(function(recipe) {
    var title = recipe.name;
    var summary = marked(recipe.summary);
    return {
      slug: recipe.slug,
      title: title,
      summary: summary,
    };
  });
  return renderFile('./src/tpl/index.html', { recipes: intros })
  .then(function(output) {
    return template.writeFile('./dist/index.html', output);
  });
});

gulp.task('build:intros', ['clean'], function() {
  var renderer = new marked.Renderer();
  renderer.link = function(href, title, text) {
    var link = '' + text + '';
  }

  return Promise.all(recipes.map(function(recipe) {
    return fsReadFile(recipe.slug + '/README.md', 'utf8')
    .then(function(readme) {
      return renderFile('./src/tpl/intro.html', { markdown: marked(readme, { renderer: renderer }) });
    })
    .then(function(content) {
      return template.writeFile('./dist/' + recipe.slug + '.html', content, { currentRecipe: recipe });
    });
  }));
});

gulp.task('build:demos', ['clean'], function() {
  return Promise.all(recipes.map(function(recipe) {
    return renderFile('./src/tpl/demo.html', { recipe: recipe })
    .then(function(output) {
      return template.writeFile('./dist/' + recipe.slug + '_demo.html', output, { currentRecipe: recipe });
    });
  }));
});

gulp.task('build:recipes', ['clean'], function() {
  return gulp
    .src(srcRecipes, {
      base: './'
    })
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:css', ['clean'], function() {
  return gulp
    .src([
      'src/css/foundation.normalize.css',
      'src/css/foundation.css',
      'src/css/foundation-icons.css',
      'src/css/style.css',
      'src/css/docco.css'
    ])
    .pipe(plugins.concat('bundle.css'))
    .pipe(minifyCss())
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:js', ['clean'], function() {
  return gulp
    .src('src/js/*.js')
    .pipe(plugins.concat('bundle.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:tabzilla', ['clean'], function() {
  return gulp
    .src('node_modules/mozilla-tabzilla/css/*.css')
    .pipe(cssBase64())
    .pipe(minifyCss())
    .pipe(gulp.dest('dist/'));
});

gulp.task('build:favicon', ['clean'], function() {
  return gulp
    .src('favicon.ico')
    .pipe(gulp.dest('dist'));
});

// Start express server after building site
gulp.task('start-server', ['build'], function startServer(cb) {
  require('./server.js').ready.then(cb);
});

// Watch files and reloads BrowserSync
gulp.task('watch', ['start-server'], function serve() {
  var browserSync = require('browser-sync').create();
  browserSync.init(null, {
    proxy: 'http://localhost:3003',
    files: './*/*.js',
    open: false
  });
  return gulp.watch(['./*/*'].concat(ignore), ['build-dev'], browserSync.reload);
});

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

// Minimal build tasks for speedy development
gulp.task('build-dev', ['build:recipes', 'test']);

// Full build for publishing
gulp.task('build', ['build:index', 'build:intros', 'build:demos', 'build:recipes', 'build:docs', 'build:css', 'build:js', 'build:tabzilla', 'build:favicon']);
<commit_msg>Run lint when building<commit_after>var gulp = require('gulp');
var fs = require('fs');
var plugins = require('gulp-load-plugins')();
var del = require('del');
var cssBase64 = require('gulp-css-base64');
var glob = require('glob');
var path = require('path');
var marked = require('marked');
var minifyCss = require('gulp-minify-css');
var swig = require('swig');
var through2 = require('through2');
var uglify = require('gulp-uglify')
var promisify = require('es6-promisify');
var mergeStream = require('merge-stream');
var parseRecipes = require('./parseRecipes.js');
var renderFile = promisify(swig.renderFile);
var fsWriteFile = promisify(fs.writeFile);
var fsReadFile = promisify(fs.readFile);

var ignore = ['!./dist', '!./dist', '!./dist/**', '!./node_modules', '!./node_modules/**'];
var recipeSlugs = glob.sync('./!(dist|node_modules|src|_recipe_template)/').map(function toBase(dir) {
  return path.basename(dir);
});
var srcRecipes = recipeSlugs.map(function makePath(name) {
  return './' + name + '/**';
});
var recipes = parseRecipes(recipeSlugs);

var template = (function() {
  function renderContent(content, options) {
    var newOptions = options || {};
    return renderFile('./src/tpl/layout.html', {
      content: content,
      package: require('./package.json'),
      recipes: recipes,
      ghBase: 'https://github.com/digitarald/serviceworker-cookbook/blob/master/',
      currentRecipe: newOptions.currentRecipe,
    });
  }

  /**
   * Write content into the layout file.
   * @param {string} outputFile - filename
   * @param {string} content - put in the main body, NOT ESCAPED
   * @param {Object} options -
   *    'currentRecipe' - if the page needs the recipe's header
   * @returns {Promise}
   */
  function writeFile(outputFile, content, options) {
    return renderContent(content, options)
    .then(function(output) {
      return fsWriteFile(outputFile, output);
    });
  }

  /**
   * Same as writeFile but works with streams
   * @returns Stream transform.
   */
  function transform(options) {
    return through2.obj(function(file, enc, next) {
      var self = this;
      renderContent(file.contents.toString('utf8'), options)
      .then(function(output) {
        file.contents = new Buffer(output);
        self.push(file);
        next();
      });
    });
  }

  return {
    transform: transform,
    writeFile: writeFile
  };
})();

gulp.task('clean', function clean(done) {
  del(['./dist']).then(function delThen() {
    fs.mkdir('./dist', function() {
      done();
    });
  });
});

gulp.task('lint', function lint() {
  return gulp
    .src(['./*.js', './*/*.js'].concat(ignore))
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError());
});

gulp.task('build:docs', ['clean'], function buildDocs() {
  var streams = recipes.map(function(recipe) {
    return gulp
    .src(recipe.srcs.map(function(src) {
      return recipe.slug + '/' + src.filename;
    }), {
      base: './'
    })
    .pipe(plugins.docco({
      template: './src/tpl/docco/docco.jst'
    }))
    .pipe(template.transform({ currentRecipe: recipe }))
    .pipe(plugins.rename(function(renamePath) {
      renamePath.dirname = '';
      renamePath.basename = recipe.slug + '_' + renamePath.basename + '_doc';
    }))
    .pipe(gulp.dest('./dist/'));
  });

  return mergeStream.apply(null, streams);
});

gulp.task('build:index', ['clean'], function buildIndex() {
  var intros = recipes.map(function(recipe) {
    var title = recipe.name;
    var summary = marked(recipe.summary);
    return {
      slug: recipe.slug,
      title: title,
      summary: summary,
    };
  });
  return renderFile('./src/tpl/index.html', { recipes: intros })
  .then(function(output) {
    return template.writeFile('./dist/index.html', output);
  });
});

gulp.task('build:intros', ['clean'], function() {
  var renderer = new marked.Renderer();
  renderer.link = function(href, title, text) {
    var link = '' + text + '';
  }

  return Promise.all(recipes.map(function(recipe) {
    return fsReadFile(recipe.slug + '/README.md', 'utf8')
    .then(function(readme) {
      return renderFile('./src/tpl/intro.html', { markdown: marked(readme, { renderer: renderer }) });
    })
    .then(function(content) {
      return template.writeFile('./dist/' + recipe.slug + '.html', content, { currentRecipe: recipe });
    });
  }));
});

gulp.task('build:demos', ['clean'], function() {
  return Promise.all(recipes.map(function(recipe) {
    return renderFile('./src/tpl/demo.html', { recipe: recipe })
    .then(function(output) {
      return template.writeFile('./dist/' + recipe.slug + '_demo.html', output, { currentRecipe: recipe });
    });
  }));
});

gulp.task('build:recipes', ['clean'], function() {
  return gulp
    .src(srcRecipes, {
      base: './'
    })
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:css', ['clean'], function() {
  return gulp
    .src([
      'src/css/foundation.normalize.css',
      'src/css/foundation.css',
      'src/css/foundation-icons.css',
      'src/css/style.css',
      'src/css/docco.css'
    ])
    .pipe(plugins.concat('bundle.css'))
    .pipe(minifyCss())
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:js', ['clean'], function() {
  return gulp
    .src('src/js/*.js')
    .pipe(plugins.concat('bundle.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./dist'));
});

gulp.task('build:tabzilla', ['clean'], function() {
  return gulp
    .src('node_modules/mozilla-tabzilla/css/*.css')
    .pipe(cssBase64())
    .pipe(minifyCss())
    .pipe(gulp.dest('dist/'));
});

gulp.task('build:favicon', ['clean'], function() {
  return gulp
    .src('favicon.ico')
    .pipe(gulp.dest('dist'));
});

// Start express server after building site
gulp.task('start-server', ['build'], function startServer(cb) {
  require('./server.js').ready.then(cb);
});

// Watch files and reloads BrowserSync
gulp.task('watch', ['start-server'], function serve() {
  var browserSync = require('browser-sync').create();
  browserSync.init(null, {
    proxy: 'http://localhost:3003',
    files: './*/*.js',
    open: false
  });
  return gulp.watch(['./*/*'].concat(ignore), ['build-dev'], browserSync.reload);
});

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

// Minimal build tasks for speedy development
gulp.task('build-dev', ['build:recipes', 'test']);

// Full build for publishing
gulp.task('build', ['build-dev', 'build:index', 'build:intros', 'build:demos', 'build:docs', 'build:css', 'build:js', 'build:tabzilla', 'build:favicon']);
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const config = require('./package.json').config;
const plugins = require('gulp-load-plugins')();
const browserify = require('browserify');
const babelify = require('babelify');
const watchify = require('watchify');
const buffer = require('vinyl-buffer');
const source = require('vinyl-source-stream');

const bundler = watchify(browserify('./src/js/app.js').transform(babelify, {presets: ['es2015']}));

function bundle() {
  return bundler.bundle()
    .on('error', plugins.util.log)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulp.dest('./web/dist/'))
    .pipe(plugins.livereload());
}

gulp.task('js:build', function () {
  const bundler = browserify('./src/js/app.js').transform(babelify, {presets: ['es2015']});

  return bundler.bundle()
    .on('error', plugins.util.log)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(plugins.uglify())
    .pipe(gulp.dest('./web/dist/'));
});

gulp.task('js', () => {
  bundle();
  bundler.on('update', bundle);
  bundler.on('log', plugins.util.log);
});

gulp.task('sass:app', () => {
  return gulp.src(config.sass.source.app)
    .pipe(plugins.sass(config.sass.options.app).on('error', plugins.sass.logError))
    // .pipe(plugins.rev())
    // .pipe(gulp.dest(config.sass.output.dir))
    // .pipe(plugins.rev.manifest(config.rev.manifest, config.rev.options))
    .pipe(gulp.dest(config.sass.output.dir))
    .pipe(plugins.livereload());
});

gulp.task('sass:vendor', () => {
  return gulp.src(config.sass.source.vendor)
    .pipe(plugins.sass(config.sass.options.vendor).on('error', plugins.sass.logError))
    .pipe(plugins.autoprefixer({
      browsers: ['last 3 versions']
    }))
    // .pipe(plugins.rev())
    // .pipe(gulp.dest(config.sass.output.dir))
    // .pipe(plugins.rev.manifest(config.rev.manifest, config.rev.options))
    .pipe(gulp.dest(config.sass.output.dir))
    .pipe(plugins.livereload());
});

gulp.task('fonts', () => {
  return gulp.src(config.fonts.source)
    .pipe(gulp.dest(config.fonts.output.dir));
});

gulp.task('images', () => {
  return gulp.src(config.images.source)
    .pipe(plugins.imagemin())
    .pipe(gulp.dest(config.images.output.dir));
});

gulp.task('templates', () => {
    return gulp.src(config.templates.source)
        .pipe(gulp.dest(config.templates.output.dir))
        .pipe(plugins.livereload());
});

gulp.task('clean', () => {
  return gulp.src(config.clean)
    .pipe(plugins.clean({force: true}));
});

gulp.task('watch', (callback) => {
  plugins.livereload.listen();

  bundle();
  gulp.watch(config.js.watch, bundle);
  gulp.watch(config.sass.watch, ['sass:app', 'templates']);
  gulp.watch(config.templates.watch, ['templates']);
  gulp.watch(config.images.source, ['images']);
});

gulp.task('default', (callback) => {
  plugins.runSequence(['js', 'sass:app'], 'images', 'templates', callback);
});

gulp.task('build', (callback) => {
  plugins.runSequence(['js:build'], ['sass:app', 'sass:vendor'], 'fonts', 'images', 'templates', callback);
});
<commit_msg>Removes reving comments<commit_after>'use strict';

const gulp = require('gulp');
const config = require('./package.json').config;
const plugins = require('gulp-load-plugins')();
const browserify = require('browserify');
const babelify = require('babelify');
const watchify = require('watchify');
const buffer = require('vinyl-buffer');
const source = require('vinyl-source-stream');

const bundler = watchify(browserify('./src/js/app.js').transform(babelify, {presets: ['es2015']}));

function bundle() {
  return bundler.bundle()
    .on('error', plugins.util.log)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(gulp.dest('./web/dist/'))
    .pipe(plugins.livereload());
}

gulp.task('js:build', function () {
  const bundler = browserify('./src/js/app.js').transform(babelify, {presets: ['es2015']});

  return bundler.bundle()
    .on('error', plugins.util.log)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(plugins.uglify())
    .pipe(gulp.dest('./web/dist/'));
});

gulp.task('js', () => {
  bundle();
  bundler.on('update', bundle);
  bundler.on('log', plugins.util.log);
});

gulp.task('sass:app', () => {
  return gulp.src(config.sass.source.app)
    .pipe(plugins.sass(config.sass.options.app).on('error', plugins.sass.logError))
    .pipe(gulp.dest(config.sass.output.dir))
    .pipe(plugins.livereload());
});

gulp.task('sass:vendor', () => {
  return gulp.src(config.sass.source.vendor)
    .pipe(plugins.sass(config.sass.options.vendor).on('error', plugins.sass.logError))
    .pipe(plugins.autoprefixer({
      browsers: ['last 3 versions']
    }))
    .pipe(gulp.dest(config.sass.output.dir))
    .pipe(plugins.livereload());
});

gulp.task('fonts', () => {
  return gulp.src(config.fonts.source)
    .pipe(gulp.dest(config.fonts.output.dir));
});

gulp.task('images', () => {
  return gulp.src(config.images.source)
    .pipe(plugins.imagemin())
    .pipe(gulp.dest(config.images.output.dir));
});

gulp.task('templates', () => {
    return gulp.src(config.templates.source)
        .pipe(gulp.dest(config.templates.output.dir))
        .pipe(plugins.livereload());
});

gulp.task('clean', () => {
  return gulp.src(config.clean)
    .pipe(plugins.clean({force: true}));
});

gulp.task('watch', (callback) => {
  plugins.livereload.listen();

  bundle();
  gulp.watch(config.js.watch, bundle);
  gulp.watch(config.sass.watch, ['sass:app', 'templates']);
  gulp.watch(config.templates.watch, ['templates']);
  gulp.watch(config.images.source, ['images']);
});

gulp.task('default', (callback) => {
  plugins.runSequence(['js', 'sass:app'], 'images', 'templates', callback);
});

gulp.task('build', (callback) => {
  plugins.runSequence(['js:build'], ['sass:app', 'sass:vendor'], 'fonts', 'images', 'templates', callback);
});
<|endoftext|>


<commit_before>"use strict";

var babelify = require("babelify");
var browserify = require("browserify");
var browserSync = require("browser-sync").create();
var changed = require("gulp-changed");
var sass = require("gulp-sass");
var ejs = require("gulp-ejs");
var fs = require("fs");
var gulp = require("gulp");
var gutil = require("gulp-util");
var KarmaServer = require("karma").Server;
var notify = require("gulp-notify");
var path = require("path");
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");
var source = require("vinyl-source-stream");
var watchify = require("watchify");

sass.compiler = require("node-sass");

// Parameters
var SRC_DIR = "src";
var DEST_DIR = "build";
var DIRS = {
    fonts: { src: "fonts" },
    html: { src: "html", dest: "", srcPattern: "*.ejs" },
    js: { src: "js" },
    css: { src: "scss", dest: "css", srcPattern: "*.scss" },
    resources: {
        src: "../node_modules/vivliostyle/resources",
        dest: "resources"
    },
    mathjax: { src: "../node_modules/mathjax", dest: "mathjax" },
    plugin_resources: {
        src: "../node_modules/vivliostyle/plugins/*/resources",
        dest: "plugins"
    }
};
var JS_ENTRIES = {
    production: "main.js",
    development: "main-dev.js"
};
var VIVLIOSTYLE_JS_SRC_DIR = "node_modules/vivliostyle/src";
var HTML_FILENAMES = {
    production: "vivliostyle-viewer.html",
    development: "vivliostyle-viewer-dev.html"
};
var SERVER_START_PATH = "/vivliostyle-ui/build/%viewer-html%#x=/vivliostyle.js/samples/gon/index.html";

function getVersion(basePath) {
    var version = JSON.parse(fs.readFileSync(basePath + "package.json", "utf8")).version;
    return version.replace(/\.0$/, "");
}
var versions = {
    core: getVersion("node_modules/vivliostyle/"),
    ui: getVersion("")
};

// Utility functions
function srcDir(type) {
    return SRC_DIR + "/" + DIRS[type].src;
}
function destDir(type) {
    var dirs = DIRS[type];
    return DEST_DIR + "/" + (typeof dirs.dest === "string" ? dirs.dest : dirs.src);
}
function srcPattern(type) {
    return SRC_DIR + "/" + DIRS[type].src + "/" + (DIRS[type].srcPattern || "**/*");
}

// JS build
function getBrowserify(development, watch) {
    var b = browserify({
        cache: {},
        packageCache: {},
        entries: [srcDir("js") + "/" + (development ? JS_ENTRIES.development : JS_ENTRIES.production)],
        transform: [
            babelify.configure({
                presets: ["@babel/preset-env"]
            })
        ],
        debug: development
    });
    if (watch) {
        b = watchify(b);
    }
    b.on("log", gutil.log);
    return b;
}
function bundleJs(b, name) {
    return b
        .bundle()
        .on("error", gutil.log.bind(gutil, "Browserify Error"))
        .pipe(name === JS_ENTRIES.production ? require("minify-stream")({ sourceMap: false }) : gutil.noop())
        .pipe(source(name))
        .pipe(gulp.dest(destDir("js")));
}
var b;
var watching = false;
function bundleJsProd() {
    var name = JS_ENTRIES.production;
    return bundleJs(b, name);
}
function bundleJsDev() {
    var name = JS_ENTRIES.development;
    return bundleJs(b, name);
}
gulp.task("build:js", function() {
    b = getBrowserify(false, watching);
    return bundleJsProd();
});
gulp.task("build:js-dev", function() {
    b = getBrowserify(true, watching);
    return bundleJsDev();
});

// create a task simply copying files
function copyTask(type) {
    var dest = destDir(type);
    return gulp.task("build:" + type, function() {
        return gulp
            .src(srcPattern(type))
            .pipe(changed(dest))
            .pipe(gulp.dest(dest));
    });
}
copyTask("fonts");
copyTask("resources");
copyTask("mathjax");
copyTask("plugin_resources");

// HTML build
function buildHtml(development) {
    return gulp
        .src(srcPattern("html"))
        .pipe(ejs({ development: development, versions: versions }))
        .pipe(
            plumber({
                errorHandler: notify.onError("Error: <%= error.message %>")
            })
        )
        .pipe(rename(development ? HTML_FILENAMES.development : HTML_FILENAMES.production))
        .pipe(gulp.dest(destDir("html")));
}
gulp.task("build:html", function() {
    return buildHtml(false);
});
gulp.task("build:html-dev", function() {
    return buildHtml(true);
});

// CSS build
function buildCss(development) {
    return gulp
        .src(srcPattern("css"))
        .pipe(
            plumber({
                errorHandler: notify.onError("Error: <%= error.message %>")
            })
        )
        .pipe(
            sass({
                outputStyle: development ? "expanded" : "compressed"
            }).on("error", sass.logError)
        )
        .pipe(gulp.dest(path.resolve(destDir("css"))));
}
gulp.task("build:css", function() {
    return buildCss(false);
});
gulp.task("build:css-dev", function() {
    return buildCss(true);
});

// build all
gulp.task(
    "build",
    gulp.parallel(
        "build:js",
        "build:html",
        "build:fonts",
        "build:resources",
        //    "build:mathjax",
        "build:plugin_resources",
        "build:css"
    )
);
gulp.task("build-dev", gulp.parallel("build:js-dev", "build:html-dev", "build:fonts", "build:resources", "build:plugin_resources", "build:css-dev"));

// watch
gulp.task("start-watching", function(done) {
    watching = true;
    done();
});
gulp.task(
    "watch",
    gulp.series(gulp.parallel("start-watching", "build"), function(done) {
        b.on("update", bundleJsProd);
        gulp.watch(srcPattern("html"), gulp.task("build:html"));
        gulp.watch(srcPattern("fonts"), gulp.task("build:fonts"));
        gulp.watch(srcPattern("resources"), gulp.task("build:resources"));
        gulp.watch(srcPattern("plugin_resources"), gulp.task("build:plugin_resources"));
        gulp.watch(srcPattern("css"), gulp.task("build:css"));
        done();
    })
);
gulp.task(
    "watch-dev",
    gulp.series(gulp.parallel("start-watching", "build-dev"), function(done) {
        b.on("update", bundleJsDev);
        gulp.watch(srcPattern("html"), gulp.task("build:html-dev"));
        gulp.watch(srcPattern("fonts"), gulp.task("build:fonts"));
        gulp.watch(srcPattern("resources"), gulp.task("build:resources"));
        gulp.watch(srcPattern("plugin_resources"), gulp.task("build:plugin_resources"));
        gulp.watch(srcPattern("css"), gulp.task("build:css-dev"));
        done();
    })
);

// serve
function serve(development) {
    browserSync.init({
        browser:
            process.platform === "darwin"
                ? "google chrome"
                : process.platform === "win32"
                ? "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
                : "chromium-browser",
        server: {
            baseDir: "../"
        },
        startPath: "/vivliostyle.js/test/files/"
    });
    var target = [DEST_DIR + "/**/*"];
    if (development) {
        target.push(VIVLIOSTYLE_JS_SRC_DIR + "/**/*");
    }
    gulp.watch(target).on("change", browserSync.reload);
}
gulp.task(
    "serve",
    gulp.series("watch", function(done) {
        serve(false);
        done();
    })
);
gulp.task(
    "serve-dev",
    gulp.series("watch-dev", function(done) {
        serve(true);
        done();
    })
);

gulp.task("default", gulp.task("serve-dev"));

// test
gulp.task("test-local", function(done) {
    var server = new KarmaServer(
        {
            configFile: process.cwd() + "/test/conf/karma-local.conf"
        },
        function(exitStatus) {
            done(exitStatus ? "Some tests failed" : undefined);
        }
    );
    server.start();
});
gulp.task("test-sauce", function(done) {
    var server = new KarmaServer(
        {
            configFile: process.cwd() + "/test/conf/karma-sauce.conf"
        },
        function(exitStatus) {
            done(exitStatus ? "Some tests failed" : undefined);
        }
    );
    server.start();
});
<commit_msg>remove JavaScript task in gulpfile<commit_after>"use strict";

var browserSync = require("browser-sync").create();
var changed = require("gulp-changed");
var sass = require("gulp-sass");
var ejs = require("gulp-ejs");
var fs = require("fs");
var gulp = require("gulp");
var KarmaServer = require("karma").Server;
var notify = require("gulp-notify");
var path = require("path");
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");

sass.compiler = require("node-sass");

// Parameters
var SRC_DIR = "src";
var DEST_DIR = "build";
var DIRS = {
    fonts: { src: "fonts" },
    html: { src: "html", dest: "", srcPattern: "*.ejs" },
    css: { src: "scss", dest: "css", srcPattern: "*.scss" },
    resources: {
        src: "../node_modules/vivliostyle/resources",
        dest: "resources"
    },
    mathjax: { src: "../node_modules/mathjax", dest: "mathjax" },
    plugin_resources: {
        src: "../node_modules/vivliostyle/plugins/*/resources",
        dest: "plugins"
    }
};
var VIVLIOSTYLE_JS_SRC_DIR = "node_modules/vivliostyle/src";
var HTML_FILENAMES = {
    production: "vivliostyle-viewer.html",
    development: "vivliostyle-viewer-dev.html"
};

function getVersion(basePath) {
    var version = JSON.parse(fs.readFileSync(basePath + "package.json", "utf8")).version;
    return version.replace(/\.0$/, "");
}
var versions = {
    core: getVersion("node_modules/vivliostyle/"),
    ui: getVersion("")
};

// Utility functions
function destDir(type) {
    var dirs = DIRS[type];
    return DEST_DIR + "/" + (typeof dirs.dest === "string" ? dirs.dest : dirs.src);
}
function srcPattern(type) {
    return SRC_DIR + "/" + DIRS[type].src + "/" + (DIRS[type].srcPattern || "**/*");
}

// create a task simply copying files
function copyTask(type) {
    var dest = destDir(type);
    return gulp.task("build:" + type, function() {
        return gulp
            .src(srcPattern(type))
            .pipe(changed(dest))
            .pipe(gulp.dest(dest));
    });
}
copyTask("fonts");
copyTask("resources");
copyTask("mathjax");
copyTask("plugin_resources");

// HTML build
function buildHtml(development) {
    return gulp
        .src(srcPattern("html"))
        .pipe(ejs({ development: development, versions: versions }))
        .pipe(
            plumber({
                errorHandler: notify.onError("Error: <%= error.message %>")
            })
        )
        .pipe(rename(development ? HTML_FILENAMES.development : HTML_FILENAMES.production))
        .pipe(gulp.dest(destDir("html")));
}
gulp.task("build:html", function() {
    return buildHtml(false);
});
gulp.task("build:html-dev", function() {
    return buildHtml(true);
});

// CSS build
function buildCss(development) {
    return gulp
        .src(srcPattern("css"))
        .pipe(
            plumber({
                errorHandler: notify.onError("Error: <%= error.message %>")
            })
        )
        .pipe(
            sass({
                outputStyle: development ? "expanded" : "compressed"
            }).on("error", sass.logError)
        )
        .pipe(gulp.dest(path.resolve(destDir("css"))));
}
gulp.task("build:css", function() {
    return buildCss(false);
});
gulp.task("build:css-dev", function() {
    return buildCss(true);
});

// build all
gulp.task("build", gulp.parallel("build:html", "build:fonts", "build:resources", "build:plugin_resources", "build:css"));
gulp.task("build-dev", gulp.parallel("build:html-dev", "build:fonts", "build:resources", "build:plugin_resources", "build:css-dev"));

// watch
gulp.task("start-watching", function(done) {
    done();
});
gulp.task(
    "watch",
    gulp.series(gulp.parallel("start-watching", "build"), function(done) {
        gulp.watch(srcPattern("html"), gulp.task("build:html"));
        gulp.watch(srcPattern("fonts"), gulp.task("build:fonts"));
        gulp.watch(srcPattern("resources"), gulp.task("build:resources"));
        gulp.watch(srcPattern("plugin_resources"), gulp.task("build:plugin_resources"));
        gulp.watch(srcPattern("css"), gulp.task("build:css"));
        done();
    })
);
gulp.task(
    "watch-dev",
    gulp.series(gulp.parallel("start-watching", "build-dev"), function(done) {
        gulp.watch(srcPattern("html"), gulp.task("build:html-dev"));
        gulp.watch(srcPattern("fonts"), gulp.task("build:fonts"));
        gulp.watch(srcPattern("resources"), gulp.task("build:resources"));
        gulp.watch(srcPattern("plugin_resources"), gulp.task("build:plugin_resources"));
        gulp.watch(srcPattern("css"), gulp.task("build:css-dev"));
        done();
    })
);

// serve
function serve(development) {
    browserSync.init({
        browser:
            process.platform === "darwin"
                ? "google chrome"
                : process.platform === "win32"
                ? "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
                : "chromium-browser",
        server: {
            baseDir: "../"
        },
        startPath: "/vivliostyle.js/test/files/"
    });
    var target = [DEST_DIR + "/**/*"];
    if (development) {
        target.push(VIVLIOSTYLE_JS_SRC_DIR + "/**/*");
    }
    gulp.watch(target).on("change", browserSync.reload);
}
gulp.task(
    "serve",
    gulp.series("watch", function(done) {
        serve(false);
        done();
    })
);
gulp.task(
    "serve-dev",
    gulp.series("watch-dev", function(done) {
        serve(true);
        done();
    })
);

gulp.task("default", gulp.task("serve-dev"));

// test
gulp.task("test-local", function(done) {
    var server = new KarmaServer(
        {
            configFile: process.cwd() + "/test/conf/karma-local.conf"
        },
        function(exitStatus) {
            done(exitStatus ? "Some tests failed" : undefined);
        }
    );
    server.start();
});
gulp.task("test-sauce", function(done) {
    var server = new KarmaServer(
        {
            configFile: process.cwd() + "/test/conf/karma-sauce.conf"
        },
        function(exitStatus) {
            done(exitStatus ? "Some tests failed" : undefined);
        }
    );
    server.start();
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var babel = require('gulp-babel');
var babelPluginDEV = require('fbjs-scripts/babel/dev-expression');
var babelPluginModules = require('fbjs-scripts/babel/rewrite-modules');
var del = require('del');
var derequire = require('gulp-derequire');
var envify = require('envify/custom');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var header = require('gulp-header');
var objectAssign = require('object-assign');
var runSequence = require('run-sequence');
var webpackStream = require('webpack-stream');

var DEVELOPMENT_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' */'
].join('\n') + '\n';
var PRODUCTION_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' *',
  ' * Copyright 2013-2015, Facebook, Inc.',
  ' * All rights reserved.',
  ' *',
  ' * This source code is licensed under the BSD-style license found in the',
  ' * LICENSE file in the root directory of this source tree. An additional grant',
  ' * of patent rights can be found in the PATENTS file in the same directory.',
  ' *',
  ' */'
].join('\n') + '\n';

var babelOpts = {
  nonStandard: true,
  loose: [
    'es6.classes'
  ],
  stage: 1,
  optional: ['runtime'],
  plugins: [babelPluginDEV, babelPluginModules],
  _moduleMap: objectAssign({}, require('fbjs/module-map'), {
    'React': 'react',
    'ReactDOM': 'react-dom',
    'StaticContainer.react': 'react-static-container'
  })
};

var buildDist = function(opts) {
  var webpackOpts = {
    debug: opts.debug,
    externals: {
      'react': 'React',
      'react-dom': 'ReactDOM'
    },
    module: {
      loaders: [
        {test: /\.js$/, loader: 'babel'}
      ],
    },
    output: {
      filename: opts.output,
      libraryTarget: 'umd',
      library: 'Relay'
    },
    plugins: [
      new webpackStream.webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(
          opts.debug ? 'development' : 'production'
        ),
      }),
      new webpackStream.webpack.optimize.OccurenceOrderPlugin(),
      new webpackStream.webpack.optimize.DedupePlugin()
    ]
  };
  if (!opts.debug) {
    webpackOpts.plugins.push(
      new webpackStream.webpack.optimize.UglifyJsPlugin({
        compress: {
          hoist_vars: true,
          screw_ie8: true,
          warnings: false
        }
      })
    );
  }
  return webpackStream(webpackOpts, null, function(err, stats) {
    if (err) {
      throw new gulpUtil.PluginError('webpack', err);
    }
    if (stats.compilation.errors.length) {
      throw new gulpUtil.PluginError('webpack', stats.toString());
    }
  });
};

var paths = {
  dist: 'dist',
  entry: 'lib/Relay.js',
  lib: 'lib',
  src: [
    '*src/**/*.js',
    '!src/**/__tests__/**/*.js',
    '!src/**/__mocks__/**/*.js'
  ],
};

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

gulp.task('modules', function() {
  return gulp
    .src(paths.src)
    .pipe(babel(babelOpts))
    .pipe(flatten())
    .pipe(gulp.dest(paths.lib));
});

gulp.task('dist', ['modules'], function () {
  var distOpts = {
    debug: true,
    output: 'relay.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(derequire())
    .pipe(header(DEVELOPMENT_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('dist:min', ['modules'], function () {
  var distOpts = {
    debug: false,
    output: 'relay.min.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(header(PRODUCTION_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('website:check-version', function(cb) {
  var version = require('./package').version;
  var websiteVersion = require('./website/core/SiteData').version;
  if (websiteVersion !== version) {
    return cb(
      new Error('Website version does not match package.json. Saw ' + websiteVersion + ' but expected ' + version)
    );
  }
  cb();
});

gulp.task('watch', function() {
  gulp.watch(paths.src, ['modules']);
});

gulp.task('default', function(cb) {
  runSequence('clean', 'website:check-version', 'modules', ['dist', 'dist:min'], cb);
});
<commit_msg>Remove unused envify require<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var babel = require('gulp-babel');
var babelPluginDEV = require('fbjs-scripts/babel/dev-expression');
var babelPluginModules = require('fbjs-scripts/babel/rewrite-modules');
var del = require('del');
var derequire = require('gulp-derequire');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var header = require('gulp-header');
var objectAssign = require('object-assign');
var runSequence = require('run-sequence');
var webpackStream = require('webpack-stream');

var DEVELOPMENT_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' */'
].join('\n') + '\n';
var PRODUCTION_HEADER = [
  '/**',
  ' * Relay v<%= version %>',
  ' *',
  ' * Copyright 2013-2015, Facebook, Inc.',
  ' * All rights reserved.',
  ' *',
  ' * This source code is licensed under the BSD-style license found in the',
  ' * LICENSE file in the root directory of this source tree. An additional grant',
  ' * of patent rights can be found in the PATENTS file in the same directory.',
  ' *',
  ' */'
].join('\n') + '\n';

var babelOpts = {
  nonStandard: true,
  loose: [
    'es6.classes'
  ],
  stage: 1,
  optional: ['runtime'],
  plugins: [babelPluginDEV, babelPluginModules],
  _moduleMap: objectAssign({}, require('fbjs/module-map'), {
    'React': 'react',
    'ReactDOM': 'react-dom',
    'StaticContainer.react': 'react-static-container'
  })
};

var buildDist = function(opts) {
  var webpackOpts = {
    debug: opts.debug,
    externals: {
      'react': 'React',
      'react-dom': 'ReactDOM'
    },
    module: {
      loaders: [
        {test: /\.js$/, loader: 'babel'}
      ],
    },
    output: {
      filename: opts.output,
      libraryTarget: 'umd',
      library: 'Relay'
    },
    plugins: [
      new webpackStream.webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(
          opts.debug ? 'development' : 'production'
        ),
      }),
      new webpackStream.webpack.optimize.OccurenceOrderPlugin(),
      new webpackStream.webpack.optimize.DedupePlugin()
    ]
  };
  if (!opts.debug) {
    webpackOpts.plugins.push(
      new webpackStream.webpack.optimize.UglifyJsPlugin({
        compress: {
          hoist_vars: true,
          screw_ie8: true,
          warnings: false
        }
      })
    );
  }
  return webpackStream(webpackOpts, null, function(err, stats) {
    if (err) {
      throw new gulpUtil.PluginError('webpack', err);
    }
    if (stats.compilation.errors.length) {
      throw new gulpUtil.PluginError('webpack', stats.toString());
    }
  });
};

var paths = {
  dist: 'dist',
  entry: 'lib/Relay.js',
  lib: 'lib',
  src: [
    '*src/**/*.js',
    '!src/**/__tests__/**/*.js',
    '!src/**/__mocks__/**/*.js'
  ],
};

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

gulp.task('modules', function() {
  return gulp
    .src(paths.src)
    .pipe(babel(babelOpts))
    .pipe(flatten())
    .pipe(gulp.dest(paths.lib));
});

gulp.task('dist', ['modules'], function () {
  var distOpts = {
    debug: true,
    output: 'relay.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(derequire())
    .pipe(header(DEVELOPMENT_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('dist:min', ['modules'], function () {
  var distOpts = {
    debug: false,
    output: 'relay.min.js'
  };
  return gulp.src(paths.entry)
    .pipe(buildDist(distOpts))
    .pipe(header(PRODUCTION_HEADER, {
      version: process.env.npm_package_version
    }))
    .pipe(gulp.dest(paths.dist));
});

gulp.task('website:check-version', function(cb) {
  var version = require('./package').version;
  var websiteVersion = require('./website/core/SiteData').version;
  if (websiteVersion !== version) {
    return cb(
      new Error('Website version does not match package.json. Saw ' + websiteVersion + ' but expected ' + version)
    );
  }
  cb();
});

gulp.task('watch', function() {
  gulp.watch(paths.src, ['modules']);
});

gulp.task('default', function(cb) {
  runSequence('clean', 'website:check-version', 'modules', ['dist', 'dist:min'], cb);
});
<|endoftext|>


<commit_before>'use strict';

//TODO remove when harmony_rest_parameters is enabled by default
require('harmonize')(['harmony_rest_parameters']);

//TODO remove when decorators land in node
require('babel-register');

const gulp = require('gulp');
const plugins = require( 'gulp-load-plugins' )();
// const isparta = require('isparta');
const del = require('del');

const TESTS = [
  // 'test/core/test-*.js',

  'test/core/test-error.js',
  'test/core/test-module.js',
  'test/core/test-modules.js',
  'test/core/test-params.js',
  'test/core/test-resource.js',
  'test/core/test-resources.js',
  'test/core/test-routes.js',
  'test/db/test-*.js',
  'test/util/test-*.js',

  // 'test/auth/test-*.js',
  // 'test/ws/test-*.js',
  // 'test/ws/util/test-*.js',
  // 'test/ravel/test-*.js',
  // 'test/**/test-*.js'
];

gulp.task('lint', function() {
  return gulp.src(['./lib/**/*.js', './test/**/*.js', 'gulpfile.js'])
             .pipe(plugins.eslint())
             .pipe(plugins.eslint.format())
             .pipe(plugins.eslint.failAfterError());
});

gulp.task('docco', function() {
  return gulp.src(['./lib/**/*.js'])
             .pipe(plugins.docco({
               layout: 'parallel'
             }))
             .pipe(gulp.dest('./docs'));
});

gulp.task('clean', function() {
  return del([
    'reports', 'docs'
  ]);
});

gulp.task('cover', ['lint'], function() {
  return gulp.src(['./lib/**/*.js'])
             .pipe(plugins.istanbul({
              //  instrumenter: isparta.Instrumenter,
               includeUntested: true
             }))
             .pipe(plugins.istanbul.hookRequire());
});

//necessary to locate issues in code, due to https://github.com/gotwarlost/istanbul/issues/274
gulp.task('test-no-cov', ['lint'], function () {
  const env = plugins.env.set({
    LOG_LEVEL : 'critical'
  });
  return gulp.src(TESTS)
    .pipe(env)
    .pipe(plugins.mocha({
      reporter: 'spec',
      quiet:false,
      colors:true,
      timeout: 10000
    }))
    .pipe(env.reset);
});

gulp.task('test', ['cover'], function () {
  const env = plugins.env.set({
    LOG_LEVEL : 'critical'
  });
  return gulp.src(TESTS)
    .pipe(env)
    .pipe(plugins.mocha({
      reporter: 'spec',
      quiet:false,
      colors:true,
      timeout: 10000
    }))
    // Creating the reports after tests ran
    .pipe(plugins.istanbul.writeReports({
      dir: './reports',
      reporters: [ 'lcov', 'json', 'text', 'text-summary', 'html']
    }))
    // Enforce a coverage of at least 100%
    .pipe(plugins.istanbul.enforceThresholds({ thresholds: { global: 100 } }))
    .pipe(env.reset);
});

gulp.task('watch', ['lint'], function() {
  gulp.watch(['./lib/**/*.js'], ['lint']);
  gulp.watch(['gulpfile.js', './test/**/*.js'], ['lint']);
});

gulp.task('coveralls', ['test'], function() {
  return gulp.src('reports/lcov.info')
             .pipe(plugins.coveralls());
});

gulp.task('show-coverage', function() {
  return gulp.src('./reports/index.html')
             .pipe(plugins.open());
});

gulp.task('show-docs', ['docco'], function() {
  return gulp.src('./docs/index.html')
             .pipe(plugins.open());
});

gulp.task('default', ['watch']);
gulp.task('travis', ['coveralls']);
//
// gulp.task('debug', () => {
//   const envs = plugins.env.set({
//     NODE_ENV: 'debug'
//   });
//   return gulp.src('src/main.js')
//     .pipe(envs)
//     .pipe(babel({optional: [
//       'utility.inlineEnvironmentconstiables'
//     ]}))
//     .pipe(uglify())
//     .pipe(transform(file => browserify(file).bundle()))
//     .pipe(envs.reset)
//     .pipe(gulp.dest('dist'));
// });
<commit_msg>Temporarily disabling coverage failure to send some data to coveralls.<commit_after>'use strict';

//TODO remove when harmony_rest_parameters is enabled by default
require('harmonize')(['harmony_rest_parameters']);

//TODO remove when decorators land in node
require('babel-register');

const gulp = require('gulp');
const plugins = require( 'gulp-load-plugins' )();
// const isparta = require('isparta');
const del = require('del');

const TESTS = [
  // 'test/core/test-*.js',

  'test/core/test-error.js',
  'test/core/test-module.js',
  'test/core/test-modules.js',
  'test/core/test-params.js',
  'test/core/test-resource.js',
  'test/core/test-resources.js',
  'test/core/test-routes.js',
  'test/db/test-*.js',
  'test/util/test-*.js',

  // 'test/auth/test-*.js',
  // 'test/ws/test-*.js',
  // 'test/ws/util/test-*.js',
  // 'test/ravel/test-*.js',
  // 'test/**/test-*.js'
];

gulp.task('lint', function() {
  return gulp.src(['./lib/**/*.js', './test/**/*.js', 'gulpfile.js'])
             .pipe(plugins.eslint())
             .pipe(plugins.eslint.format())
             .pipe(plugins.eslint.failAfterError());
});

gulp.task('docco', function() {
  return gulp.src(['./lib/**/*.js'])
             .pipe(plugins.docco({
               layout: 'parallel'
             }))
             .pipe(gulp.dest('./docs'));
});

gulp.task('clean', function() {
  return del([
    'reports', 'docs'
  ]);
});

gulp.task('cover', ['lint'], function() {
  return gulp.src(['./lib/**/*.js'])
             .pipe(plugins.istanbul({
              //  instrumenter: isparta.Instrumenter,
               includeUntested: true
             }))
             .pipe(plugins.istanbul.hookRequire());
});

//necessary to locate issues in code, due to https://github.com/gotwarlost/istanbul/issues/274
gulp.task('test-no-cov', ['lint'], function () {
  const env = plugins.env.set({
    LOG_LEVEL : 'critical'
  });
  return gulp.src(TESTS)
    .pipe(env)
    .pipe(plugins.mocha({
      reporter: 'spec',
      quiet:false,
      colors:true,
      timeout: 10000
    }))
    .pipe(env.reset);
});

gulp.task('test', ['cover'], function () {
  const env = plugins.env.set({
    LOG_LEVEL : 'critical'
  });
  return gulp.src(TESTS)
    .pipe(env)
    .pipe(plugins.mocha({
      reporter: 'spec',
      quiet:false,
      colors:true,
      timeout: 10000
    }))
    // Creating the reports after tests ran
    .pipe(plugins.istanbul.writeReports({
      dir: './reports',
      reporters: [ 'lcov', 'json', 'text', 'text-summary', 'html']
    }))
    // Enforce a coverage of at least 100%
    //.pipe(plugins.istanbul.enforceThresholds({ thresholds: { global: 100 } }))
    .pipe(env.reset);
});

gulp.task('watch', ['lint'], function() {
  gulp.watch(['./lib/**/*.js'], ['lint']);
  gulp.watch(['gulpfile.js', './test/**/*.js'], ['lint']);
});

gulp.task('coveralls', ['test'], function() {
  return gulp.src('reports/lcov.info')
             .pipe(plugins.coveralls());
});

gulp.task('show-coverage', function() {
  return gulp.src('./reports/index.html')
             .pipe(plugins.open());
});

gulp.task('show-docs', ['docco'], function() {
  return gulp.src('./docs/index.html')
             .pipe(plugins.open());
});

gulp.task('default', ['watch']);
gulp.task('travis', ['coveralls']);
//
// gulp.task('debug', () => {
//   const envs = plugins.env.set({
//     NODE_ENV: 'debug'
//   });
//   return gulp.src('src/main.js')
//     .pipe(envs)
//     .pipe(babel({optional: [
//       'utility.inlineEnvironmentconstiables'
//     ]}))
//     .pipe(uglify())
//     .pipe(transform(file => browserify(file).bundle()))
//     .pipe(envs.reset)
//     .pipe(gulp.dest('dist'));
// });
<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp');
var less = require('gulp-less');
var plumber = require('gulp-plumber');
var webserver = require('gulp-webserver');
var rename = require('gulp-rename');
var assemble = require('gulp-assemble');
var htmlmin = require('gulp-htmlmin');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rimraf = require('gulp-rimraf');
var awspublish = require('gulp-awspublish');
var foreach = require('gulp-foreach');
var path = require('path');

function formatPagePath(pagePath) {
  return pagePath
    .replace(path.resolve(process.cwd(), 'src/pages'), '')
    .replace(path.extname(pagePath), '.html');
}

gulp.task('clean', function (cb) {
  return gulp.src('./out/**/*', { read: false })
    .pipe(rimraf(cb));
});

var config = {
  styles: 'src/less/**/',
  stylesOut: 'out/css/',
  allStyle: '*.less',
  mainStyle: 'main.less',
  pages: './src/pages/**/*.hbs'
};

gulp.task('jshint', function () {
  gulp.src(['src/helpers/**/*.js', 'src/test/**/*.js', 'src/scripts/**/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('scripts', function() {
  gulp.src('./src/scripts/**/*.js')
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./out/scripts'));
});

gulp.task('test', function () {
  gulp.src(['src/test/**/*.js'], { read: false })
    .pipe(plumber())
    .pipe(mocha({
      // reporter: 'Spec' // throws error on drone.iteam.se - may need a separate npm module included?
    }));
});

gulp.task('connect', function () {
  gulp.src('./out/')
    .pipe(webserver({
      livereload: true
    }));
});

gulp.task('copy', function () {
  gulp.src(['bower_components/ionicons/fonts/*'])
    .pipe(gulp.dest('out/content/fonts'));

  gulp.src(['src/content/**/*'])
    .pipe(gulp.dest('out/content'));
});

gulp.task('less', function () {
  gulp.src(config.styles + config.mainStyle)
    .pipe(plumber())
    .pipe(less({
      compress: true
    }))
    .pipe(rename('iteam.css'))
    .pipe(gulp.dest(config.stylesOut));
});

var options = {
  partials: 'src/partials/*.hbs',
  layoutdir: 'src/layouts/',
  helpers: [
    'src/helpers/**/*.js',
    'node_modules/handlebars-helper-partial/index.js',
    'node_modules/handlebars-helpers/index.js'
  ]
};

gulp.task('assemble', function () {
  gulp.src(config.pages)
    .pipe(foreach(function (stream, file) {
      return stream
        .pipe(assemble(options))
        .pipe(htmlmin({
          collapseWhitespace:true
        }))
        .pipe(concat(formatPagePath(file.path)));
    }))
    .pipe(gulp.dest('./out'));
});

gulp.task('watch', function () {
  gulp.watch(['src/layouts/**/*', config.pages, 'src/partials/**/*.hbs', 'src/**/*.md'], ['assemble']);
  gulp.watch([config.styles + config.allStyle], ['less']);
  gulp.watch('src/content/**/*', ['copy']);
  gulp.watch(['src/helpers/**/*.js','src/test/**/*.js'], ['jshint', 'test']);
  gulp.watch('./src/scripts/**/*.js', ['jshint', 'scripts']);
});

gulp.on('err', function(e) {
  console.log(e.err.stack);
});

gulp.task('s3', function () {
  var aws = {
    key : process.env.AWS_ACCESS_KEY_ID,
    secret : process.env.AWS_SECRET_ACCESS_KEY,
    access: 'public-read',
    region: 'eu-west-1',
    bucket: 'test.iteam.se'
  };

  var publisher = awspublish.create(aws);

  var headers = {
    'Cache-Control': 'max-age=315360000, no-transform, public'
  };

  return gulp.src('./out/**/*')
    .pipe(awspublish.gzip())
    .pipe(publisher.publish(headers))
    .pipe(publisher.cache())
    .pipe(awspublish.reporter());
});

gulp.task('default', [
  'copy',
  'jshint',
  'scripts',
  'test',
  'less',
  'assemble',
  'connect',
  'watch'
]);

gulp.task('build', [
  'copy',
  'jshint',
  'scripts',
  'test',
  'less',
  'assemble'
]);

gulp.task('deploy:master', [
  'build',
  's3'
]);
<commit_msg>gulp copy and assemble wait for clean to be completed fix #42<commit_after>'use strict';
var gulp = require('gulp');
var less = require('gulp-less');
var plumber = require('gulp-plumber');
var webserver = require('gulp-webserver');
var rename = require('gulp-rename');
var assemble = require('gulp-assemble');
var htmlmin = require('gulp-htmlmin');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rimraf = require('gulp-rimraf');
var awspublish = require('gulp-awspublish');
var foreach = require('gulp-foreach');
var path = require('path');

function formatPagePath(pagePath) {
  return pagePath
    .replace(path.resolve(process.cwd(), 'src/pages'), '')
    .replace(path.extname(pagePath), '.html');
}

gulp.task('clean', function (cb) {
  return gulp.src('out/', { read: false })
    .pipe(rimraf(cb));
});

var config = {
  styles: 'src/less/**/',
  stylesOut: 'out/css/',
  allStyle: '*.less',
  mainStyle: 'main.less',
  pages: './src/pages/**/*.hbs'
};

gulp.task('jshint', function () {
  gulp.src(['src/helpers/**/*.js', 'src/test/**/*.js', 'src/scripts/**/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('scripts', function() {
  gulp.src('./src/scripts/**/*.js')
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./out/scripts'));
});

gulp.task('test', function () {
  gulp.src(['src/test/**/*.js'], { read: false })
    .pipe(plumber())
    .pipe(mocha({
      // reporter: 'Spec' // throws error on drone.iteam.se - may need a separate npm module included?
    }));
});

gulp.task('connect', function () {
  gulp.src('./out/')
    .pipe(webserver({
      livereload: true
    }));
});

gulp.task('copy', ['clean'], function () {
  gulp.src(['bower_components/ionicons/fonts/*'])
    .pipe(gulp.dest('out/content/fonts'));

  gulp.src(['src/content/**/*'])
    .pipe(gulp.dest('out/content'));
});

gulp.task('less', function () {
  gulp.src(config.styles + config.mainStyle)
    .pipe(plumber())
    .pipe(less({
      compress: true
    }))
    .pipe(rename('iteam.css'))
    .pipe(gulp.dest(config.stylesOut));
});

var options = {
  partials: 'src/partials/*.hbs',
  layoutdir: 'src/layouts/',
  helpers: [
    'src/helpers/**/*.js',
    'node_modules/handlebars-helper-partial/index.js',
    'node_modules/handlebars-helpers/index.js'
  ]
};

gulp.task('assemble', ['clean'], function () {
  gulp.src(config.pages)
    .pipe(foreach(function (stream, file) {
      return stream
        .pipe(assemble(options))
        .pipe(htmlmin({
          collapseWhitespace:true
        }))
        .pipe(concat(formatPagePath(file.path)));
    }))
    .pipe(gulp.dest('./out'));
});

gulp.task('watch', function () {
  gulp.watch(['src/layouts/**/*', config.pages, 'src/partials/**/*.hbs', 'src/**/*.md'], ['assemble']);
  gulp.watch([config.styles + config.allStyle], ['less']);
  gulp.watch('src/content/**/*', ['copy']);
  gulp.watch(['src/helpers/**/*.js','src/test/**/*.js'], ['jshint', 'test']);
  gulp.watch('./src/scripts/**/*.js', ['jshint', 'scripts']);
});

gulp.on('err', function(e) {
  console.log(e.err.stack);
});

gulp.task('s3', function () {
  var aws = {
    key : process.env.AWS_ACCESS_KEY_ID,
    secret : process.env.AWS_SECRET_ACCESS_KEY,
    access: 'public-read',
    region: 'eu-west-1',
    bucket: 'test.iteam.se'
  };

  var publisher = awspublish.create(aws);

  var headers = {
    'Cache-Control': 'max-age=315360000, no-transform, public'
  };

  return gulp.src('./out/**/*')
    .pipe(awspublish.gzip())
    .pipe(publisher.publish(headers))
    .pipe(publisher.cache())
    .pipe(awspublish.reporter());
});

gulp.task('default', [
  'clean',
  'copy',
  'jshint',
  'scripts',
  'test',
  'less',
  'assemble',
  'connect',
  'watch'
]);

gulp.task('build', [
  'clean',
  'copy',
  'jshint',
  'scripts',
  'test',
  'less',
  'assemble'
]);

gulp.task('deploy:master', [
  'build',
  's3'
]);
<|endoftext|>


<commit_before>var gulp = require("gulp");
var babelify = require("babelify");
var browserify = require("browserify");
var vinylSourceStream = require("vinyl-source-stream");
var vinylBuffer = require("vinyl-buffer");

gulp.task("default", function() {

});
gulp.task("script", function() {
	var sources = browserify({
		entries: "./src/js/inverted-index.js",
		debug: true
  })
  .transform(babelify.configure({
		presets: ["es2015"]
	}));

  return sources.bundle()
    .pipe(vinylSourceStream('app.min.js'))
    .pipe(vinylBuffer())
    .pipe(gulp.dest('./build/js/'));
});<commit_msg>add tasks to gulpfile.js that are used to  automate and reload pages.<commit_after>var gulp = require("gulp");
var babelify = require("babelify");
var browserify = require("browserify");
var cleanCSS = require("gulp-clean-css");
var vinylSourceStream = require("vinyl-source-stream");
var vinylBuffer = require("vinyl-buffer");

var plugins = require("gulp-load-plugins")();

var src = {
	html: "./src/**/*.html",
	css: "./src/css/style/style.css",
	sass: "./src/css/sass/materialize.scss",
	scripts: {
		all: "./src/js/**/*.js",
		app: "./src/js/inverted-index.js"
	}
};

var build = "./build/";
var out = {
	html: build + "*.html",
	css: build + "css/",
	customcss: build + "css/style",
	scripts: {
		file: "app.min.js",
		folder: build + "js/"
	}
};

gulp.task("default", function() {

});

gulp.task("sass", function() {
	return gulp.src(src.sass)
    .pipe(plugins.sass())
    .pipe(gulp.dest(out.css));
});

gulp.task("css", function() {
	return gulp.src(src.css)
    .pipe(cleanCSS())
    .pipe(gulp.dest(out.customcss))
		.pipe(plugins.connect.reload());
});

gulp.task("script", function() {
	var sources = browserify({
		entries: src.scripts.app,
		debug: true
  })
  .transform(babelify.configure({
		presets: ["es2015"]
	}));

  return sources.bundle()
    .pipe(vinylSourceStream(out.scripts.file))
    .pipe(vinylBuffer())
    .pipe(gulp.dest(out.scripts.folder));
});

gulp.task("html", function() {
	return gulp.src(src.html)
	.pipe(gulp.dest(build))
	.pipe(plugins.connect.reload());
});

/* The jshint task runs jshint with ES6 support. */
gulp.task("jshint", function() {
	return gulp.src(src.scripts.all)
		.pipe(plugins.jshint({
			esnext: true // Enable ES6 support
		}))
		.pipe(plugins.jshint.reporter("jshint-stylish"));
});

gulp.task("serve", ["build", "watch"], function() {
	plugins.connect.server({
		root: build,
		port: 8080,
		livereload: true,
		fallback: build + "index.html"
	});
});

gulp.task("watch", function() {
	gulp.watch(src.sass, ["sass"]);
	gulp.watch(src.css, ["css"]);
	gulp.watch(src.html, ["html"]);
	gulp.watch(src.scripts.all, ["script"]);
});

gulp.task("build", ["script", "sass", "css", "html"]);
gulp.task("default", ["serve"]);<|endoftext|>