<commit_before>/*
There here is YOUR config
This var is an example of the assets you can use in your own application.
The array KEYS correspond to the OUTPUT files/directories,
The array VALUES contain a LIST OF SOURCE FILES
*/
var config = {

    // The base output directory for all your assets
    "output_directory": "web",

    /**
     * This option is used to simply copy files into a new directory.
     * This is very useful when copying dist files of external components.
     * Example:
     *     "fonts/": [
     *         "node_modules/materialize-css/dist/fonts/*",
     *         "node_modules/bootstrap/dist/fonts/*"
     *     ]
     */
    "copy": {
    },

    /**
     * Here you can add other files to watch when using "gulp watch".
     * They will automatically run the "dump" command when modified.
     * It is VERY useful when you use massively less/sass "import" rules, for example.
     * Example:
        "src/AppBundle/Resources/public/less/*.less"
     */
    "files_to_watch": [
    ],

    /**
     * All files here are images that will be optimized/compressed with imagemin.
     * The key corresponds to the output directory (prepended with "output_directory" previous option).
     * Example:
        "images/": [
            "src/AppBundle/Resources/public/images/*"
        ]
     */
    "images": {
    },

    /**
     * All files from this section are parsed with LESS plugin and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
        "css/main_less.css": [
            "web/components/bootstrap/less/bootstrap.less",
            "src/AppBundle/Resources/public/less/main.less"
        ]
     */
    "less": {
    },

    /**
     * All files from this section are parsed with SASS plugin and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
        "css/main_sass.css": [
            "src/AppBundle/Resources/public/less/main.scss"
        ]
     */
    "sass": {
    },

    /**
     * All files from this section are just concatenated and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
        "css/main.css": [
            "src/AppBundle/Resources/public/css/main.css"
        ]
     */
    "css": {
    },

    /**
     * All files from this section are just concatenated and dumped into a JS file.
     * If using "--prod" in command line, will minify with "uglyflyjs".
     * Example:
        "js/main.js": [
            "web/components/bootstrap/dist/bootstrap-src.js",
            "src/AppBundle/Resources/public/css/main.js"
        ]
     */
    "js": {
    }
};

/*************** End config ***************/

// Everything AFTER this line of code is updatable to the latest version of this gulpfile.
// Check it out there if you need: https://github.com/Orbitale/Gulpfile

/************* Some helpers *************/

var GulpfileHelpers = {};
GulpfileHelpers.objectSize = function(object) {
    var size = 0, key;
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            size++;
        }
    }
    return size;
};

GulpfileHelpers.objectForEach = function(object, callback) {
    var key;
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            callback.apply(object, [key, object[key]]);
        }
    }
    return object;
};

/*************** Global vars ***************/

// These data are mostly used to introduce logic that will save memory and time.
var isProd    = process.argv.indexOf('--prod') >= 0;
var hasImages = GulpfileHelpers.objectSize(config.images) > 0;
var hasLess   = GulpfileHelpers.objectSize(config.less) > 0;
var hasSass   = GulpfileHelpers.objectSize(config.sass) > 0;
var hasCss    = GulpfileHelpers.objectSize(config.css) > 0;
var hasJs     = GulpfileHelpers.objectSize(config.js) > 0;

// Required extensions
var gulp       = require('gulp');
var gulpif     = require('gulp-if');
var watch      = require('gulp-watch');
var concat     = require('gulp-concat');
var uglyfly    = require('gulp-uglyfly');
var cleancss   = require('gulp-clean-css');
var sourcemaps = require('gulp-sourcemaps');

// Load other extensions only when having specific components. Saves memory & time execution.
var less     = hasLess   ? require('gulp-less')     : function(){ return {}; };
var sass     = hasSass   ? require('gulp-sass')     : function(){ return {}; };
var imagemin = hasImages ? require('gulp-imagemin') : function(){ return {}; };

/*************** Gulp tasks ***************/

/**
 * Dumps the LESS assets
 */
gulp.task('less', function() {
    var list = config.less,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(less())
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the SASS assets
 */
gulp.task('sass', function() {
    var list = config.sass,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(sass())
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Simply copy files into another directory.
 * Useful for simple "dist" files from node_modules directory, for example.
 */
gulp.task('copy', function() {
    let list = config.copy,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(gulp.dest(outputDir + assets_output))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Compress images.
 * Thanks to @docteurklein.
 */
gulp.task('images', function() {
    var list = config.images,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(imagemin({
                optimizationLevel: 7,
                progressive: true,
                interlaced: true
            }))
            .pipe(gulp.dest(outputDir + assets_output))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the CSS assets.
 */
gulp.task('css', function() {
    var list = config.css,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the JS assets
 */
gulp.task('js', function() {
    var list = config.js,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(sourcemaps.init())
            .pipe(concat({path: assets_output, cwd: ''}))
            .pipe(gulpif(isProd, uglyfly()))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Will watch for files and run "dump" for each modification
 */
gulp.task('watch', ['dump'], function() {
    var files_less = [],
        files_images = [],
        files_css = [],
        files_sass = [],
        files_js = [],
        callback = function(event) {
            console.log('File "' + event.path + '" updated');
        },
        other_files_to_watch = config.files_to_watch || [],
        files_to_watch = []
    ;

    console.info('Night gathers, and now my watch begins...');

    GulpfileHelpers.objectForEach(config.images, function(key, images){
        files_images.push(images);
        files_to_watch.push(images);
    });
    GulpfileHelpers.objectForEach(config.less, function(key, less){
        files_less.push(less);
        files_to_watch.push(less);
    });
    GulpfileHelpers.objectForEach(config.sass, function(key, sass){
        files_sass.push(sass);
        files_to_watch.push(sass);
    });
    GulpfileHelpers.objectForEach(config.css, function(key, css){
        files_css.push(css);
        files_to_watch.push(css);
    });
    GulpfileHelpers.objectForEach(config.js, function(key, js){
        files_js.push(js);
        files_to_watch.push(js);
    });

    if (files_to_watch.length) {
        console.info('Watching file(s):');
        // Flatten the array
        files_to_watch = [].concat.apply([], files_to_watch).sort();
        console.info("       > "+files_to_watch.join("\n       > "));
    }

    if (other_files_to_watch.length) {
        gulp.watch(other_files_to_watch, ['dump']).on('change', callback);
    }
    if (hasImages) {
        gulp.watch(files_images, ['images']).on('change', callback);
    }
    if (hasLess) {
        gulp.watch(files_less, ['less']).on('change', callback);
    }
    if (hasSass) {
        gulp.watch(files_sass, ['sass']).on('change', callback);
    }
    if (hasCss) {
        gulp.watch(files_css, ['css']).on('change', callback);
    }
    if (hasJs) {
        gulp.watch(files_js, ['js']).on('change', callback);
    }
});

/**
 * Runs all the needed commands to dump all assets and manifests
 */
var dumpTasks = [];
if (hasImages) { dumpTasks.push('images'); }
if (hasLess) { dumpTasks.push('less'); }
if (hasSass) { dumpTasks.push('sass'); }
if (hasCss) { dumpTasks.push('css'); }
if (hasJs) { dumpTasks.push('js'); }
gulp.task('dump', dumpTasks);

/**
 * Small user guide
 */
gulp.task('default', function(){
    console.info("");
    console.info("usage: gulp [command] [--prod]");
    console.info("");
    console.info("Options:");
    console.info("    --prod       If specified, will run clean-css and uglyfyjs when dumping the assets.");
    console.info("");
    console.info("Commands:");
    console.info("    copy         Copy the sources in the `config.copy` into a destination folder.");
    console.info("    images       Dumps the sources in the `config.images` parameter from image files.");
    console.info("    less         Dumps the sources in the `config.less` parameter from LESS files.");
    console.info("    sass         Dumps the sources in the `config.sass` parameter from SCSS files.");
    console.info("    css          Dumps the sources in the `config.css` parameter from plain CSS files.");
    console.info("    js           Dumps the sources in the `config.js` parameter from plain JS files.");
    console.info("    dump         Executes all the above commands.");
    console.info("    watch        Executes 'dump', then watches all sources, and dumps all assets once any file is updated.");
    console.info("");
});

// Gulpfile with a single var as configuration.
// License: MIT
// Author: 2016 - Alex "Pierstoval" Rock Ancelet <alex@orbitale.io>
// Repository: https://github.com/Orbitale/Gulpfile
<commit_msg>Migrate some code to ECMA6 and normalize comments<commit_after>/*
There here is YOUR config
This var is an example of the assets you can use in your own application.
The array KEYS correspond to the OUTPUT files/directories,
The array VALUES contain a LIST OF SOURCE FILES
*/
const config = {

    // The base output directory for all your assets
    "output_directory": "web",

    /**
     * This option is used to simply copy files into a new directory.
     * This is very useful when copying dist files of external components.
     * Example:
     *     "fonts/": [
     *         "node_modules/materialize-css/dist/fonts/*",
     *         "node_modules/bootstrap/dist/fonts/*"
     *     ]
     */
    "copy": {
    },

    /**
     * Here you can add other files to watch when using "gulp watch".
     * They will automatically run the "dump" command when modified.
     * It is VERY useful when you use massively less/sass "import" rules, for example.
     * Example:
     *     "src/AppBundle/Resources/public/less/*.less"
     */
    "files_to_watch": [
    ],

    /**
     * All files here are images that will be optimized/compressed with imagemin.
     * The key corresponds to the output directory (prepended with "output_directory" previous option).
     * Example:
     *     "images/": [
     *         "src/AppBundle/Resources/public/images/*"
     *     ]
     */
    "images": {
    },

    /**
     * All files from this section are parsed with LESS plugin and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
     *     "css/main_less.css": [
     *         "node_modules/bootstrap/less/bootstrap.less",
     *         "src/AppBundle/Resources/public/less/main.less"
     *     ]
     */
    "less": {
    },

    /**
     * All files from this section are parsed with SASS plugin and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
     *     "css/main_sass.css": [
     *         "src/AppBundle/Resources/public/less/main.scss"
     *     ]
     */
    "sass": {
    },

    /**
     * All files from this section are just concatenated and dumped into a CSS file.
     * If using "--prod" in command line, will minify with "clean-css".
     * Example:
     *     "css/main.css": [
     *         "src/AppBundle/Resources/public/css/main.css"
     *     ]
     */
    "css": {
    },

    /**
     * All files from this section are just concatenated and dumped into a JS file.
     * If using "--prod" in command line, will minify with "uglyflyjs".
     * Example:
     *     "js/main.js": [
     *         "web/components/bootstrap/dist/bootstrap-src.js",
     *         "src/AppBundle/Resources/public/css/main.js"
     *     ]
     */
    "js": {
    }
};

/*************** End config ***************/

// Everything AFTER this line of code is updatable to the latest version of this gulpfile.
// Check it out there if you need: https://github.com/Orbitale/Gulpfile

/************* Some helpers *************/

let GulpfileHelpers = {};
GulpfileHelpers.objectSize = function(object) {
    let size = 0, key;
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            size++;
        }
    }
    return size;
};

GulpfileHelpers.objectForEach = function(object, callback) {
    let key;
    for (key in object) {
        if (object.hasOwnProperty(key)) {
            callback.apply(object, [key, object[key]]);
        }
    }
    return object;
};

/*************** Global vars ***************/

// These data are mostly used to introduce logic that will save memory and time.
const isProd    = process.argv.indexOf('--prod') >= 0;
const hasImages = GulpfileHelpers.objectSize(config.images) > 0;
const hasLess   = GulpfileHelpers.objectSize(config.less) > 0;
const hasSass   = GulpfileHelpers.objectSize(config.sass) > 0;
const hasCss    = GulpfileHelpers.objectSize(config.css) > 0;
const hasJs     = GulpfileHelpers.objectSize(config.js) > 0;

// Required extensions
let gulp       = require('gulp');
let gulpif     = require('gulp-if');
let watch      = require('gulp-watch');
let concat     = require('gulp-concat');
let uglyfly    = require('gulp-uglyfly');
let cleancss   = require('gulp-clean-css');
let sourcemaps = require('gulp-sourcemaps');

// Load other extensions only when having specific components. Saves memory & time execution.
let less     = hasLess   ? require('gulp-less')     : function(){ return {}; };
let sass     = hasSass   ? require('gulp-sass')     : function(){ return {}; };
let imagemin = hasImages ? require('gulp-imagemin') : function(){ return {}; };

/*************** Gulp tasks ***************/

/**
 * Dumps the LESS assets
 */
gulp.task('less', function() {
    let list = config.less,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(less())
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the SASS assets
 */
gulp.task('sass', function() {
    let list = config.sass,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(sass())
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Simply copy files into another directory.
 * Useful for simple "dist" files from node_modules directory, for example.
 */
gulp.task('copy', function() {
    let list = config.copy,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(gulp.dest(outputDir + assets_output))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Compress images.
 * Thanks to @docteurklein.
 */
gulp.task('images', function() {
    let list = config.images,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(imagemin({
                optimizationLevel: 7,
                progressive: true,
                interlaced: true,
                verbose: true
            }))
            .pipe(gulp.dest(outputDir + assets_output))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the CSS assets.
 */
gulp.task('css', function() {
    let list = config.css,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(concat(assets_output))
            .pipe(gulpif(isProd, cleancss()))
            .pipe(concat(assets_output))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Dumps the JS assets
 */
gulp.task('js', function() {
    let list = config.js,
        outputDir = config.output_directory+'/',
        assets_output, assets, pipes, i, l
    ;
    for (assets_output in list) {
        if (!list.hasOwnProperty(assets_output)) { continue; }
        assets = list[assets_output];
        pipes = gulp
            .src(assets)
            .pipe(sourcemaps.init())
            .pipe(concat({path: assets_output, cwd: ''}))
            .pipe(gulpif(isProd, uglyfly()))
            .pipe(gulp.dest(outputDir))
        ;

        console.info(" [file+] "+assets_output+" >");
        for (i = 0, l = assets.length; i < l; i++) {
            console.info("       > "+assets[i]);
        }
    }
});

/**
 * Will watch for files and run "dump" for each modification
 */
gulp.task('watch', ['dump'], function() {
    let files_less = [],
        files_images = [],
        files_css = [],
        files_sass = [],
        files_js = [],
        callback = function(event) {
            console.log('File "' + event.path + '" updated');
        },
        other_files_to_watch = config.files_to_watch || [],
        files_to_watch = []
    ;

    console.info('Night gathers, and now my watch begins...');

    GulpfileHelpers.objectForEach(config.images, function(key, images){
        files_images.push(images);
        files_to_watch.push(images);
    });
    GulpfileHelpers.objectForEach(config.less, function(key, less){
        files_less.push(less);
        files_to_watch.push(less);
    });
    GulpfileHelpers.objectForEach(config.sass, function(key, sass){
        files_sass.push(sass);
        files_to_watch.push(sass);
    });
    GulpfileHelpers.objectForEach(config.css, function(key, css){
        files_css.push(css);
        files_to_watch.push(css);
    });
    GulpfileHelpers.objectForEach(config.js, function(key, js){
        files_js.push(js);
        files_to_watch.push(js);
    });

    if (files_to_watch.length) {
        console.info('Watching file(s):');
        // Flatten the array
        files_to_watch = [].concat.apply([], files_to_watch).sort();
        console.info("       > "+files_to_watch.join("\n       > "));
    }

    if (other_files_to_watch.length) {
        gulp.watch(other_files_to_watch, ['dump']).on('change', callback);
    }
    if (hasImages) {
        gulp.watch(files_images, ['images']).on('change', callback);
    }
    if (hasLess) {
        gulp.watch(files_less, ['less']).on('change', callback);
    }
    if (hasSass) {
        gulp.watch(files_sass, ['sass']).on('change', callback);
    }
    if (hasCss) {
        gulp.watch(files_css, ['css']).on('change', callback);
    }
    if (hasJs) {
        gulp.watch(files_js, ['js']).on('change', callback);
    }
});

/**
 * Runs all the needed commands to dump all assets and manifests
 */
let dumpTasks = [];
if (hasImages) { dumpTasks.push('images'); }
if (hasLess) { dumpTasks.push('less'); }
if (hasSass) { dumpTasks.push('sass'); }
if (hasCss) { dumpTasks.push('css'); }
if (hasJs) { dumpTasks.push('js'); }
gulp.task('dump', dumpTasks);

/**
 * Small user guide
 */
gulp.task('default', function(){
    console.info("");
    console.info("usage: gulp [command] [--prod]");
    console.info("");
    console.info("Options:");
    console.info("    --prod       If specified, will run clean-css and uglyfyjs when dumping the assets.");
    console.info("");
    console.info("Commands:");
    console.info("    copy         Copy the sources in the `config.copy` into a destination folder.");
    console.info("    images       Dumps the sources in the `config.images` parameter from image files.");
    console.info("    less         Dumps the sources in the `config.less` parameter from LESS files.");
    console.info("    sass         Dumps the sources in the `config.sass` parameter from SCSS files.");
    console.info("    css          Dumps the sources in the `config.css` parameter from plain CSS files.");
    console.info("    js           Dumps the sources in the `config.js` parameter from plain JS files.");
    console.info("    dump         Executes all the above commands.");
    console.info("    watch        Executes 'dump', then watches all sources, and dumps all assets once any file is updated.");
    console.info("");
});

// Gulpfile with a single var as configuration.
// License: MIT
// Author: 2016 - Alex "Pierstoval" Rock Ancelet <alex@orbitale.io>
// Repository: https://github.com/Orbitale/Gulpfile
<|endoftext|>


<commit_before>/* eslint amd:true */
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const nodemon = require('gulp-nodemon');
const bower = require('gulp-bower');
const browserSync = require('browser-sync');
const istanbul = require('gulp-istanbul');
const eslint = require('gulp-eslint');
const filter = require('gulp-filter');
const sass = require('gulp-sass');
require('dotenv').config();

const port = process.env.PORT;

const src = {
  scss: './public/css/common.scss'
};

const out = {
  css: './public/css/'
};

gulp.task('sass', () => gulp.src(src.scss)
  .pipe(sass())
  .pipe(gulp.dest(out.css)));

gulp.task('watch', () => {
  gulp.watch('app/views/**', browserSync.reload);
  gulp.watch(['public/js/**', 'app/**/*.js'], browserSync.reload);
  gulp.watch('public/views/**', browserSync.reload);
  gulp.watch(src.sass, ['sass']);
  gulp.watch('public/css/**', browserSync.reload);
});

gulp.task('nodemon', () => {
  nodemon({
    script: 'server.js',
    ext: 'js',
    env: { NODE_ENV: 'development' }
  });
});

gulp.task('pre-test', () => gulp.src(['test/**/*.js'])
  .pipe(istanbul({ includeUntested: true }))
  .pipe(istanbul.hookRequire()));

gulp.task('mochaTest', ['pre-test'], () => gulp.src(['./test/**/*.js'],
  {
    read: false
  })
  .pipe(mocha({ reporter: 'spec' }))
  .pipe(istanbul.writeReports({
    dir: './coverage',
    reporters: ['lcov'],
    reportOpts: { dir: './coverage' },
  }))
  .once('error', () => {
    process.exit(1);
  })
  .once('end', () => {
    process.exit();
  }));

gulp.task('bower', () => bower({
  cmd: 'install',
  directory: './public/lib',
  verbosity: 2
}));

gulp.task('serve', ['build', 'watch'], () => {
  browserSync({
    proxy: `localhost:${port}`,
    port: 5000,
    ui: {
      port: 5001
    },
    reloadOnRestart: true
  });
});

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

gulp.task('build', ['sass', 'nodemon', 'bower']);

gulp.task('lint', () => {
  const jsFilter = filter(['gulpfile.js', 'public/js/**/*.js',
    'test/**/*.js', 'app/**/*.js', 'public/lib/**/*.js']);
  return gulp.src('./**/*.js')
  .pipe(jsFilter)
  .pipe(eslint())
  .pipe(eslint.format());
});
<commit_msg>bug(browser-sync): fix browser sync error [Fixes #134209531]<commit_after>/* eslint amd:true */
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const nodemon = require('gulp-nodemon');
const bower = require('gulp-bower');
const browserSync = require('browser-sync');
const istanbul = require('gulp-istanbul');
const eslint = require('gulp-eslint');
const filter = require('gulp-filter');
const sass = require('gulp-sass');
require('dotenv').config();

const port = process.env.PORT;

const src = {
  scss: './public/css/common.scss'
};

const out = {
  css: './public/css/'
};

gulp.task('sass', () => gulp.src(src.scss)
  .pipe(sass())
  .pipe(gulp.dest(out.css)));

gulp.task('watch', () => {
  gulp.watch('app/views/**', browserSync.reload);
  gulp.watch(['public/js/**', 'app/**/*.js'], browserSync.reload);
  gulp.watch('public/views/**', browserSync.reload);
  gulp.watch(src.sass, ['sass']);
  gulp.watch('public/css/**', browserSync.reload);
});

gulp.task('nodemon', () => {
  nodemon({
    script: 'server.js',
    ext: 'js',
    env: { NODE_ENV: 'development' }
  });
});

gulp.task('pre-test', () => gulp.src(['test/**/*.js'])
  .pipe(istanbul({ includeUntested: true }))
  .pipe(istanbul.hookRequire()));

gulp.task('mochaTest', ['pre-test'], () => gulp.src(['./test/**/*.js'],
  {
    read: false
  })
  .pipe(mocha({ reporter: 'spec' }))
  .pipe(istanbul.writeReports({
    dir: './coverage',
    reporters: ['lcov'],
    reportOpts: { dir: './coverage' },
  }))
  .once('error', () => {
    process.exit(1);
  })
  .once('end', () => {
    process.exit();
  }));

gulp.task('bower', () => bower({
  cmd: 'install',
  directory: './public/lib',
  verbosity: 2
}));

gulp.task('serve', ['build', 'watch'], () => {
  browserSync({
    proxy: `localhost:${port}`,
    port: 5000,
    ui: {
      port: 5001
    },
    reloadOnRestart: true,
    ghostMode: false
  });
});

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

gulp.task('build', ['sass', 'nodemon', 'bower']);

gulp.task('lint', () => {
  const jsFilter = filter(['gulpfile.js', 'public/js/**/*.js',
    'test/**/*.js', 'app/**/*.js', 'public/lib/**/*.js']);
  return gulp.src('./**/*.js')
  .pipe(jsFilter)
  .pipe(eslint())
  .pipe(eslint.format());
});
<|endoftext|>


<commit_before>// =======================================================================
// Gulp Plugins
// =======================================================================
var gulp            = require('gulp'),
    gutil           = require('gulp-util'),
    jshint          = require('gulp-jshint'),
    stylish         = require('jshint-stylish'),
    concat          = require('gulp-concat'),
    clean           = require('gulp-clean'),
    streamify       = require('gulp-streamify'),
    uglify          = require('gulp-uglify'),
    sourcemaps      = require('gulp-sourcemaps'),
    less            = require('gulp-less-sourcemap'),
    prefix          = require('gulp-autoprefixer'),
    minifyCSS       = require('gulp-minify-css'),
    notify          = require('gulp-notify'),
    angularTplCache = require('gulp-angular-templatecache'),
    browserify      = require('browserify'),
    source          = require('vinyl-source-stream'),
    buffer          = require('vinyl-buffer'),
    runSequence     = require('run-sequence');

// =======================================================================
// File Paths
// =======================================================================
var filePath = {
    build: {
        dest: './dist/'
    },
    lint: {
        src: ['./app/*.js', './app/**/*.js']
    },
    browserify: {
        src: './app/app.js',
        watch: ['!./app/assets/libs/*.js','./app/*.js','./app/**/*.js']
    },
    styles: {
        src: './app/app.less',
        watch: ['./app/app.less','./app/**/*.less']
    },
    images: {
        src: './app/assets/images/*',
        watch: './app/assets/images/*',
        dest: './dist/images/'
    },
    vendorJS: {
        // These files will be bundled into a single vendor.js file that's called at the bottom of index.html
        src:
        [
            './libs/jquery/dist/jquery.min.js',
            './libs/bootstrap/dist/js/bootstrap.min.js'
        ]
    },
    vendorCSS: {
        src: ['./libs/bootstrap/dist/css/bootstrap.css']
    },
    copyIndex: {
        src: './app/index.html',
        watch: './app/index.html'
    }
};

// =======================================================================
// Server Settings for local development (Express Server)
// =======================================================================
var embedlr         = require('gulp-embedlr'),
    refresh         = require('gulp-livereload'),
    lrserver        = require('tiny-lr')(),
    express         = require('express'),
    livereload      = require('connect-livereload'),
    livereloadport  = 35729,
    serverport      = 5000,
    server          = express();

server.use(livereload({port: livereloadport}));
// Use our 'dist' folder as rootfolder
server.use(express.static('./dist'));
// Redirects everything back to our index.html
server.all('/*', function(req, res) {
    res.sendfile(filePath.copyIndex.src, { root: 'dist' });
});

// =======================================================================
// Dev Server Task
// =======================================================================
gulp.task('dev', function() {
    server.listen(serverport);
    lrserver.listen(livereloadport);
    console.log('Server running at http://localhost:5000');
});

// =======================================================================
// Clean out dist folder contents on build
// =======================================================================
gulp.task('clean', function () {
    return gulp.src(filePath.build.dest, {read: false})
        .pipe(clean());
});

// =======================================================================
// JSHint
// =======================================================================
gulp.task('lint', function() {
    return gulp.src(filePath.lint.src)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// =======================================================================
// Browserify
// =======================================================================
gulp.task('browserify', function() {
    return browserify(filePath.browserify.src)
        .bundle({ debug: true })
        .pipe(source('bundle.js'))
        .pipe(buffer())
    //    .pipe(streamify(uglify()))
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'Browserify task complete' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Styles Task
// =======================================================================
gulp.task('styles', function () {
    return gulp.src(filePath.styles.src)
        .pipe(less())
        .pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(minifyCSS())
        .pipe(gulp.dest(filePath.build.dest))
        // This next line will be displayed twice - once for the CSS file and once for the source map
        .pipe(notify({ message: 'Styles task complete' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Images Task
// =======================================================================
gulp.task('images', function() {
    return gulp.src(filePath.images.src)
    .pipe(gulp.dest(filePath.images.dest))
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(refresh(lrserver));
});

// =======================================================================
// Vendor JS Task
// =======================================================================
gulp.task('vendorJS', function () {
    return gulp.src(filePath.vendorJS.src)
        .pipe(concat("vendor.js"))
        .pipe(uglify())
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'VendorJS task complete' }))
});

// =======================================================================
// Vendor CSS Task
// =======================================================================
gulp.task('vendorCSS', function () {
    return gulp.src(filePath.vendorCSS.src)
        .pipe(concat("vendor.css"))
        .pipe(minifyCSS())
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'VendorCSS task complete' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Copy index.html
// =======================================================================
gulp.task('copyIndex', function () {
    return gulp.src(filePath.copyIndex.src)
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'index.html successfully copied' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Watch for changes
// =======================================================================
gulp.task('watch', function () {
    gulp.watch(filePath.browserify.watch, ['browserify']);
    gulp.watch(filePath.styles.watch, ['styles']);
    gulp.watch(filePath.images.watch, ['images']);
    gulp.watch(filePath.vendorJS.src, ['vendorJS']);
    gulp.watch(filePath.vendorCSS.src, ['vendorCSS']);
    gulp.watch(filePath.copyIndex.watch, ['copyIndex']);
    console.log('Watching...');
});

// =======================================================================
// Sequential Build Rendering
// =======================================================================
gulp.task('build', function(callback) {
    runSequence(
        ['clean', 'lint'],
        ['browserify', 'styles', 'images', 'vendorJS', 'vendorCSS', 'copyIndex'],
        ['dev', 'watch'],
        callback
    );
});

gulp.task('default',['build']);<commit_msg>Set up watchify for browserify build<commit_after>// =======================================================================
// Gulp Plugins
// =======================================================================
var gulp            = require('gulp'),
    gutil           = require('gulp-util'),
    jshint          = require('gulp-jshint'),
    stylish         = require('jshint-stylish'),
    concat          = require('gulp-concat'),
    clean           = require('gulp-clean'),
    streamify       = require('gulp-streamify'),
    uglify          = require('gulp-uglify'),
    sourcemaps      = require('gulp-sourcemaps'),
    less            = require('gulp-less-sourcemap'),
    prefix          = require('gulp-autoprefixer'),
    minifyCSS       = require('gulp-minify-css'),
    notify          = require('gulp-notify'),
    angularTplCache = require('gulp-angular-templatecache'),
    browserify      = require('browserify'),
    watchify        = require('watchify'),
    source          = require('vinyl-source-stream'),
    buffer          = require('vinyl-buffer'),
    runSequence     = require('run-sequence');

// =======================================================================
// File Paths
// =======================================================================
var filePath = {
    build: {
        dest: './dist/'
    },
    lint: {
        src: ['./app/*.js', './app/**/*.js']
    },
    browserify: {
        src: './app/app.js',
        watch: ['!./app/assets/libs/*.js','./app/*.js','./app/**/*.js', '/app/**/*.html']
    },
    styles: {
        src: './app/app.less',
        watch: ['./app/app.less','./app/**/*.less']
    },
    images: {
        src: './app/assets/images/*',
        watch: './app/assets/images/*',
        dest: './dist/images/'
    },
    vendorJS: {
        // These files will be bundled into a single vendor.js file that's called at the bottom of index.html
        src:
        [
            './libs/jquery/dist/jquery.min.js',
            './libs/bootstrap/dist/js/bootstrap.min.js'
        ]
    },
    vendorCSS: {
        src: ['./libs/bootstrap/dist/css/bootstrap.css']
    },
    copyIndex: {
        src: './app/index.html',
        watch: './app/index.html'
    }
};

// =======================================================================
// Server Settings for local development (Express Server)
// =======================================================================
var embedlr         = require('gulp-embedlr'),
    refresh         = require('gulp-livereload'),
    lrserver        = require('tiny-lr')(),
    express         = require('express'),
    livereload      = require('connect-livereload'),
    livereloadport  = 35729,
    serverport      = 5000,
    server          = express();

server.use(livereload({port: livereloadport}));
// Use our 'dist' folder as rootfolder
server.use(express.static('./dist'));
// Redirects everything back to our index.html
server.all('/*', function(req, res) {
    res.sendfile(filePath.copyIndex.src, { root: 'dist' });
});

// =======================================================================
// Dev Server Task
// =======================================================================
gulp.task('dev', function() {
    server.listen(serverport);
    lrserver.listen(livereloadport);
    console.log('Server running at http://localhost:5000');
});

// =======================================================================
// Clean out dist folder contents on build
// =======================================================================
gulp.task('clean', function () {
    return gulp.src(filePath.build.dest, {read: false})
        .pipe(clean());
});

// =======================================================================
// JSHint
// =======================================================================
gulp.task('lint', function() {
    return gulp.src(filePath.lint.src)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// =======================================================================
// Browserify
// =======================================================================
gulp.task('browserify', function() {
    var bundler = watchify(filePath.browserify.src);

    bundler.on('update', rebundle)

    function rebundle () {
        return bundler.bundle({ debug: true })
            .pipe(source('bundle.js'))
            .pipe(buffer())
        //    .pipe(streamify(uglify()))
            .pipe(gulp.dest(filePath.build.dest))
            .pipe(notify({ message: 'Browserify task complete' }))
            .pipe(refresh(lrserver));
    }

    return rebundle()
});

// =======================================================================
// Styles Task
// =======================================================================
gulp.task('styles', function () {
    return gulp.src(filePath.styles.src)
        .pipe(less())
        .pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(minifyCSS())
        .pipe(gulp.dest(filePath.build.dest))
        // This next line will be displayed twice - once for the CSS file and once for the source map
        .pipe(notify({ message: 'Styles task complete' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Images Task
// =======================================================================
gulp.task('images', function() {
    return gulp.src(filePath.images.src)
    .pipe(gulp.dest(filePath.images.dest))
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(refresh(lrserver));
});

// =======================================================================
// Vendor JS Task
// =======================================================================
gulp.task('vendorJS', function () {
    return gulp.src(filePath.vendorJS.src)
        .pipe(concat("vendor.js"))
        .pipe(uglify())
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'VendorJS task complete' }))
});

// =======================================================================
// Vendor CSS Task
// =======================================================================
gulp.task('vendorCSS', function () {
    return gulp.src(filePath.vendorCSS.src)
        .pipe(concat("vendor.css"))
        .pipe(minifyCSS())
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'VendorCSS task complete' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Copy index.html
// =======================================================================
gulp.task('copyIndex', function () {
    return gulp.src(filePath.copyIndex.src)
        .pipe(gulp.dest(filePath.build.dest))
        .pipe(notify({ message: 'index.html successfully copied' }))
        .pipe(refresh(lrserver));
});

// =======================================================================
// Watch for changes
// =======================================================================
gulp.task('watch', function () {
    gulp.watch(filePath.browserify.watch, ['browserify']);
    gulp.watch(filePath.styles.watch, ['styles']);
    gulp.watch(filePath.images.watch, ['images']);
    gulp.watch(filePath.vendorJS.src, ['vendorJS']);
    gulp.watch(filePath.vendorCSS.src, ['vendorCSS']);
    gulp.watch(filePath.copyIndex.watch, ['copyIndex']);
    console.log('Watching...');
});

// =======================================================================
// Sequential Build Rendering
// =======================================================================
gulp.task('build', function(callback) {
    runSequence(
        ['clean', 'lint'],
        ['browserify', 'styles', 'images', 'vendorJS', 'vendorCSS', 'copyIndex'],
        ['dev', 'watch'],
        callback
    );
});

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


<commit_before>/*!
 * gulp
 * $ npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    xml2json = require('gulp-xml2json');
    streamqueue = require('streamqueue');
    cssnano = require('gulp-cssnano');
    sourcemaps = require('gulp-sourcemaps');

var destination = process.env.GULP_DESTINATION || 'static';

// Copy
gulp.task('copyjson', function() {
  return gulp.src('themes/barricade/static/src/particlesjs-config.json')
    .pipe(gulp.dest(destination + '/src/'))
    .pipe(notify({ message: 'Copy json task complete' }));
});
gulp.task('copyfonts', function() {
  return gulp.src('themes/barricade/static/src/fonts/*')
    .pipe(gulp.dest(destination + '/src/fonts'))
    .pipe(notify({ message: 'Copy fonts task complete' }));
});
gulp.task('copy', function() {
    gulp.start('copyjson', 'copyfonts');
});

// Styles
gulp.task('styles', function() {
  return sass('themes/barricade/static/src/sass/styles.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(destination + '/src/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scriptconcat', function() {
  return gulp.src([
      'themes/barricade/static/src/js/custom/jquery.js',
      'themes/barricade/static/src/js/custom/foundation.js',
      'themes/barricade/static/src/js/custom/foundation.topbar.js',
      'themes/barricade/static/src/js/custom/foundation.offcanvas.js',
      'themes/barricade/static/src/js/custom/foundation.accordion.js',
      'themes/barricade/static/src/js/custom/foundation.dropdown.js',
      'themes/barricade/static/src/js/custom/foundation.slider.js',
      'themes/barricade/static/src/js/custom/foundation.tooltip.js',
      'themes/barricade/static/src/js/custom/particles.min.js',
      'themes/barricade/static/src/js/custom/headroom.min.js',
      'themes/barricade/static/src/js/custom/init.js'
    ])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('themes/barricade/static/src/js'))
    .pipe(notify({ message: 'Script concat task complete' }));
});
gulp.task('scriptminify', function() {
  return gulp.src([
      'themes/barricade/static/src/js/main.js',
      'themes/barricade/static/src/js/analytics.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    // .pipe(concat())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(destination + '/src/js'))
    .pipe(notify({ message: 'Script minify task complete' }));
});
gulp.task('scripts', function() {
    gulp.start('scriptconcat', 'scriptminify');
});

// Images
gulp.task('images', function() {
  return streamqueue({ objectMode: true },
    gulp.src('themes/barricade/static/src/img/**/*{.jpg,.png,.gif}')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(notify({ message: 'Images minifed' })),
    gulp.src('themes/barricade/static/src/img/**/*')
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(gulp.dest(destination + '/src/img'))
  )
});

// JSON
gulp.task('json', function () {
  return gulp.src(destination + '/index.xml')
    .pipe(xml2json())
    .pipe(rename({extname: '.json'}))
    .pipe(gulp.dest(destination + '/'))
    .pipe(notify({ message: 'JSON updated' }));
});

// Clean
gulp.task('clean', function() {
  return del(destination + '/src/**/*',  {force: true});
});

// Default task
gulp.task('default', ['clean'],  function() {
  gulp.start('styles', 'scripts', 'images', 'json', 'copy');
});

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

  // Watch .scss files
  gulp.watch('themes/barricade/static/src/sass/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('themes/barricade/static/src/js/custom/init.js', ['scripts']);

  // Watch image files
  gulp.watch('themes/barricade/static/img/src/**/*.{png,gif,jpg}', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in static/, reload on change
  gulp.watch([destination + '/**', destination + '/src/**']).on('change', livereload.changed);

});
<commit_msg>Intermediate step seems to be required 😅<commit_after>/*!
 * gulp
 * $ npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-cache del --save-dev
 */

// Load plugins
var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del');
    xml2json = require('gulp-xml2json');
    streamqueue = require('streamqueue');
    cssnano = require('gulp-cssnano');
    sourcemaps = require('gulp-sourcemaps');

var destination = process.env.GULP_DESTINATION || 'static';

// Copy
gulp.task('copyjson', function() {
  return gulp.src('themes/barricade/static/src/particlesjs-config.json')
    .pipe(gulp.dest(destination + '/src/'))
    .pipe(notify({ message: 'Copy json task complete' }));
});
gulp.task('copyfonts', function() {
  return gulp.src('themes/barricade/static/src/fonts/*')
    .pipe(gulp.dest(destination + '/src/fonts'))
    .pipe(notify({ message: 'Copy fonts task complete' }));
});
gulp.task('copy', function() {
    gulp.start('copyjson', 'copyfonts');
});

// Styles
gulp.task('styles', function() {
  return sass('themes/barricade/static/src/sass/styles.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('themes/barricade/static/src/css'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(sourcemaps.init())
    .pipe(cssnano())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(destination + '/src/css'))
    .pipe(notify({ message: 'Styles task complete' }));
});

// Scripts
gulp.task('scriptconcat', function() {
  return gulp.src([
      'themes/barricade/static/src/js/custom/jquery.js',
      'themes/barricade/static/src/js/custom/foundation.js',
      'themes/barricade/static/src/js/custom/foundation.topbar.js',
      'themes/barricade/static/src/js/custom/foundation.offcanvas.js',
      'themes/barricade/static/src/js/custom/foundation.accordion.js',
      'themes/barricade/static/src/js/custom/foundation.dropdown.js',
      'themes/barricade/static/src/js/custom/foundation.slider.js',
      'themes/barricade/static/src/js/custom/foundation.tooltip.js',
      'themes/barricade/static/src/js/custom/particles.min.js',
      'themes/barricade/static/src/js/custom/headroom.min.js',
      'themes/barricade/static/src/js/custom/init.js'
    ])
    .pipe(concat('main.js'))
    .pipe(gulp.dest('themes/barricade/static/src/js'))
    .pipe(notify({ message: 'Script concat task complete' }));
});
gulp.task('scriptminify', function() {
  return gulp.src([
      'themes/barricade/static/src/js/main.js',
      'themes/barricade/static/src/js/analytics.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    // .pipe(concat())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(destination + '/src/js'))
    .pipe(notify({ message: 'Script minify task complete' }));
});
gulp.task('scripts', function() {
    gulp.start('scriptconcat', 'scriptminify');
});

// Images
gulp.task('images', function() {
  return streamqueue({ objectMode: true },
    gulp.src('themes/barricade/static/src/img/**/*{.jpg,.png,.gif}')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(notify({ message: 'Images minifed' })),
    gulp.src('themes/barricade/static/src/img/**/*')
    .pipe(notify({ message: 'Images task complete' }))
    .pipe(gulp.dest(destination + '/src/img'))
  )
});

// JSON
gulp.task('json', function () {
  return gulp.src(destination + '/index.xml')
    .pipe(xml2json())
    .pipe(rename({extname: '.json'}))
    .pipe(gulp.dest(destination + '/'))
    .pipe(notify({ message: 'JSON updated' }));
});

// Clean
gulp.task('clean', function() {
  return del(destination + '/src/**/*',  {force: true});
});

// Default task
gulp.task('default', ['clean'],  function() {
  gulp.start('styles', 'scripts', 'images', 'json', 'copy');
});

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

  // Watch .scss files
  gulp.watch('themes/barricade/static/src/sass/**/*.scss', ['styles']);

  // Watch .js files
  gulp.watch('themes/barricade/static/src/js/custom/init.js', ['scripts']);

  // Watch image files
  gulp.watch('themes/barricade/static/img/src/**/*.{png,gif,jpg}', ['images']);

  // Create LiveReload server
  livereload.listen();

  // Watch any files in static/, reload on change
  gulp.watch([destination + '/**', destination + '/src/**']).on('change', livereload.changed);

});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var del = require('del');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var inject = require('gulp-inject');
var hash = require('gulp-hash');
var filenames = require('gulp-filenames');
var series = require('stream-series');

var appRoot = 'src/main/resources/static/';
var appDist = appRoot + 'dist/';
var libDist = appDist + 'lib/';
var bower_components = 'bower_components/';

var angularLibs = {
    name: 'angular',
    js: [
        bower_components + 'angular/angular.min.js',
        bower_components + 'angular-route/angular-route.min.js'
    ]
};

var app1 = {
    name: 'app1',
    html: appRoot + 'app1/app1.html',
    js: [
        appRoot + 'app1/app1.js',
        appRoot + 'app1/controllers/**/*.js',
        appRoot + 'app1/services/**/*.js'
    ]
};

var app2 = {
    name: 'app2',
    html: appRoot + 'app2/app2.html',
    js: [
        appRoot + 'app2/app2.js',
        appRoot + 'app2/controllers/**/*.js',
        appRoot + 'app2/services/**/*.js'
    ]
};

var concatJsTask = function (lib) {
    return gulp.src(lib.js)
        .pipe(concat(lib.name + '.js'))
        .pipe(hash())
        .pipe(filenames(lib.name + 'Js'))
        .pipe(gulp.dest(libDist));
};

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

gulp.task('build:angular-libs', function () {
    return concatJsTask(angularLibs);
});

gulp.task('scripts:app1', ['clean', 'build:angular-libs'], function () {
    return gulp.src(app1.js)
        .pipe(sourcemaps.init())
        .pipe(concat(app1.name + '.js'))
        .pipe(ngAnnotate())
        .pipe(uglify())
        .pipe(hash())
        .pipe(filenames(app1.name + 'Js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(appDist));
});

gulp.task('inject:app1', ['scripts:app1'], function () {
    var target = gulp.src(app1.html);
    var angularStream = gulp.src(libDist + filenames.get(angularLibs.name + 'Js'), {read: false});
    var appStream = gulp.src(appDist + filenames.get(app1.name + 'Js'), {read: false});

    return target
        .pipe(inject(series(angularStream, appStream), {read: false, relative: true}))
        .pipe(gulp.dest(appRoot + 'app1/'));
});

gulp.task('scripts:app2', ['clean', 'build:angular-libs'], function () {
    return gulp.src(app2.js)
        .pipe(sourcemaps.init())
        .pipe(concat(app2.name + '.js'))
        .pipe(ngAnnotate())
        .pipe(uglify())
        .pipe(hash())
        .pipe(filenames(app2.name + 'Js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(appDist));
});

gulp.task('inject:app2', ['scripts:app2'], function () {
    var target = gulp.src(app2.html);
    var angularStream = gulp.src(libDist + filenames.get(angularLibs.name + 'Js'), {read: false});
    var appStream = gulp.src(appDist + filenames.get(app2.name + 'Js'), {read: false});

    return target
        .pipe(inject(series(angularStream, appStream), {read: false, relative: true}))
        .pipe(gulp.dest(appRoot + 'app2/'));
});

gulp.task('scripts:all', ['inject:app1', 'inject:app2']);

gulp.task('default', ['scripts:all']);
<commit_msg>Refactored code. Generalized repeating code<commit_after>var gulp = require('gulp');
var del = require('del');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var inject = require('gulp-inject');
var hash = require('gulp-hash');
var filenames = require('gulp-filenames');
var series = require('stream-series');

var appRoot = 'src/main/resources/static/';
var appDist = appRoot + 'dist/';
var libDist = appDist + 'lib/';
var bower_components = 'bower_components/';

var angularLibs = {
    name: 'angular',
    js: [
        bower_components + 'angular/angular.min.js',
        bower_components + 'angular-route/angular-route.min.js'
    ]
};

var app1 = {
    name: 'app1',
    html: appRoot + 'app1/app1.html',
    htmlDest: appRoot + 'app1/',
    src: [
        appRoot + 'app1/app1.js',
        appRoot + 'app1/controllers/**/*.js',
        appRoot + 'app1/services/**/*.js'
    ]
};

var app2 = {
    name: 'app2',
    html: appRoot + 'app2/app2.html',
    htmlDest: appRoot + 'app2/',
    src: [
        appRoot + 'app2/app2.js',
        appRoot + 'app2/controllers/**/*.js',
        appRoot + 'app2/services/**/*.js'
    ]
};

var concatJsTask = function (lib) {
    return gulp.src(lib.js)
        .pipe(concat(lib.name + '.js'))
        .pipe(hash())
        .pipe(filenames(lib.name + 'Js'))
        .pipe(gulp.dest(libDist));
};

var angularScriptsTask = function (appConfig) {
    return gulp.src(appConfig.src)
        .pipe(sourcemaps.init())
        .pipe(concat(appConfig.name + '.js'))
        .pipe(ngAnnotate())
        .pipe(uglify())
        .pipe(hash())
        .pipe(filenames(appConfig.name + 'Js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(appDist));
};

var injectAppJsHtmlTask = function (appConfig) {
    var target = gulp.src(appConfig.html);
    var angularStream = gulp.src(libDist + filenames.get(angularLibs.name + 'Js'), {read: false});
    var appStream = gulp.src(appDist + filenames.get(appConfig.name + 'Js'), {read: false});

    return target
        .pipe(inject(series(angularStream, appStream), {read: false, relative: true}))
        .pipe(gulp.dest(appConfig.htmlDest));
};

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

gulp.task('build:angular-libs', function () {
    return concatJsTask(angularLibs);
});

gulp.task('scripts:app1', ['clean', 'build:angular-libs'], function () {
    return angularScriptsTask(app1);
});

gulp.task('inject:app1', ['scripts:app1'], function () {
    return injectAppJsHtmlTask(app1);
});

gulp.task('scripts:app2', ['clean', 'build:angular-libs'], function () {
    return angularScriptsTask(app2);
});

gulp.task('inject:app2', ['scripts:app2'], function () {
    return injectAppJsHtmlTask(app2);
});

gulp.task('scripts:all', ['inject:app1', 'inject:app2']);

gulp.task('default', ['scripts:all']);
<|endoftext|>


<commit_before>const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const sass = require('gulp-sass')
const plumber = require('gulp-plumber')
const gutil = require('gulp-util')
const fs = require('fs')
const juice = require('juice')
const path = require('path')
const information = require(path.join(__dirname, 'working/information.json'))
const html2txt = require('gulp-html2txt')
const cheerio = require('cheerio')
const mailgun = require('mailgun.js')
const imagemin = require('gulp-imagemin')
const postcss = require('gulp-postcss')
const uncss = require('postcss-uncss')

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', (done) => {
  return gulp.src('working/scss/*.scss')
    // plumber is used so that the watch task does not break when there is some wrong code
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(gulp.dest('working/css'))
    .pipe(browserSync.stream())
})

// Compile sass into CSS, remove unneeded CSS and dump it into the working folder for use in build process
// it is not neccessary to create a build CSS file just for the purpose of building the final email
gulp.task('css', () => {
  var plugins = [
    uncss({
      html: ['working/index.html']
    })
  ]
  return gulp.src('working/scss/*.scss')
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(postcss(plugins))
    .pipe(gulp.dest('working/css'))
})

/**
* replaces each instance of a replacelist key template in the string for the replacelist value
* @param {string}
* @param {object}
* @return {string}
*/
const replaceLinks = (str, replacelist = {}, customUrl = '') => {
  // there has to be a string to pass through even if replacelist is empty
  if (str.length < 1) throw new Error('File is empty')
  // if there is no replacelist or it is empty, pass through the value
  let html = str
  if (Object.keys(replacelist).length !== 0) {
    for (const key of Object.keys(replacelist)) {
      let replacestring = new RegExp(`#{${key}}`, 'gi')
      if (customUrl) {
        let url = customUrl.replace(/(#{url})/g, replacelist[key])
        html = html.replace(replacestring, url)
      } else {
        html = html.replace(replacestring, replacelist[key])
      }
    }
    let basicReg = /#{(.*?)}/g
    let els = html.match(basicReg)
    if (els !== null) {
      // find all matches and filter out the fluff
      // TODO think about if a set would be more appropriate as it would only list the unique values
      /*
      let allElements = new Set(els.map(x => x.replace('#{','').replace('}', '')))
      console.log(`Warning: there are still ${allElements.size} elements not replaced: ${[...allElements]}'`)
      */
      let allElements = els.map(x => x.replace('#{', '').replace('}', ''))
      console.log(`Warning: there are still ${allElements.length} instances not replaced: ${allElements}`)
    }
    return html
  } else {
    console.log('Warning: no links are provided, html goes through as is.')
    return str
  }
}

/**
* creates a url parameter string from the links object given
* @param {object}
* @return {string}
*/
const createParameterString = (parameters) => {
  let availableUtmKeys = ['source', 'medium', 'name', 'term', 'content']
  let paramsArr = []

  // check if the parameters exist, otherwise don't bother
  if (parameters.utm || parameters.custom) {
    // loop through all the utm and custom keys
    for (const paramKeys of Object.keys(parameters)) {
      // loop through the inner keys of utm and custom
      for (const key of Object.keys(parameters[paramKeys])) {
        // don't add if it is empty or if it is not a string or number
        if (parameters[paramKeys][key] && (typeof parameters[paramKeys][key] === 'string' || typeof parameters[paramKeys][key] === 'number')) {
          // only add the keys that are valid utm keys, ignore the ones that are not correct
          // IGNORE OR ERROR?
          if (paramKeys === 'utm' && availableUtmKeys.indexOf(key) !== -1) {
            paramsArr.push(`utm_${key}=${parameters[paramKeys][key]}`)
          } else if (paramKeys !== 'utm') { // if the keys are not utm, you are free to add them
            paramsArr.push(`${key}=${parameters[paramKeys][key]}`)
          }
        }
      }
    }
  }
  // joining all parameters in a string
  // if there are no parameters, create an empty string
  let paramsString = paramsArr.length !== 0 ? `?${paramsArr.join('&')}` : ''
  return paramsString
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @param {function}
* @return {string}
*/
const addParameters = (str, parameters = '', cheerio) => {
  // check if the createParameterString returns a non-empty string
  // to avoid all the work that is not needed
  if (parameters) {
    // load the cheerio instance for appending links
    const $ = cheerio.load(str, { decodeEntities: false })
    // create the parameter string that will be appended to each href

    // add the parameters to each href in the email
    $('a').each(function (i, el) {
      let origHref = $(this).attr('href')
      // if the split method returns an array that is longer than 1 element, it means that there is an existing parameter in it
      // append the parameters only if there is no existing parameters
      if (origHref.split('?').length === 1) {
        $(this).attr('href', origHref + parameters)
      }
    })
    return $.html()
  } else {
    // if there is nothing available, return as is
    return str
  }
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @return {string}
*/
const createHtml = (html, cssPath, addParameters, createParameterString, cheerio) => {
  return new Promise((resolve, reject) => {
    // replace the file path in the html file so that juice can find it, looking from the root of the project
    // replace the path for images since juice needs all files to be present
    let email = html.replace('<link rel="stylesheet" href="css/styles.css">', `<link rel="stylesheet" href="${cssPath}">`).replace('img/', 'working/img/')
    juice.juiceResources(email, { preserveMediaQueries: true, applyStyleTags: true }, (err, html) => {
      if (err) reject(err)
      // just create the html that will be used
      resolve(html)
    })
  })
}
// addParameters(replaceLinks(html, information.links), createParameterString(information.parameters), cheerio)
gulp.task('premailer', (done) => {
  fs.readFile('working/index.html', 'utf-8', (err, html) => {
    if (err) throw err
    createHtml(html, 'working/css/styles.css', addParameters, createParameterString, cheerio).then(html => {
      fs.writeFile('build/index.html', html.replace('working/img/', 'img/'), 'utf8', err => {
        if (err) {
          if (err.code === 'ENOENT') {
            fs.mkdir('build', err => {
              if (err) console.log(err)
              fs.writeFile('build/index.html', html.replace('working/img/', 'img/'), 'utf8', err => {
                if (err) console.log(err)
                done()
              })
            })
          }
        } else {
          done()
        }
      })
    }).catch(e => {
      console.log(e)
    })
  })
})

// convert html to txt
gulp.task('txt', () => {
  return gulp.src('build/index.html')
    .pipe(html2txt())
    .pipe(gulp.dest('build/'))
})

// start up browserSync
gulp.task('browserSync', (done) => {
  browserSync.init({
    server: 'working'
  })
  done()
})

// reload browserSync
gulp.task('reload', (done) => {
  browserSync.reload()
  done()
})

// watch scss and html files for changes
gulp.task('watchSassAndHtml', () => {
  gulp.watch('working/scss/*.scss', gulp.parallel('sass', 'reload'))
  gulp.watch('working/*.html', gulp.series('reload'))
})

// compress images
gulp.task('img', (done) => {
  return gulp.src('working/img/*')
    .pipe(imagemin())
    .pipe(gulp.dest('build/img'))
})

const sendmail = (done) => {
  const credentials = require('./credentials.json')
  const mg = mailgun.client({ username: 'api', key: process.env.MAILGUN_API_KEY || credentials.mailgun.key })
  const information = require('./working/information.json')
  const html = new Promise((resolve, reject) => {
    fs.readFile('./build/index.html', 'utf-8', (err, data) => {
      if (err) throw Error(err)
      if (data.length > 0) {
        let newData = data.replace(/img\/(.*?)"/gi, 'cid:$1"')
        resolve(newData)
      } else {
        reject('Empty file')
      }
    })
  })
  const text = new Promise((resolve, reject) => {
    fs.readFile('./build/index.txt', 'utf-8', (err, data) => {
      if (err) throw Error(err)
      if (data.length > 0) {
        resolve(data)
      } else {
        reject('Empty file')
      }
    })
  })
  const images = new Promise((resolve, reject) => {
    // read the path to the images and return a readStream for each file
    fs.readdir(path.join(__dirname, 'working', 'img'), (err, files) => {
      console.log(files)
      if (err) reject(err)
      const streamOfImages = files.map(img => {
        return fs.createReadStream(path.join(__dirname, 'working', 'img', img))
      })
      resolve(streamOfImages)
    })
  })
  const attachments = new Promise((resolve, reject) => {
    // read the path to the attachments and return a readStream for each file
    fs.readdir(path.join(__dirname, 'working', 'attachments'), (err, files) => {
      if (err) throw Error(err)
      const streamOfFiles = files
      .filter(file => {
        // .gitkeep should not be sent
        return file !== '.gitkeep'
      })
      .map(file => {
        return fs.createReadStream(path.join(__dirname, 'working', 'attachments', file))
      })
      resolve(streamOfFiles)
    })
  })
  Promise.all([html, text, images, attachments]).then(emails => {
    let [html, text, images, attachments] = emails
    mg.messages.create(credentials.mailgun.domain, {
      from: `${information.senderName} ${information.senderEmail}`,
      to: information.recipient,
      subject: information.subject,
      text: text,
      html: html,
      inline: images,
      attachment: attachments
    })
      .then(msg => {
        console.log(msg)
        done()
      }
      ) // logs response data
      .catch(err => {
        console.log(err)
        done()
      }) // logs any error
    done()
  }).catch(err => {
    console.log(err)
    done()
  })
}

gulp.task('links', (done) => {
  fs.readFile('./build/index.html', 'utf-8', (err, data) => {
    if (err) console.log(err)
    fs.writeFile('./build/index.html', addParameters(replaceLinks(data, information.links), createParameterString(information.parameters), cheerio), 'utf-8', err => {
      if (err) console.log(err)
      done()
    })
  })
})

gulp.task('email', gulp.series('css', 'premailer', 'txt', sendmail))
gulp.task('build', gulp.series('css', 'premailer', 'txt', 'img', 'links'))
gulp.task('serve', gulp.series('sass', gulp.parallel('browserSync', 'watchSassAndHtml')))

module.exports = {
  replaceLinks,
  addParameters,
  createParameterString,
  createHtml,
  sendmail
}
<commit_msg>remove unnecessary deps<commit_after>const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const sass = require('gulp-sass')
const plumber = require('gulp-plumber')
const gutil = require('gulp-util')
const fs = require('fs')
const juice = require('juice')
const path = require('path')
const information = require(path.join(__dirname, 'working/information.json'))
const html2txt = require('gulp-html2txt')
const cheerio = require('cheerio')
const mailgun = require('mailgun.js')
const imagemin = require('gulp-imagemin')
const postcss = require('gulp-postcss')
const uncss = require('postcss-uncss')

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', (done) => {
  return gulp.src('working/scss/*.scss')
    // plumber is used so that the watch task does not break when there is some wrong code
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(gulp.dest('working/css'))
    .pipe(browserSync.stream())
})

// Compile sass into CSS, remove unneeded CSS and dump it into the working folder for use in build process
// it is not neccessary to create a build CSS file just for the purpose of building the final email
gulp.task('css', () => {
  var plugins = [
    uncss({
      html: ['working/index.html']
    })
  ]
  return gulp.src('working/scss/*.scss')
    .pipe(plumber(function (error) {
      gutil.beep()
      console.log(error)
      this.emit('end')
    }))
    .pipe(sass())
    .pipe(postcss(plugins))
    .pipe(gulp.dest('working/css'))
})

/**
* replaces each instance of a replacelist key template in the string for the replacelist value
* @param {string}
* @param {object}
* @return {string}
*/
const replaceLinks = (str, replacelist = {}, customUrl = '') => {
  // there has to be a string to pass through even if replacelist is empty
  if (str.length < 1) throw new Error('File is empty')
  // if there is no replacelist or it is empty, pass through the value
  let html = str
  if (Object.keys(replacelist).length !== 0) {
    for (const key of Object.keys(replacelist)) {
      let replacestring = new RegExp(`#{${key}}`, 'gi')
      if (customUrl) {
        let url = customUrl.replace(/(#{url})/g, replacelist[key])
        html = html.replace(replacestring, url)
      } else {
        html = html.replace(replacestring, replacelist[key])
      }
    }
    let basicReg = /#{(.*?)}/g
    let els = html.match(basicReg)
    if (els !== null) {
      // find all matches and filter out the fluff
      // TODO think about if a set would be more appropriate as it would only list the unique values
      /*
      let allElements = new Set(els.map(x => x.replace('#{','').replace('}', '')))
      console.log(`Warning: there are still ${allElements.size} elements not replaced: ${[...allElements]}'`)
      */
      let allElements = els.map(x => x.replace('#{', '').replace('}', ''))
      console.log(`Warning: there are still ${allElements.length} instances not replaced: ${allElements}`)
    }
    return html
  } else {
    console.log('Warning: no links are provided, html goes through as is.')
    return str
  }
}

/**
* creates a url parameter string from the links object given
* @param {object}
* @return {string}
*/
const createParameterString = (parameters) => {
  let availableUtmKeys = ['source', 'medium', 'name', 'term', 'content']
  let paramsArr = []

  // check if the parameters exist, otherwise don't bother
  if (parameters.utm || parameters.custom) {
    // loop through all the utm and custom keys
    for (const paramKeys of Object.keys(parameters)) {
      // loop through the inner keys of utm and custom
      for (const key of Object.keys(parameters[paramKeys])) {
        // don't add if it is empty or if it is not a string or number
        if (parameters[paramKeys][key] && (typeof parameters[paramKeys][key] === 'string' || typeof parameters[paramKeys][key] === 'number')) {
          // only add the keys that are valid utm keys, ignore the ones that are not correct
          // IGNORE OR ERROR?
          if (paramKeys === 'utm' && availableUtmKeys.indexOf(key) !== -1) {
            paramsArr.push(`utm_${key}=${parameters[paramKeys][key]}`)
          } else if (paramKeys !== 'utm') { // if the keys are not utm, you are free to add them
            paramsArr.push(`${key}=${parameters[paramKeys][key]}`)
          }
        }
      }
    }
  }
  // joining all parameters in a string
  // if there are no parameters, create an empty string
  let paramsString = paramsArr.length !== 0 ? `?${paramsArr.join('&')}` : ''
  return paramsString
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @param {function}
* @return {string}
*/
const addParameters = (str, parameters = '', cheerio) => {
  // check if the createParameterString returns a non-empty string
  // to avoid all the work that is not needed
  if (parameters) {
    // load the cheerio instance for appending links
    const $ = cheerio.load(str, { decodeEntities: false })
    // create the parameter string that will be appended to each href

    // add the parameters to each href in the email
    $('a').each(function (i, el) {
      let origHref = $(this).attr('href')
      // if the split method returns an array that is longer than 1 element, it means that there is an existing parameter in it
      // append the parameters only if there is no existing parameters
      if (origHref.split('?').length === 1) {
        $(this).attr('href', origHref + parameters)
      }
    })
    return $.html()
  } else {
    // if there is nothing available, return as is
    return str
  }
}

/**
* replaces each instance of a href atrribute in the first argument for the values provided in the second argument
* @param {string}
* @param {string}
* @return {string}
*/
const createHtml = (html, cssPath) => {
  return new Promise((resolve, reject) => {
    // replace the file path in the html file so that juice can find it, looking from the root of the project
    // replace the path for images since juice needs all files to be present
    let email = html.replace('<link rel="stylesheet" href="css/styles.css">', `<link rel="stylesheet" href="${cssPath}">`).replace('img/', 'working/img/')
    juice.juiceResources(email, { preserveMediaQueries: true, applyStyleTags: true }, (err, html) => {
      if (err) reject(err)
      // just create the html that will be used
      resolve(html)
    })
  })
}
// addParameters(replaceLinks(html, information.links), createParameterString(information.parameters), cheerio)
gulp.task('premailer', (done) => {
  fs.readFile('working/index.html', 'utf-8', (err, html) => {
    if (err) throw err
    createHtml(html, 'working/css/styles.css', addParameters, createParameterString, cheerio).then(html => {
      fs.writeFile('build/index.html', html.replace('working/img/', 'img/'), 'utf8', err => {
        if (err) {
          if (err.code === 'ENOENT') {
            fs.mkdir('build', err => {
              if (err) console.log(err)
              fs.writeFile('build/index.html', html.replace('working/img/', 'img/'), 'utf8', err => {
                if (err) console.log(err)
                done()
              })
            })
          }
        } else {
          done()
        }
      })
    }).catch(e => {
      console.log(e)
    })
  })
})

// convert html to txt
gulp.task('txt', () => {
  return gulp.src('build/index.html')
    .pipe(html2txt())
    .pipe(gulp.dest('build/'))
})

// start up browserSync
gulp.task('browserSync', (done) => {
  browserSync.init({
    server: 'working'
  })
  done()
})

// reload browserSync
gulp.task('reload', (done) => {
  browserSync.reload()
  done()
})

// watch scss and html files for changes
gulp.task('watchSassAndHtml', () => {
  gulp.watch('working/scss/*.scss', gulp.parallel('sass', 'reload'))
  gulp.watch('working/*.html', gulp.series('reload'))
})

// compress images
gulp.task('img', (done) => {
  return gulp.src('working/img/*')
    .pipe(imagemin())
    .pipe(gulp.dest('build/img'))
})

const sendmail = (done) => {
  const credentials = require('./credentials.json')
  const mg = mailgun.client({ username: 'api', key: process.env.MAILGUN_API_KEY || credentials.mailgun.key })
  const information = require('./working/information.json')
  const html = new Promise((resolve, reject) => {
    fs.readFile('./build/index.html', 'utf-8', (err, data) => {
      if (err) throw Error(err)
      if (data.length > 0) {
        let newData = data.replace(/img\/(.*?)"/gi, 'cid:$1"')
        resolve(newData)
      } else {
        reject('Empty file')
      }
    })
  })
  const text = new Promise((resolve, reject) => {
    fs.readFile('./build/index.txt', 'utf-8', (err, data) => {
      if (err) throw Error(err)
      if (data.length > 0) {
        resolve(data)
      } else {
        reject('Empty file')
      }
    })
  })
  const images = new Promise((resolve, reject) => {
    // read the path to the images and return a readStream for each file
    fs.readdir(path.join(__dirname, 'working', 'img'), (err, files) => {
      console.log(files)
      if (err) reject(err)
      const streamOfImages = files.map(img => {
        return fs.createReadStream(path.join(__dirname, 'working', 'img', img))
      })
      resolve(streamOfImages)
    })
  })
  const attachments = new Promise((resolve, reject) => {
    // read the path to the attachments and return a readStream for each file
    fs.readdir(path.join(__dirname, 'working', 'attachments'), (err, files) => {
      if (err) throw Error(err)
      const streamOfFiles = files
      .filter(file => {
        // .gitkeep should not be sent
        return file !== '.gitkeep'
      })
      .map(file => {
        return fs.createReadStream(path.join(__dirname, 'working', 'attachments', file))
      })
      resolve(streamOfFiles)
    })
  })
  Promise.all([html, text, images, attachments]).then(emails => {
    let [html, text, images, attachments] = emails
    mg.messages.create(credentials.mailgun.domain, {
      from: `${information.senderName} ${information.senderEmail}`,
      to: information.recipient,
      subject: information.subject,
      text: text,
      html: html,
      inline: images,
      attachment: attachments
    })
      .then(msg => {
        console.log(msg)
        done()
      }
      ) // logs response data
      .catch(err => {
        console.log(err)
        done()
      }) // logs any error
    done()
  }).catch(err => {
    console.log(err)
    done()
  })
}

gulp.task('links', (done) => {
  fs.readFile('./build/index.html', 'utf-8', (err, data) => {
    if (err) console.log(err)
    fs.writeFile('./build/index.html', addParameters(replaceLinks(data, information.links), createParameterString(information.parameters), cheerio), 'utf-8', err => {
      if (err) console.log(err)
      done()
    })
  })
})

gulp.task('email', gulp.series('css', 'premailer', 'txt', sendmail))
gulp.task('build', gulp.series('css', 'premailer', 'txt', 'img', 'links'))
gulp.task('serve', gulp.series('sass', gulp.parallel('browserSync', 'watchSassAndHtml')))

module.exports = {
  replaceLinks,
  addParameters,
  createParameterString,
  createHtml,
  sendmail
}
<|endoftext|>


<commit_before>/* eslint-env node */

var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
var runSequence = require('run-sequence').use(gulp)

require('../yjs/gulpfile.helper.js')(gulp, {
  polyfills: [],
  entry: './src/Array.js',
  targetName: 'y-array.js',
  moduleName: 'y-array',
  specs: ['./src/Array.spec.js']
})

gulp.task('default', ['updateSubmodule'], function (cb) {
  gulp.src('package.json')
    .pipe($.prompt.prompt({
      type: 'checkbox',
      name: 'tasks',
      message: 'Which tasks would you like to run?',
      choices: [
        'test                    Test this project',
        'dev:browser             Watch files & serve the testsuite for the browser',
        'dev:nodejs              Watch filse & test this project with nodejs',
        'bump                    Bump the current state of the project',
        'publish                 Publish this project. Creates a github tag',
        'dist                    Build the distribution files'
      ]
    }, function (res) {
      var tasks = res.tasks.map(function (task) {
        return task.split(' ')[0]
      })
      if (tasks.length > 0) {
        console.info('gulp ' + tasks.join(' '))
        runSequence(tasks, cb)
      } else {
        console.info('Ok, .. goodbye')
      }
    }))
})
<commit_msg>implemented moduleName, made window statements failsafe<commit_after>/* eslint-env node */

var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
var runSequence = require('run-sequence').use(gulp)

require('../yjs/gulpfile.helper.js')(gulp, {
  polyfills: [],
  entry: './src/Array.js',
  targetName: 'y-array.js',
  moduleName: 'yArray',
  specs: ['./src/Array.spec.js']
})

gulp.task('default', ['updateSubmodule'], function (cb) {
  gulp.src('package.json')
    .pipe($.prompt.prompt({
      type: 'checkbox',
      name: 'tasks',
      message: 'Which tasks would you like to run?',
      choices: [
        'test                    Test this project',
        'dev:browser             Watch files & serve the testsuite for the browser',
        'dev:nodejs              Watch filse & test this project with nodejs',
        'bump                    Bump the current state of the project',
        'publish                 Publish this project. Creates a github tag',
        'dist                    Build the distribution files'
      ]
    }, function (res) {
      var tasks = res.tasks.map(function (task) {
        return task.split(' ')[0]
      })
      if (tasks.length > 0) {
        console.info('gulp ' + tasks.join(' '))
        runSequence(tasks, cb)
      } else {
        console.info('Ok, .. goodbye')
      }
    }))
})
<|endoftext|>


<commit_before>'use strict';

/**
 * Import node modules
 */
var gulp         = require('gulp');
var plumber      = require('gulp-plumber');
var stylus       = require('gulp-stylus');
var rename       = require('gulp-rename');
var postcss      = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var cssnano      = require('cssnano');
var zip          = require('gulp-zip');

var path = {
  src: {
    stylus: 'src/stylus'
  },
  dist: {
    css: 'dist/css'
  }
};

/**
 * Stylus to CSS
 */
gulp.task('css', function() {
  return gulp.src(
      [
        path.src.stylus + '/basis.styl',
        path.src.stylus + '/plugin/basis-ie9/basis-ie9.styl'
      ],
      {base: path.src.stylus }
    )
    .pipe(stylus({
      'resolve url nocheck': true
    }))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 2 versions'],
        cascade: false
      })
    ]))
    .pipe(gulp.dest(path.dist.css))
    .pipe(postcss([cssnano()]))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(path.dist.css));
});

/**
 * Auto Compile Stylus.
 */
gulp.task('watch', function() {
  gulp.watch([path.src.stylus + '/**/*/styl'], ['css']);
});

/**
 * Build
 */
gulp.task('build', ['css']);

/**
 * Release
 */
gulp.task('release', ['build'], function() {
  return gulp.src(
      [
        './**',
        '!node_modules',
        '!node_modules/**',
        '!bin',
        '!bin/**',
        '!.git',
        '!.gitignore',
        '!.travis.yml',
        '!**/.DS_Store'
      ],
      {base: './'}
    )
    .pipe( gulp.dest('release'));
} );

/**
 * Creates the zip file
 */
gulp.task('zip', ['release'], function(){
  return gulp.src(
      [
        'release/**',
        '!release/.git'
      ]
      , {base: './release'}
    )
    .pipe(zip('basis.zip'))
    .pipe(gulp.dest('./'));
});

gulp.task('default', ['build', 'watch']);
<commit_msg>Some fixes<commit_after>'use strict';

/**
 * Import node modules
 */
var gulp         = require('gulp');
var plumber      = require('gulp-plumber');
var stylus       = require('gulp-stylus');
var rename       = require('gulp-rename');
var postcss      = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var cssnano      = require('cssnano');
var zip          = require('gulp-zip');

var path = {
  src: {
    stylus: 'src/stylus'
  },
  dist: {
    css: 'dist/css'
  }
};

/**
 * Stylus to CSS
 */
gulp.task('css', function() {
  return gulp.src(
      [
        path.src.stylus + '/basis.styl',
        path.src.stylus + '/plugin/basis-ie9/basis-ie9.styl'
      ],
      {base: path.src.stylus }
    )
    .pipe(stylus({
      'resolve url nocheck': true
    }))
    .pipe(postcss([
      autoprefixer({
        browsers: ['last 2 versions'],
        cascade: false
      })
    ]))
    .pipe(gulp.dest(path.dist.css))
    .pipe(postcss([cssnano()]))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(path.dist.css));
});

/**
 * Auto Compile Stylus.
 */
gulp.task('watch', function() {
  gulp.watch([path.src.stylus + '/**/*/styl'], ['css']);
});

/**
 * Build
 */
gulp.task('build', ['css']);

/**
 * Release
 */
gulp.task('release', ['build'], function() {
  return gulp.src(
      [
        '**/*',
        '!node_modules',
        '!node_modules/**',
        '!bin',
        '!bin/**',
        '!.git',
        '!.gitignore',
        '!.travis.yml',
        '!**/.DS_Store'
      ],
      {base: './'}
    )
    .pipe( gulp.dest('release'));
} );

/**
 * Creates the zip file
 */
gulp.task('zip', ['release'], function(){
  return gulp.src(
      [
        'release/**',
        '!release/.git'
      ]
      , {base: './release'}
    )
    .pipe(zip('basis.zip'))
    .pipe(gulp.dest('./'));
});

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