<commit_before>// Инициализируем плагины
var lr = require('tiny-lr'), // Минивебсервер для livereload
    gulp = require('gulp'), // Сообственно Gulp JS
    jade = require('gulp-jade'), // Плагин для Jade
    htmlhint = require('gulp-htmlhint'),
    prettify = require('gulp-html-prettify'),
    stylus = require('gulp-stylus'), // Плагин для Stylus
    autoprefixer = require('gulp-autoprefixer'), // Расстановка префиксов
    livereload = require('gulp-livereload'), // Livereload для Gulp
    csso = require('gulp-csso'), // Минификация CSS
    imagemin = require('gulp-imagemin'), // Минификация изображений
    svgmin = require('gulp-svgmin'), // Минификация svg
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    uglify = require('gulp-uglify'), // Минификация JS
    concat = require('gulp-concat'), // Склейка файлов
    cache = require('gulp-cache'),
    //zip = require('gulp-zip'); // Архив собранного проекта
    connect = require('connect'), // Webserver
    server = lr();

// Собираем Stylus
gulp.task('stylus', function() {
    gulp.src('assets/styles/**/*.styl')
        .pipe(stylus()) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
    .pipe(gulp.dest('public/css/')) // записываем css
    .pipe(livereload(server)); // даем команду на перезагрузку css
});

// html
gulp.task('html', function(){
    gulp.src('assets/**/*.html')
        .pipe(htmlhint({
            "tag-pair": true,
            "style-disabled": true,
            "img-alt-require": true,
            "tagname-lowercase": true,
            "src-not-empty": true,
            "id-unique": true,
            "spec-char-escape": true
        }))
        .pipe(htmlhint.reporter())
        //.pipe(gulp.dest('public/'))
        .pipe(prettify({
            indent_char: ' ',
            indent_size: 4
        }))
        .pipe(gulp.dest('build/'))
        .pipe(livereload(server));
});

// Собираем html из Jade
gulp.task('jade', function() {
    gulp.src(['assets/template/*.jade', '!assets/template/_*.jade'])
        .pipe(jade({
            pretty: true
        }))  // Собираем Jade только в папке ./assets/template/ исключая файлы с _*
        .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    //.pipe(gulp.dest('public/')) // Записываем собранные файлы
    .pipe(htmlhint({
        "tag-pair": true,
        "style-disabled": true,
        "img-alt-require": true,
        "tagname-lowercase": true,
        "src-not-empty": true,
        "id-unique": true,
        "spec-char-escape": true
    }))
    .pipe(htmlhint.reporter())
    //.pipe(gulp.dest('public/'))
    .pipe(prettify({
        indent_char: ' ',
        indent_size: 4
    }))
    .pipe(gulp.dest('public/'))
    .pipe(livereload(server)); // даем команду на перезагрузку страницы
});

// Собираем JS
gulp.task('js', function() {
    gulp.src(['assets/js/**/*.js', '!assets/js/libs/**/*.js'])
        .pipe(concat('index.js')) // Собираем все JS, кроме тех которые находятся в ./assets/js/vendor/**
        .pipe(gulp.dest('public/js'))
        .pipe(livereload(server)); // даем команду на перезагрузку страницы
});

// Копируем и минимизируем изображения
gulp.task('images', function() {
    gulp.src(['assets/img/**/*', '!assets/img/**/*.svg'])
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(livereload(server))
        .pipe(gulp.dest('public/img'))
});

gulp.task('svgmin', function() {
    gulp.src('assets/img/**/*.svg')
        .pipe(svgmin())
        .pipe(gulp.dest('public/img'));
});

/*gulp.task('zip', function () {
    gulp.src('assets/*')
        .pipe(zip('archive.zip'))
        .pipe(gulp.dest('build'));
});*/

// Clean
gulp.task('clean', function() {
    return gulp.src(['build/css', 'build/js', 'build/img'], {read: false})
        .pipe(clean());
});

// Локальный сервер для разработки
gulp.task('http-server', function() {
    connect()
        .use(require('connect-livereload')())
        .use(connect.static('public'))
        .listen('9000');

    console.log('Server listening on http://localhost:9000');
});

// Запуск сервера разработки gulp watch
gulp.task('watch', function() {

    // Копируем, что не должно компилиться
    gulp.src('assets/styles/**/*.css').pipe(gulp.dest('public/css/'));
    gulp.src('assets/js/libs/*').pipe(gulp.dest('public/js/libs/'));
    // gulp.src('assets/**/*.html').pipe(gulp.dest('public/'));
    gulp.src('assets/static/**/*').pipe(gulp.dest('public/'));

    // Предварительная сборка проекта
    gulp.run('stylus');
    gulp.run('html');
    gulp.run('jade');
    gulp.run('images');
    gulp.run('svgmin');
    gulp.run('js');

    // Подключаем Livereload
    server.listen(35729, function(err) {
        if (err) return console.log(err);

        gulp.watch('assets/styles/**/*.styl', function() {
            gulp.run('stylus');
        });
        gulp.watch('assets/**/*.html', function() {
            gulp.run('html');
        });
        gulp.watch('assets/template/**/*.jade', function() {
            gulp.run('jade');
        });
        gulp.watch('assets/img/**/*', function() {
            gulp.run('images');
        });
        gulp.watch('assets/img/**/*.svg', function() {
            gulp.run('svgmin');
        });
        gulp.watch('assets/js/**/*', function() {
            gulp.run('js');
        });
    });
    gulp.run('http-server');
});

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

    // Копируем, что не должно компилиться
    gulp.src('assets/styles/**/*.css').pipe(gulp.dest('build/css/'));
    gulp.src('assets/js/libs/*').pipe(gulp.dest('build/js/libs/'));
    // gulp.src('assets/**/*.html').pipe(gulp.dest('build/'));
    gulp.src('assets/static/**/*').pipe(gulp.dest('build/'));

    // css
    gulp.src('assets/styles/**/*.styl')
        .pipe(stylus()) // собираем stylus
        .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(gulp.dest('build/css/')) // записываем css
        //.pipe(concat('allstyles.css'))
        .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(gulp.dest('build/css/'))
        .pipe(rename("allstyles.min.css"))
        .pipe(csso()) // минимизируем css
        .pipe(gulp.dest('build/css/')) // записываем css

    // html
    gulp.task('html', function(){
        gulp.src('assets/**/*.html')
            .pipe(htmlhint({
                "tag-pair": true,
                "style-disabled": true,
                "img-alt-require": true,
                "tagname-lowercase": true,
                "src-not-empty": true,
                "id-unique": true,
                "spec-char-escape": true
            }))
            .pipe(htmlhint.reporter())
            //.pipe(gulp.dest('build/'))
            .pipe(prettify({
                indent_char: ' ',
                indent_size: 4
            }))
            .pipe(gulp.dest('build/'))
            .pipe(livereload(server));
    });

    // jade
    gulp.src(['assets/template/*.jade', '!assets/template/_*.jade'])
        .pipe(jade({
            pretty: true
        }))
    //.pipe(gulp.dest('build/')) // Записываем собранные файлы
    .pipe(htmlhint({
        "tag-pair": true,
        "style-disabled": true,
        "img-alt-require": true,
        "tagname-lowercase": true,
        "src-not-empty": true,
        "id-unique": true,
        "spec-char-escape": true
    }))
    .pipe(htmlhint.reporter())
    //.pipe(gulp.dest('build/'))
    .pipe(prettify({
        indent_char: ' ',
        indent_size: 4
    }))
    .pipe(gulp.dest('build/'))
    .pipe(livereload(server)); // даем команду на перезагрузку страницы

    // js
    gulp.src(['assets/js/**/*.js', '!assets/js/libs/**/*.js'])
        .pipe(gulp.dest('build/js'))
        .pipe(concat('allscripts.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('build/js'));

    // image
    gulp.src(['assets/img/**/*', '!assets/img/**/*.svg'])
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('build/img'));

    gulp.src('assets/img/**/*.svg')
        .pipe(svgmin())
        .pipe(gulp.dest('build/img'));

});<commit_msg>add prettify html<commit_after>// Инициализируем плагины
var lr = require('tiny-lr'), // Минивебсервер для livereload
    gulp = require('gulp'), // Сообственно Gulp JS
    jade = require('gulp-jade'), // Плагин для Jade
    htmlhint = require('gulp-htmlhint'),
    prettify = require('gulp-html-prettify'),
    stylus = require('gulp-stylus'), // Плагин для Stylus
    autoprefixer = require('gulp-autoprefixer'), // Расстановка префиксов
    livereload = require('gulp-livereload'), // Livereload для Gulp
    csso = require('gulp-csso'), // Минификация CSS
    imagemin = require('gulp-imagemin'), // Минификация изображений
    svgmin = require('gulp-svgmin'), // Минификация svg
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    uglify = require('gulp-uglify'), // Минификация JS
    concat = require('gulp-concat'), // Склейка файлов
    cache = require('gulp-cache'),
    //zip = require('gulp-zip'); // Архив собранного проекта
    connect = require('connect'), // Webserver
    server = lr();

// Собираем Stylus
gulp.task('stylus', function() {
    gulp.src('assets/styles/**/*.styl')
        .pipe(stylus()) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
    .pipe(gulp.dest('public/css/')) // записываем css
    .pipe(livereload(server)); // даем команду на перезагрузку css
});

// html
gulp.task('html', function(){
    gulp.src('assets/**/*.html')
        .pipe(htmlhint({
            "tag-pair": true,
            "style-disabled": true,
            "img-alt-require": true,
            "tagname-lowercase": true,
            "src-not-empty": true,
            "id-unique": true,
            "spec-char-escape": true
        }))
        .pipe(htmlhint.reporter())
        //.pipe(gulp.dest('public/'))
        .pipe(prettify({
            indent_char: ' ',
            indent_size: 4
        }))
        .pipe(gulp.dest('public/'))
        .pipe(livereload(server));
});

// Собираем html из Jade
gulp.task('jade', function() {
    gulp.src(['assets/template/*.jade', '!assets/template/_*.jade'])
        .pipe(jade({
            pretty: true
        }))  // Собираем Jade только в папке ./assets/template/ исключая файлы с _*
        .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    //.pipe(gulp.dest('public/')) // Записываем собранные файлы
    .pipe(htmlhint({
        "tag-pair": true,
        "style-disabled": true,
        "img-alt-require": true,
        "tagname-lowercase": true,
        "src-not-empty": true,
        "id-unique": true,
        "spec-char-escape": true
    }))
    .pipe(htmlhint.reporter())
    //.pipe(gulp.dest('public/'))
    .pipe(prettify({
        indent_char: ' ',
        indent_size: 4
    }))
    .pipe(gulp.dest('public/'))
    .pipe(livereload(server)); // даем команду на перезагрузку страницы
});

// Собираем JS
gulp.task('js', function() {
    gulp.src(['assets/js/**/*.js', '!assets/js/libs/**/*.js'])
        .pipe(concat('index.js')) // Собираем все JS, кроме тех которые находятся в ./assets/js/vendor/**
        .pipe(gulp.dest('public/js'))
        .pipe(livereload(server)); // даем команду на перезагрузку страницы
});

// Копируем и минимизируем изображения
gulp.task('images', function() {
    gulp.src(['assets/img/**/*', '!assets/img/**/*.svg'])
        .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(livereload(server))
        .pipe(gulp.dest('public/img'))
});

gulp.task('svgmin', function() {
    gulp.src('assets/img/**/*.svg')
        .pipe(svgmin())
        .pipe(gulp.dest('public/img'));
});

/*gulp.task('zip', function () {
    gulp.src('assets/*')
        .pipe(zip('archive.zip'))
        .pipe(gulp.dest('build'));
});*/

// Clean
gulp.task('clean', function() {
    return gulp.src(['build/css', 'build/js', 'build/img'], {read: false})
        .pipe(clean());
});

// Локальный сервер для разработки
gulp.task('http-server', function() {
    connect()
        .use(require('connect-livereload')())
        .use(connect.static('public'))
        .listen('9000');

    console.log('Server listening on http://localhost:9000');
});

// Запуск сервера разработки gulp watch
gulp.task('watch', function() {

    // Копируем, что не должно компилиться
    gulp.src('assets/styles/**/*.css').pipe(gulp.dest('public/css/'));
    gulp.src('assets/js/libs/*').pipe(gulp.dest('public/js/libs/'));
    // gulp.src('assets/**/*.html').pipe(gulp.dest('public/'));
    gulp.src('assets/static/**/*').pipe(gulp.dest('public/'));

    // Предварительная сборка проекта
    gulp.run('stylus');
    gulp.run('html');
    gulp.run('jade');
    gulp.run('images');
    gulp.run('svgmin');
    gulp.run('js');

    // Подключаем Livereload
    server.listen(35729, function(err) {
        if (err) return console.log(err);

        gulp.watch('assets/styles/**/*.styl', function() {
            gulp.run('stylus');
        });
        gulp.watch('assets/**/*.html', function() {
            gulp.run('html');
        });
        gulp.watch('assets/template/**/*.jade', function() {
            gulp.run('jade');
        });
        gulp.watch('assets/img/**/*', function() {
            gulp.run('images');
        });
        gulp.watch('assets/img/**/*.svg', function() {
            gulp.run('svgmin');
        });
        gulp.watch('assets/js/**/*', function() {
            gulp.run('js');
        });
    });
    gulp.run('http-server');
});

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

    // Копируем, что не должно компилиться
    gulp.src('assets/styles/**/*.css').pipe(gulp.dest('build/css/'));
    gulp.src('assets/js/libs/*').pipe(gulp.dest('build/js/libs/'));
    // gulp.src('assets/**/*.html').pipe(gulp.dest('build/'));
    gulp.src('assets/static/**/*').pipe(gulp.dest('build/'));

    // css
    gulp.src('assets/styles/**/*.styl')
        .pipe(stylus()) // собираем stylus
        .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(gulp.dest('build/css/')) // записываем css
        //.pipe(concat('allstyles.css'))
        .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7"))
        .pipe(gulp.dest('build/css/'))
        .pipe(rename("allstyles.min.css"))
        .pipe(csso()) // минимизируем css
        .pipe(gulp.dest('build/css/')) // записываем css

    // html
    gulp.task('html', function(){
        gulp.src('assets/**/*.html')
            .pipe(htmlhint({
                "tag-pair": true,
                "style-disabled": true,
                "img-alt-require": true,
                "tagname-lowercase": true,
                "src-not-empty": true,
                "id-unique": true,
                "spec-char-escape": true
            }))
            .pipe(htmlhint.reporter())
            //.pipe(gulp.dest('build/'))
            .pipe(prettify({
                indent_char: ' ',
                indent_size: 4
            }))
            .pipe(gulp.dest('build/'))
            .pipe(livereload(server));
    });

    // jade
    gulp.src(['assets/template/*.jade', '!assets/template/_*.jade'])
        .pipe(jade({
            pretty: true
        }))
    //.pipe(gulp.dest('build/')) // Записываем собранные файлы
    .pipe(htmlhint({
        "tag-pair": true,
        "style-disabled": true,
        "img-alt-require": true,
        "tagname-lowercase": true,
        "src-not-empty": true,
        "id-unique": true,
        "spec-char-escape": true
    }))
    .pipe(htmlhint.reporter())
    //.pipe(gulp.dest('build/'))
    .pipe(prettify({
        indent_char: ' ',
        indent_size: 4
    }))
    .pipe(gulp.dest('build/'))
    .pipe(livereload(server)); // даем команду на перезагрузку страницы

    // js
    gulp.src(['assets/js/**/*.js', '!assets/js/libs/**/*.js'])
        .pipe(gulp.dest('build/js'))
        .pipe(concat('allscripts.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('build/js'));

    // image
    gulp.src(['assets/img/**/*', '!assets/img/**/*.svg'])
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('build/img'));

    gulp.src('assets/img/**/*.svg')
        .pipe(svgmin())
        .pipe(gulp.dest('build/img'));

});<|endoftext|>


<commit_before>var gulp      = require('gulp'),
    concat    = require('gulp-concat'),
    uglify    = require('gulp-uglify'),
    header    = require('gulp-header'),
    jshint    = require('gulp-jshint'),
    sass      = require('gulp-sass'),
    rename    = require('gulp-rename'),
    plumber   = require('gulp-plumber'),
    gutil     = require('gulp-util'),
    minifyCSS = require('gulp-minify-css'),
    nodemon   = require('gulp-nodemon'),
    meta      = require('./package.json');

    var srcDir  = './src/',
        jsDir   = './web/js/',
        cssDir  = './web/css/',
        sassDir = './src/sass/',
        expose  = [],
        dependencies = [
            './bower_components/angular/angular.js',
            './bower_components/angular-route/angular-route.js',
            './bower_components/angular-bootstrap-colorpicker/js/bootstrap-colorpicker-module.js',
            './bower_components/paper/dist/paper-full.js',
            './bower_components/createjs-soundjs/lib/soundjs-0.5.2.min.js',
            './bower_components/tom32i-event-emitter.js/dist/event-emitter.min.js',
            './bower_components/tom32i-option-resolver.js/dist/option-resolver.min.js',
            './bower_components/tom32i-gamepad.js/dist/gamepad.min.js',
            './bower_components/tom32i-key-mapper.js/dist/key-mapper.min.js'
        ],
        recipes = {
            server: require('./recipes/server.json'),
            client: require('./recipes/client.json')
        },
        banner = [
          '/*!',
          ' * <%= name %> <%= version %>',
          ' * <%= homepage %>',
          ' * <%= license %>',
          ' */\n\n'
        ].join('\n');

var onError = function (err) {
  gutil.beep();
  console.log(err.toString());
  this.emit('end');
};

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

gulp.task('front-expose', function() {
    gulp.src(dependencies)
        .pipe(concat('dependencies.js'))
        .pipe(uglify())
        .pipe(gulp.dest(recipes.client.path));

    for (var i = expose.length - 1; i >= 0; i--) {
        gulp.src(expose[i]).pipe(gulp.dest(recipes.client.path));
    }
});

gulp.task('front-full', function() {
    gulp.src(recipes.client.files)
        .pipe(concat(recipes.client.name))
        .pipe(header(banner, meta))
        .pipe(gulp.dest(recipes.client.path));
});

gulp.task('front-min', function(){
    gulp.src(recipes.client.files)
        .pipe(concat(recipes.client.name))
        .pipe(uglify())
        .pipe(header(banner, meta))
        .pipe(gulp.dest(recipes.client.path));
});

gulp.task('views', function(){
    gulp.src('src/client/views/**/*')
        .pipe(gulp.dest(jsDir + 'views'));
});

gulp.task('server', function() {
    gulp.src(recipes.server.files)
        .pipe(concat(recipes.server.name))
        .pipe(gulp.dest(recipes.server.path));
});

gulp.task('nodemon', function () {
    nodemon({
        watch: recipes.server.files
        ext: 'js',
        script: 'bin/curvytron.js',
        restartable: "rs"
    })
    .on('change', ['server', 'front-expose', 'front-full'])
    .on('restart', ['default'])
});

gulp.task('sass-full', function() {
  gulp.src(sassDir + 'style.scss')
    .pipe(plumber({ errorHandler: onError }))
    .pipe(sass())
    .pipe(rename('style.css'))
    .pipe(gulp.dest(cssDir));
});

gulp.task('sass-min', function() {
  gulp.src(sassDir + 'style.scss')
    .pipe(plumber({ errorHandler: onError }))
    .pipe(sass())
    .pipe(minifyCSS())
    .pipe(rename('style.css'))
    .pipe(gulp.dest(cssDir));
});

gulp.task('watch', ['dev', 'views', 'sass-full'], function () {
    gulp.watch('src/**/*.js', ['dev']);
    gulp.watch('src/client/views/**/*', ['views']);
    gulp.watch('src/**/*.scss', ['sass-full']);
});

gulp.task('default', ['jshint', 'server', 'front-expose', 'views', 'front-min', 'sass-min']);
gulp.task('dev', ['jshint', 'server', 'front-expose', 'views', 'front-full', 'sass-full']);
<commit_msg>Fixed gulpfile<commit_after>var gulp      = require('gulp'),
    concat    = require('gulp-concat'),
    uglify    = require('gulp-uglify'),
    header    = require('gulp-header'),
    jshint    = require('gulp-jshint'),
    sass      = require('gulp-sass'),
    rename    = require('gulp-rename'),
    plumber   = require('gulp-plumber'),
    gutil     = require('gulp-util'),
    minifyCSS = require('gulp-minify-css'),
    nodemon   = require('gulp-nodemon'),
    meta      = require('./package.json');

    var srcDir  = './src/',
        jsDir   = './web/js/',
        cssDir  = './web/css/',
        sassDir = './src/sass/',
        expose  = [],
        dependencies = [
            './bower_components/angular/angular.js',
            './bower_components/angular-route/angular-route.js',
            './bower_components/angular-bootstrap-colorpicker/js/bootstrap-colorpicker-module.js',
            './bower_components/paper/dist/paper-full.js',
            './bower_components/createjs-soundjs/lib/soundjs-0.5.2.min.js',
            './bower_components/tom32i-event-emitter.js/dist/event-emitter.min.js',
            './bower_components/tom32i-option-resolver.js/dist/option-resolver.min.js',
            './bower_components/tom32i-gamepad.js/dist/gamepad.min.js',
            './bower_components/tom32i-key-mapper.js/dist/key-mapper.min.js'
        ],
        recipes = {
            server: require('./recipes/server.json'),
            client: require('./recipes/client.json')
        },
        banner = [
          '/*!',
          ' * <%= name %> <%= version %>',
          ' * <%= homepage %>',
          ' * <%= license %>',
          ' */\n\n'
        ].join('\n');

var onError = function (err) {
  gutil.beep();
  console.log(err.toString());
  this.emit('end');
};

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

gulp.task('front-expose', function() {
    gulp.src(dependencies)
        .pipe(concat('dependencies.js'))
        .pipe(uglify())
        .pipe(gulp.dest(recipes.client.path));

    for (var i = expose.length - 1; i >= 0; i--) {
        gulp.src(expose[i]).pipe(gulp.dest(recipes.client.path));
    }
});

gulp.task('front-full', function() {
    gulp.src(recipes.client.files)
        .pipe(concat(recipes.client.name))
        .pipe(header(banner, meta))
        .pipe(gulp.dest(recipes.client.path));
});

gulp.task('front-min', function(){
    gulp.src(recipes.client.files)
        .pipe(concat(recipes.client.name))
        .pipe(uglify())
        .pipe(header(banner, meta))
        .pipe(gulp.dest(recipes.client.path));
});

gulp.task('views', function(){
    gulp.src('src/client/views/**/*')
        .pipe(gulp.dest(jsDir + 'views'));
});

gulp.task('server', function() {
    gulp.src(recipes.server.files)
        .pipe(concat(recipes.server.name))
        .pipe(gulp.dest(recipes.server.path));
});

gulp.task('nodemon', function () {
    nodemon({
        watch: recipes.server.files,
        ext: 'js',
        script: 'bin/curvytron.js',
        restartable: "rs"
    })
    .on('change', ['server', 'front-expose', 'front-full'])
    .on('restart', ['default'])
});

gulp.task('sass-full', function() {
  gulp.src(sassDir + 'style.scss')
    .pipe(plumber({ errorHandler: onError }))
    .pipe(sass())
    .pipe(rename('style.css'))
    .pipe(gulp.dest(cssDir));
});

gulp.task('sass-min', function() {
  gulp.src(sassDir + 'style.scss')
    .pipe(plumber({ errorHandler: onError }))
    .pipe(sass())
    .pipe(minifyCSS())
    .pipe(rename('style.css'))
    .pipe(gulp.dest(cssDir));
});

gulp.task('watch', ['dev', 'views', 'sass-full'], function () {
    gulp.watch('src/**/*.js', ['dev']);
    gulp.watch('src/client/views/**/*', ['views']);
    gulp.watch('src/**/*.scss', ['sass-full']);
});

gulp.task('default', ['jshint', 'server', 'front-expose', 'views', 'front-min', 'sass-min']);
gulp.task('dev', ['jshint', 'server', 'front-expose', 'views', 'front-full', 'sass-full']);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    php = require('gulp-connect-php'),
    sass,
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    svgstore = require('gulp-svgstore'),
    path = require('path'),
    svgmin = require('gulp-svgmin'),
    svgfallback = require('gulp-svgfallback'),
    svg2png = require('gulp-svg2png'),
    inject = require('gulp-inject'),
    browserSync = require('browser-sync').create(),
    rename = require('gulp-rename'),
    config = require('./gulp-config.js');

function errorlog (error) {
  console.error.bind(error);
  this.emit('end');
}

// browser-sync
gulp.task('browser-sync', ['js'], function() {
  browserSync.init(config.browserSync);

  gulp.watch(config.watch.js, ['js']);
  gulp.watch(config.watch.html).on('change', browserSync.reload);
});

// JS Task
gulp.task('gn', function () {
  return gulp.src(config.gn)
    .pipe(concat('go-native.js'))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gn-min', function () {
  return gulp.src(config.dest + '/go-native.js')
    .pipe(sourcemaps.init())
    .pipe(rename('go-native.min.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write(config.mapdest))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gnie8', function () {
  return gulp.src(config.gnie8)
    .pipe(concat('go-native.ie8.js'))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gnie8-min', function () {
  return gulp.src(config.dest + '/go-native.ie8.js')
    .pipe(sourcemaps.init())
    .pipe(rename('go-native.ie8.min.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write(config.mapdest))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

// js tasks
gulp.task('js', [
  'gn',
  'gn-min',
  'gnie8',
  'gnie8-min',
]);

// Default Task
gulp.task('default', [
  'browser-sync',
  'js',
]);  <commit_msg>update gulpfile<commit_after>var gulp = require('gulp'),
    php = require('gulp-connect-php'),
    sass,
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    svgstore = require('gulp-svgstore'),
    path = require('path'),
    svgmin = require('gulp-svgmin'),
    svgfallback = require('gulp-svgfallback'),
    svg2png = require('gulp-svg2png'),
    inject = require('gulp-inject'),
    browserSync = require('browser-sync').create(),
    rename = require('gulp-rename'),
    config = require('./gulp-config.js');

function errorlog (error) {
  console.error.bind(error);
  this.emit('end');
}

// browser-sync
gulp.task('browser-sync', function() {
  browserSync.init(config.browserSync);
});

// Watch
gulp.task('watch', function () {
  gulp.watch(config.watch.js, ['js']);
  gulp.watch(config.watch.html).on('change', browserSync.reload);
});

// JS Task
gulp.task('gn', function () {
  return gulp.src(config.gn)
    .pipe(concat('go-native.js'))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gn-min', ['gn'], function () {
  return gulp.src(config.dest + '/go-native.js')
    .pipe(sourcemaps.init())
    .pipe(rename('go-native.min.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write(config.mapdest))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gnie8', function () {
  return gulp.src(config.gnie8)
    .pipe(concat('go-native.ie8.js'))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

gulp.task('gnie8-min', ['gnie8'], function () {
  return gulp.src(config.dest + '/go-native.ie8.js')
    .pipe(sourcemaps.init())
    .pipe(rename('go-native.ie8.min.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write(config.mapdest))
    .on('error', errorlog)
    .pipe(gulp.dest(config.dest))
    .pipe(browserSync.stream());
});

// js tasks
gulp.task('js', [
  'gn-min',
  'gnie8-min',
]);

// Default Task
gulp.task('default', [
  'browser-sync',
  'js',
  'watch',
]);  <|endoftext|>


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

gulp.task('default', function _default() {
  // place code for your default task here
});
<commit_msg>Run lint through gulp.<commit_after>const gulp = require('gulp');
const eslint = require('gulp-eslint');

gulp.task('lint', function () {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['wger/nutrition/static/js/nutrition.js','!node_modules/**'])
        // eslint() attaches the lint output to the "eslint" property
        // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failAfterError last.
        .pipe(eslint.failAfterError());
});

gulp.task('default', ['lint'], function () {
    // This will only run if the lint task is successful...
});
<|endoftext|>


<commit_before>const babel = require('gulp-babel');
const cssnano = require('cssnano');
const gulp = require('gulp');
const postcss = require('gulp-postcss');
const postcssNested = require('postcss-nested');
const postcsssSimpleVars = require('postcss-simple-vars');
const pug = require('gulp-pug');
const uglify = require('gulp-uglify');

gulp.task('build', () => {
  gulp.src('app/src/pug/*')
    .pipe(pug())
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/src/css/*')
    .pipe(postcss([postcsssSimpleVars, postcssNested, cssnano]))
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/src/js/*')
    .pipe(babel({presets: ['es2015']}))
    .pipe(uglify())
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/main.js')
    .pipe(babel({presets: ['es2015']}))
    .pipe(uglify())
    .pipe(gulp.dest('app/dist'));
});

gulp.task('watch', ['build'], () => {
  gulp.watch('app/src/**', ['build']);
});
<commit_msg>Auto inject inline SVGs :robot_face:<commit_after>const babel = require('gulp-babel');
const cssnano = require('cssnano');
const gulp = require('gulp');
const injectSvg = require('gulp-inject-svg');
const postcss = require('gulp-postcss');
const postcssNested = require('postcss-nested');
const postcsssSimpleVars = require('postcss-simple-vars');
const pug = require('gulp-pug');
const uglify = require('gulp-uglify');

gulp.task('build', () => {
  gulp.src('app/src/pug/*')
    .pipe(pug())
    .pipe(injectSvg())
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/src/css/*')
    .pipe(postcss([postcsssSimpleVars, postcssNested, cssnano]))
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/src/js/*')
    .pipe(babel({presets: ['es2015']}))
    .pipe(uglify())
    .pipe(gulp.dest('app/dist'));

  gulp.src('app/main.js')
    .pipe(babel({presets: ['es2015']}))
    .pipe(uglify())
    .pipe(gulp.dest('app/dist'));
});

gulp.task('watch', ['build'], () => {
  gulp.watch('app/src/**', ['build']);
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  fs = require('fs'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  testConfig = require('./config/env/test'),
  glob = require('glob'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  pngquant = require('imagemin-pngquant'),
  wiredep = require('wiredep').stream,
  path = require('path'),
  endOfLine = require('os').EOL,
  protractor = require('gulp-protractor').protractor,
  webdriver_update = require('gulp-protractor').webdriver_update,
  webdriver_standalone = require('gulp-protractor').webdriver_standalone,
  del = require('del'),
  KarmaServer = require('karma').Server,
  semver = require('semver');

// Local settings
var changedTestFiles = [];

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
  process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {

  // Node.js v7 and newer use different debug argument
  var debugArgument = semver.satisfies(process.versions.node, '>=7.0.0') ? '--inspect' : '--debug';

  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: [debugArgument],
    ext: 'js,html',
    verbose: true,
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Nodemon task without verbosity or debugging
gulp.task('nodemon-nodebug', function () {
  return plugins.nodemon({
    script: 'server.js',
    ext: 'js,html',
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Watch Files For Changes
gulp.task('watch', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.refresh.changed);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.server.gulpConfig, ['templatecache', 'eslint']);
    gulp.watch(defaultAssets.client.views, ['templatecache']).on('change', plugins.refresh.changed);
  } else {
    gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.refresh.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
        }
      });
    });

    plugins.refresh.changed();
  });
});

// CSS linting task
gulp.task('csslint', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.formatter());
    // Don't fail CSS issues yet
    // .pipe(plugins.csslint.failFormatter());
});

// ESLint JS linting task
gulp.task('eslint', function () {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format());
});

// JS minifying task
gulp.task('uglify', function () {
  var assets = _.union(
    defaultAssets.client.js,
    defaultAssets.client.templates
  );
  del(['public/dist/*']);

  return gulp.src(assets)
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csso())
    .pipe(plugins.concat('application.min.css'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Imagemin task
gulp.task('imagemin', function () {
  return gulp.src(defaultAssets.client.img)
    .pipe(plugins.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: [pngquant()]
    }))
    .pipe(gulp.dest('public/dist/img'));
});

// wiredep task to default
gulp.task('wiredep', function () {
  return gulp.src('config/assets/default.js')
    .pipe(wiredep({
      ignorePath: '../../'
    }))
    .pipe(gulp.dest('config/assets/'));
});

// wiredep task to production
gulp.task('wiredep:prod', function () {
  return gulp.src('config/assets/production.js')
    .pipe(wiredep({
      ignorePath: '../../',
      fileTypes: {
        js: {
          replace: {
            css: function (filePath) {
              var minFilePath = filePath.replace('.css', '.min.css');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            },
            js: function (filePath) {
              var minFilePath = filePath.replace('.js', '.min.js');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            }
          }
        }
      }
    }))
    .pipe(gulp.dest('config/assets/'));
});

// Copy local development environment config example
gulp.task('copyLocalEnvConfig', function () {
  var src = [];
  var renameTo = 'local-development.js';

  // only add the copy source if our destination file doesn't already exist
  if (!fs.existsSync('config/env/' + renameTo)) {
    src.push('config/env/local.example.js');
  }

  return gulp.src(src)
    .pipe(plugins.rename(renameTo))
    .pipe(gulp.dest('config/env'));
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', function () {
  return fs.mkdir('modules/users/client/img/profile/uploads', function (err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
  });
});

// Angular template cache task
gulp.task('templatecache', function () {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.templateCache('templates.js', {
      root: '/modules/',
      module: 'core',
      templateHeader: '(function () {' + endOfLine + '	\'use strict\';' + endOfLine + endOfLine + '	angular' + endOfLine + '		.module(\'<%= module %>\'<%= standalone %>)' + endOfLine + '		.run(templates);' + endOfLine + endOfLine + '	templates.$inject = [\'$templateCache\'];' + endOfLine + endOfLine + '	function templates($templateCache) {' + endOfLine,
      templateBody: '		$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '	}' + endOfLine + '})();' + endOfLine
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  var mongooseService = require('./config/lib/mongoose');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongooseService.connect(function (db) {
    // Load mongoose models
    mongooseService.loadModels();

    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        mongooseService.disconnect(function (err) {
          if (err) {
            console.log('Error disconnecting from database');
            console.log(err);
          }

          return done(error);
        });
      });
  });
});

// Prepare istanbul coverage test
gulp.task('pre-test', function () {

  // Display coverage for all server JavaScript files
  return gulp.src(defaultAssets.server.allJS)
    // Covering files
    .pipe(plugins.istanbul())
    // Force `require` to return covered files
    .pipe(plugins.istanbul.hookRequire());
});

// Run istanbul test and write report
gulp.task('mocha:coverage', ['pre-test', 'mocha'], function () {
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;

  return gulp.src(testSuites)
    .pipe(plugins.istanbul.writeReports({
      reportOpts: { dir: './coverage/server' }
    }));
});

// Karma test runner task
gulp.task('karma', function (done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js'
  }, done).start();
});

// Run karma with coverage options set and write report
gulp.task('karma:coverage', function(done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    preprocessors: {
      'modules/*/client/views/**/*.html': ['ng-html2js'],
      'modules/core/client/app/config.js': ['coverage'],
      'modules/core/client/app/init.js': ['coverage'],
      'modules/*/client/*.js': ['coverage'],
      'modules/*/client/config/*.js': ['coverage'],
      'modules/*/client/controllers/*.js': ['coverage'],
      'modules/*/client/directives/*.js': ['coverage'],
      'modules/*/client/services/*.js': ['coverage']
    },
    reporters: ['progress', 'coverage'],
    coverageReporter: {
      dir: 'coverage/client',
      reporters: [
        { type: 'lcov', subdir: '.' }
        // printing summary to console currently weirdly causes gulp to hang so disabled for now
        // https://github.com/karma-runner/karma-coverage/issues/209
        // { type: 'text-summary' }
      ]
    }
  }, done).start();
});

// Drops the MongoDB database, used in e2e testing
gulp.task('dropdb', function (done) {
  // Use mongoose configuration
  var mongooseService = require('./config/lib/mongoose');

  mongooseService.connect(function (db) {
    db.dropDatabase(function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log('Successfully dropped db: ', db.databaseName);
      }

      mongooseService.disconnect(done);
    });
  });
});

// Downloads the selenium webdriver if protractor version is compatible
gulp.task('webdriver_update', webdriver_update);

// Start the standalone selenium server
// NOTE: This is not needed if you reference the
// seleniumServerJar in your protractor.conf.js
gulp.task('webdriver_standalone', webdriver_standalone);

// Protractor test runner task
gulp.task('protractor', ['webdriver_update'], function () {
  gulp.src([])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('end', function() {
      console.log('E2E Testing complete');
      // exit with success.
      process.exit(0);
    })
    .on('error', function(err) {
      console.error('E2E Tests failed:');
      console.error(err);
      process.exit(1);
    });
});

// Lint CSS and JavaScript files.
gulp.task('lint', function (done) {
  runSequence('less', 'sass', ['csslint', 'eslint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function (done) {
  runSequence('env:dev', 'wiredep:prod', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function (done) {
  runSequence('env:test', 'test:server', 'karma', 'nodemon', 'protractor', done);
});

gulp.task('test:server', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function (done) {
  runSequence('test:server', 'watch:server:run-tests', done);
});

gulp.task('test:client', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'karma', done);
});

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});

gulp.task('test:coverage', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha:coverage', 'karma:coverage', done);
});

// Run the project in development mode with node debugger enabled
gulp.task('default', function (done) {
  runSequence('env:dev', ['copyLocalEnvConfig', 'makeUploadsDir'], 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function (done) {
  runSequence(['copyLocalEnvConfig', 'makeUploadsDir', 'templatecache'], 'build', 'env:prod', 'lint', ['nodemon-nodebug', 'watch'], done);
});
<commit_msg>fix(gulp): fix broken test:server:watch task (#1842)<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  fs = require('fs'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  testConfig = require('./config/env/test'),
  glob = require('glob'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  pngquant = require('imagemin-pngquant'),
  wiredep = require('wiredep').stream,
  path = require('path'),
  endOfLine = require('os').EOL,
  protractor = require('gulp-protractor').protractor,
  webdriver_update = require('gulp-protractor').webdriver_update,
  webdriver_standalone = require('gulp-protractor').webdriver_standalone,
  del = require('del'),
  KarmaServer = require('karma').Server,
  semver = require('semver');

// Local settings
var changedTestFiles = [];

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
  process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {

  // Node.js v7 and newer use different debug argument
  var debugArgument = semver.satisfies(process.versions.node, '>=7.0.0') ? '--inspect' : '--debug';

  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: [debugArgument],
    ext: 'js,html',
    verbose: true,
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Nodemon task without verbosity or debugging
gulp.task('nodemon-nodebug', function () {
  return plugins.nodemon({
    script: 'server.js',
    ext: 'js,html',
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  });
});

// Watch Files For Changes
gulp.task('watch', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.refresh.changed);
  gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.refresh.changed);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.server.gulpConfig, ['templatecache', 'eslint']);
    gulp.watch(defaultAssets.client.views, ['templatecache']).on('change', plugins.refresh.changed);
  } else {
    gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.refresh.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.refresh.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
          plugins.refresh.changed(f);
        }
      });
    });
  });
});

// CSS linting task
gulp.task('csslint', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.formatter());
    // Don't fail CSS issues yet
    // .pipe(plugins.csslint.failFormatter());
});

// ESLint JS linting task
gulp.task('eslint', function () {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format());
});

// JS minifying task
gulp.task('uglify', function () {
  var assets = _.union(
    defaultAssets.client.js,
    defaultAssets.client.templates
  );
  del(['public/dist/*']);

  return gulp.src(assets)
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csso())
    .pipe(plugins.concat('application.min.css'))
    .pipe(plugins.rev())
    .pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(gulp.dest('./modules/'));
});

// Imagemin task
gulp.task('imagemin', function () {
  return gulp.src(defaultAssets.client.img)
    .pipe(plugins.imagemin({
      progressive: true,
      svgoPlugins: [{ removeViewBox: false }],
      use: [pngquant()]
    }))
    .pipe(gulp.dest('public/dist/img'));
});

// wiredep task to default
gulp.task('wiredep', function () {
  return gulp.src('config/assets/default.js')
    .pipe(wiredep({
      ignorePath: '../../'
    }))
    .pipe(gulp.dest('config/assets/'));
});

// wiredep task to production
gulp.task('wiredep:prod', function () {
  return gulp.src('config/assets/production.js')
    .pipe(wiredep({
      ignorePath: '../../',
      fileTypes: {
        js: {
          replace: {
            css: function (filePath) {
              var minFilePath = filePath.replace('.css', '.min.css');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            },
            js: function (filePath) {
              var minFilePath = filePath.replace('.js', '.min.js');
              var fullPath = path.join(process.cwd(), minFilePath);
              if (!fs.existsSync(fullPath)) {
                return '\'' + filePath + '\',';
              } else {
                return '\'' + minFilePath + '\',';
              }
            }
          }
        }
      }
    }))
    .pipe(gulp.dest('config/assets/'));
});

// Copy local development environment config example
gulp.task('copyLocalEnvConfig', function () {
  var src = [];
  var renameTo = 'local-development.js';

  // only add the copy source if our destination file doesn't already exist
  if (!fs.existsSync('config/env/' + renameTo)) {
    src.push('config/env/local.example.js');
  }

  return gulp.src(src)
    .pipe(plugins.rename(renameTo))
    .pipe(gulp.dest('config/env'));
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', function () {
  return fs.mkdir('modules/users/client/img/profile/uploads', function (err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
  });
});

// Angular template cache task
gulp.task('templatecache', function () {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.templateCache('templates.js', {
      root: '/modules/',
      module: 'core',
      templateHeader: '(function () {' + endOfLine + '	\'use strict\';' + endOfLine + endOfLine + '	angular' + endOfLine + '		.module(\'<%= module %>\'<%= standalone %>)' + endOfLine + '		.run(templates);' + endOfLine + endOfLine + '	templates.$inject = [\'$templateCache\'];' + endOfLine + endOfLine + '	function templates($templateCache) {' + endOfLine,
      templateBody: '		$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '	}' + endOfLine + '})();' + endOfLine
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  var mongooseService = require('./config/lib/mongoose');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongooseService.connect(function (db) {
    // Load mongoose models
    mongooseService.loadModels();

    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        mongooseService.disconnect(function (err) {
          if (err) {
            console.log('Error disconnecting from database');
            console.log(err);
          }

          return done(error);
        });
      });
  });
});

// Prepare istanbul coverage test
gulp.task('pre-test', function () {

  // Display coverage for all server JavaScript files
  return gulp.src(defaultAssets.server.allJS)
    // Covering files
    .pipe(plugins.istanbul())
    // Force `require` to return covered files
    .pipe(plugins.istanbul.hookRequire());
});

// Run istanbul test and write report
gulp.task('mocha:coverage', ['pre-test', 'mocha'], function () {
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;

  return gulp.src(testSuites)
    .pipe(plugins.istanbul.writeReports({
      reportOpts: { dir: './coverage/server' }
    }));
});

// Karma test runner task
gulp.task('karma', function (done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js'
  }, done).start();
});

// Run karma with coverage options set and write report
gulp.task('karma:coverage', function(done) {
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    preprocessors: {
      'modules/*/client/views/**/*.html': ['ng-html2js'],
      'modules/core/client/app/config.js': ['coverage'],
      'modules/core/client/app/init.js': ['coverage'],
      'modules/*/client/*.js': ['coverage'],
      'modules/*/client/config/*.js': ['coverage'],
      'modules/*/client/controllers/*.js': ['coverage'],
      'modules/*/client/directives/*.js': ['coverage'],
      'modules/*/client/services/*.js': ['coverage']
    },
    reporters: ['progress', 'coverage'],
    coverageReporter: {
      dir: 'coverage/client',
      reporters: [
        { type: 'lcov', subdir: '.' }
        // printing summary to console currently weirdly causes gulp to hang so disabled for now
        // https://github.com/karma-runner/karma-coverage/issues/209
        // { type: 'text-summary' }
      ]
    }
  }, done).start();
});

// Drops the MongoDB database, used in e2e testing
gulp.task('dropdb', function (done) {
  // Use mongoose configuration
  var mongooseService = require('./config/lib/mongoose');

  mongooseService.connect(function (db) {
    db.dropDatabase(function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log('Successfully dropped db: ', db.databaseName);
      }

      mongooseService.disconnect(done);
    });
  });
});

// Downloads the selenium webdriver if protractor version is compatible
gulp.task('webdriver_update', webdriver_update);

// Start the standalone selenium server
// NOTE: This is not needed if you reference the
// seleniumServerJar in your protractor.conf.js
gulp.task('webdriver_standalone', webdriver_standalone);

// Protractor test runner task
gulp.task('protractor', ['webdriver_update'], function () {
  gulp.src([])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('end', function() {
      console.log('E2E Testing complete');
      // exit with success.
      process.exit(0);
    })
    .on('error', function(err) {
      console.error('E2E Tests failed:');
      console.error(err);
      process.exit(1);
    });
});

// Lint CSS and JavaScript files.
gulp.task('lint', function (done) {
  runSequence('less', 'sass', ['csslint', 'eslint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function (done) {
  runSequence('env:dev', 'wiredep:prod', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function (done) {
  runSequence('env:test', 'test:server', 'karma', 'nodemon', 'protractor', done);
});

gulp.task('test:server', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function (done) {
  runSequence('test:server', 'watch:server:run-tests', done);
});

gulp.task('test:client', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'karma', done);
});

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});

gulp.task('test:coverage', function (done) {
  runSequence('env:test', ['copyLocalEnvConfig', 'makeUploadsDir', 'dropdb'], 'lint', 'mocha:coverage', 'karma:coverage', done);
});

// Run the project in development mode with node debugger enabled
gulp.task('default', function (done) {
  runSequence('env:dev', ['copyLocalEnvConfig', 'makeUploadsDir'], 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function (done) {
  runSequence(['copyLocalEnvConfig', 'makeUploadsDir', 'templatecache'], 'build', 'env:prod', 'lint', ['nodemon-nodebug', 'watch'], done);
});
<|endoftext|>


<commit_before>"use strict";

let gulp         = require("gulp"),
    rename       = require("gulp-rename"),
    json_minify  = require("gulp-json-minify"),
    browserSync  = require("browser-sync")

gulp.task("default", [ "copy", "confirmation" ])
gulp.task("release", [ "default" ])
gulp.task("dev",     [ "copy_watch" ])
gulp.task("server",  [ "copy", "browserSync" ])

gulp.task("copy", function () {
    gulp.src("source/js/example_response.json", { base: process.cwd() })
        .pipe(rename("character_sheet__player_name.json"))
        .pipe(json_minify())
        .pipe(gulp.dest("public/data"))
})

gulp.task("copy_watch", [ "copy" ], function () {
    gulp.watch(["source/js/example_response.json"], ["copy"])
})

gulp.task("browserSync", [], function () {
    browserSync.init({
        server: { baseDir: "./public" }
    });
})

let console_spacer = `[        ]`,
    console_linebreak = `=============================================================`

gulp.task("confirmation", [], function () {
    console.log(`${console_spacer}`)
    console.log(`${console_spacer} ${console_linebreak}`)
    console.log(`${console_spacer}`)
    console.log(`${console_spacer} \tSample data is available and the app has been built`)
    console.log(`${console_spacer}`)
    console.log(`${console_spacer} ${console_linebreak}`)
    console.log(`${console_spacer}`)
})
<commit_msg>Build process: Remove logging from gulpfile.js<commit_after>const gulp        = require('gulp')
const rename      = require('gulp-rename')
const json_minify = require('gulp-json-minify')
const browserSync = require('browser-sync')

gulp.task('default', [ 'copy_watch' ])
gulp.task('release', [ 'copy' ])
gulp.task('dev',     [ 'copy_watch' ])
gulp.task('server',  [ 'copy', 'browserSync' ])

gulp.task('copy', function () {
    gulp.src('source/js/example_response.json', { base: process.cwd() })
        .pipe(rename('character_sheet__player_name.json'))
        .pipe(json_minify())
        .pipe(gulp.dest('public/data'))
})

gulp.task('copy_watch', [ 'copy' ], function () {
    gulp.watch(['source/js/example_response.json'], ['copy'])
})

gulp.task('browserSync', [], function () {
    browserSync.init({
        server: { baseDir: './public' }
    });
})<|endoftext|>


<commit_before>/* eslint camelcase: 0 */
'use strict';

var util = require('util')
  , gulp = require('gulp')
  , browserify = require('browserify')
  , uglify = require('gulp-uglify')
  , sourcemaps = require('gulp-sourcemaps')
  , source = require('vinyl-source-stream')
  , buffer = require('vinyl-buffer')
  , envify = require('envify/custom')
  , mocha = require('gulp-mocha')
  , eslint = require('gulp-eslint')
  , rename = require('gulp-rename')
  , header = require('gulp-header')
  , pkg = require('./package.json')
  , fs = require('fs')
  ;

var libName = 'sockjs-' + pkg.version
  , browserifyOptions = {
      entries: './lib/entry.js'
    , standalone: 'SockJS'
    , insertGlobalVars: {
        process: function () {
          return '{ env: {} }';
        }
      }
    }
  ;

var banner = '/* sockjs-client v<%= pkg.version %> | http://sockjs.org | MIT license */\n';

gulp.task('test', function () {
  gulp.src('tests/node.js', {read: false})
    .pipe(mocha());
});

gulp.task('eslint', function () {
  gulp.src(['lib/**/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

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

gulp.task('write-version', function () {
  fs.writeFileSync('./lib/version.js', "module.exports = '" + pkg.version + "';");
});

gulp.task('testbundle', ['browserify:min'], function() {
  return gulp.src('./build/' + libName + '.min.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./tests/html/lib/'));
});

gulp.task('testbundle-debug', ['browserify'], function() {
  gulp.src('./build/sockjs.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./tests/html/lib/'));

  return gulp.src('./build/sockjs.js.map')
    .pipe(rename('sockjs.js.map'))
    .pipe(gulp.dest('./tests/html/lib/'));
});

gulp.task('browserify', ['write-version'], function () {
  return browserify(util._extend({
      debug: true
    }, browserifyOptions))
    .bundle()
    .pipe(source('sockjs.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(header(banner, { pkg: pkg }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./build/'))
    ;
});

gulp.task('browserify:min', ['write-version'], function () {
  return browserify(browserifyOptions)
    .exclude('debug')
    .transform(envify({
      NODE_ENV: 'production'
    }))
    .bundle()
    .pipe(source(libName + '.min.js'))
    .pipe(buffer())
    .pipe(uglify({
      compress: {
        // remove debug statements from output entirely
        pure_funcs: ['debug']
      }
    }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(gulp.dest('./build/'))
    ;
});

gulp.task('release', ['browserify', 'browserify:min'], function () {
  // sockjs-{version}.min.js
  gulp.src('./build/' + libName + '.min.js')
    .pipe(gulp.dest('./dist/'));

  // sockjs-{version}.js
  gulp.src('./build/sockjs.js')
    .pipe(rename(libName + '.js'))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('stable-release', function () {
  var bower = require('./bower.json');
  bower.version = pkg.version;
  fs.writeFileSync('./bower.json', JSON.stringify(bower, null, 2));

  // sockjs.min.js
  gulp.src('./build/' + libName + '.min.js')
    .pipe(rename('sockjs.min.js'))
    .pipe(gulp.dest('./dist/'));

  // sockjs.js
  gulp.src('./build/sockjs.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./dist/'));
});
<commit_msg>Fix stable-release build command<commit_after>/* eslint camelcase: 0 */
'use strict';

var util = require('util')
  , gulp = require('gulp')
  , browserify = require('browserify')
  , uglify = require('gulp-uglify')
  , sourcemaps = require('gulp-sourcemaps')
  , source = require('vinyl-source-stream')
  , buffer = require('vinyl-buffer')
  , envify = require('envify/custom')
  , mocha = require('gulp-mocha')
  , eslint = require('gulp-eslint')
  , rename = require('gulp-rename')
  , header = require('gulp-header')
  , pkg = require('./package.json')
  , fs = require('fs')
  ;

var libName = 'sockjs-' + pkg.version
  , browserifyOptions = {
      entries: './lib/entry.js'
    , standalone: 'SockJS'
    , insertGlobalVars: {
        process: function () {
          return '{ env: {} }';
        }
      }
    }
  ;

var banner = '/* sockjs-client v<%= pkg.version %> | http://sockjs.org | MIT license */\n';

gulp.task('test', function () {
  gulp.src('tests/node.js', {read: false})
    .pipe(mocha());
});

gulp.task('eslint', function () {
  gulp.src(['lib/**/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

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

gulp.task('write-version', function () {
  fs.writeFileSync('./lib/version.js', "module.exports = '" + pkg.version + "';");
});

gulp.task('testbundle', ['browserify:min'], function() {
  return gulp.src('./build/' + libName + '.min.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./tests/html/lib/'));
});

gulp.task('testbundle-debug', ['browserify'], function() {
  gulp.src('./build/sockjs.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./tests/html/lib/'));

  return gulp.src('./build/sockjs.js.map')
    .pipe(rename('sockjs.js.map'))
    .pipe(gulp.dest('./tests/html/lib/'));
});

gulp.task('browserify', ['write-version'], function () {
  return browserify(util._extend({
      debug: true
    }, browserifyOptions))
    .bundle()
    .pipe(source('sockjs.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(header(banner, { pkg: pkg }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./build/'))
    ;
});

gulp.task('browserify:min', ['write-version'], function () {
  return browserify(browserifyOptions)
    .exclude('debug')
    .transform(envify({
      NODE_ENV: 'production'
    }))
    .bundle()
    .pipe(source(libName + '.min.js'))
    .pipe(buffer())
    .pipe(uglify({
      compress: {
        // remove debug statements from output entirely
        pure_funcs: ['debug']
      }
    }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(gulp.dest('./build/'))
    ;
});

gulp.task('release', ['browserify', 'browserify:min'], function () {
  // sockjs-{version}.min.js
  gulp.src('./build/' + libName + '.min.js')
    .pipe(gulp.dest('./dist/'));

  // sockjs-{version}.js
  gulp.src('./build/sockjs.js')
    .pipe(rename(libName + '.js'))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('stable-release', ['release'], function () {
  var bower = require('./bower.json');
  bower.version = pkg.version;
  fs.writeFileSync('./bower.json', JSON.stringify(bower, null, 2));

  // sockjs.min.js
  gulp.src('./build/' + libName + '.min.js')
    .pipe(rename('sockjs.min.js'))
    .pipe(gulp.dest('./dist/'));

  // sockjs.js
  gulp.src('./build/sockjs.js')
    .pipe(rename('sockjs.js'))
    .pipe(gulp.dest('./dist/'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fse = require('fs-extra');
var jshint = require('gulp-jshint');

gulp.task('clean', function(done) {
  fse.removeSync('dist');
  fse.mkdirSync('dist');
  done();
});

var ignore = ['!./dist/**', '!./node_modules/**', '!./coverage/**'];

gulp.task('lint', function() {
  return gulp.src(['**/*.js'].concat(ignore))
    .pipe(jshint({esnext: true}))
    .pipe(jshint.reporter('default', {esnext: true}));
});

gulp.task('default', ['clean', 'lint'], function() {
  return gulp
    .src(['static/*',
          'node_modules/localforage/dist/localforage.min.js',
          'node_modules/quagga/dist/quagga.min.js',
          'node_modules/bwip-js/bwip.js', 'node_modules/bwip-js/bwipp/code128.js', 'node_modules/bwip-js/bwipp/raiseerror.js', 'node_modules/bwip-js/bwipp/renlinear.js', 'node_modules/bwip-js/lib/canvas.js', 'node_modules/bwip-js/Inconsolata.otf', 'node_modules/bwip-js/freetype.js', 'node_modules/bwip-js/freetype.js.mem'])
    .pipe(gulp.dest('dist'));
});
<commit_msg>Don't copy unused lib/canvas.js file<commit_after>var gulp = require('gulp');
var fse = require('fs-extra');
var jshint = require('gulp-jshint');

gulp.task('clean', function(done) {
  fse.removeSync('dist');
  fse.mkdirSync('dist');
  done();
});

var ignore = ['!./dist/**', '!./node_modules/**', '!./coverage/**'];

gulp.task('lint', function() {
  return gulp.src(['**/*.js'].concat(ignore))
    .pipe(jshint({esnext: true}))
    .pipe(jshint.reporter('default', {esnext: true}));
});

gulp.task('default', ['clean', 'lint'], function() {
  return gulp
    .src(['static/*',
          'node_modules/localforage/dist/localforage.min.js',
          'node_modules/quagga/dist/quagga.min.js',
          'node_modules/bwip-js/bwip.js', 'node_modules/bwip-js/bwipp/code128.js', 'node_modules/bwip-js/bwipp/raiseerror.js', 'node_modules/bwip-js/bwipp/renlinear.js', 'node_modules/bwip-js/Inconsolata.otf', 'node_modules/bwip-js/freetype.js', 'node_modules/bwip-js/freetype.js.mem'])
    .pipe(gulp.dest('dist'));
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('generators/**/*.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      console.log(err);
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

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

gulp.task('prepublish', []);
gulp.task('default', ['static', 'test']);
<commit_msg>add lib/ directory to test config<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src(['generators/**/*.js','lib/*.js'])
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      console.log(err);
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

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

gulp.task('prepublish', []);
gulp.task('default', ['static', 'test']);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    watch = require('gulp-watch'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    cssnano = require('gulp-cssnano'),
    debug = require('gulp-debug'),
    connect = require('gulp-connect'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('gulp-rimraf'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    iconfont = require('gulp-iconfont'),
    iconfontCss = require('gulp-iconfont-css'),

    imgDest = 'build/images',
    imgSource = './images/**/*';

  /**
   * Build custom js
   */
  gulp.task('buildCustomJS', function () {
    browserify({entries: './js/app.js', debug: true})
      .transform('babelify', {presets: ['es2015']})
      .bundle().on('error', function (err) {
        showError.apply(this, ['JS error', err])
      })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build js vendor (concatenate vendor array)
   */
  gulp.task('buildJsVendors', function () {
    gulp.src(require('./vendor_entries/vendor.js'))
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for application from SASS
   */
  gulp.task('buildSass', function () {
    gulp.src('./scss/app.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error', err]);
      }))
      .pipe(cssnano())
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for vendor from SASS
   */
  gulp.task('buildStylesVendors', function () {
    gulp.src('./vendor_entries/vendor.scss')
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error (vendor)', err]);
      }))
      .pipe(cssnano())
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Images minification
   */
  gulp.task('imageMin', function () {
    gulp.src(imgSource)
      .pipe(newer(imgDest))
      .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngquant()]
      }))
      .pipe(gulp.dest(imgDest));
  });

  /**
   * Clean image build directory
   */
  gulp.task('imageClean', function () {
    gulp.src(imgDest).pipe(rimraf());
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch('./js/**/*', ['buildCustomJS']);
    gulp.watch('./vendor_entries/vendor.js', ['buildJsVendors']);
    gulp.watch('./scss/**/*', ['buildSass']);
    gulp.watch('./vendor_entries/vendor.scss', ['buildStylesVendors']);
    watch('./images/**/*', function () {
      gulp.run('imageMin');
    });
    gulp.watch(['./build/*', './*.html']).on('change', function (file) {
      gulp.src(file.path).pipe(connect.reload());
    });
  });

  /**
   * Starting local server
   */
  gulp.task('startLocalhost', function () {
    connect.server({
      livereload: true
    });
  });

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', ['cleanProduction'], function () {
    gulp.src(['./**/*',
      '!vendor_entries',
      '!vendor_entries/**/*',
      '!images/',
      '!images/**/*',
      '!bower/',
      '!bower/**/*',
      '!js/',
      '!js/**/*',
      '!node_modules/**/*',
      '!node_modules/',
      '!scss/**/*',
      '!scss/',
      '!build/**.map',
      '!.bowerrc',
      '!bower.json',
      '!.gitignore',
      '!gulpfile.js',
      '!LICENSE',
      '!package.json',
      '!production',
      '!README.md'])
          .pipe(gulp.dest('./production'));
  });

  /**
   * Clean production folder
   */
  gulp.task('cleanProduction', function () {
    return gulp.src('./production/', {read: false})
      .pipe(rimraf());
  });

  /**
   * Make iconfont from svg icons
   */
  gulp.task('makeIconFont', function () {
    var fontName = 'iconfont';
    gulp.src(['./fonts/icons/*.svg'])
      .pipe(iconfontCss({
        fontName: fontName,
        fontPath: 'fonts/iconfont/'
      }))
      .pipe(iconfont({
        fontName: fontName,
        normalize: true
       }))
      .pipe(gulp.dest('./scss/fonts/iconfont/'));
  });

  /**
   * Copy iconfont to the build folder
   */
  gulp.task('iconFont', ['makeIconFont'], function() {
    gulp.src('./scss/fonts/**/*')
      .pipe(gulp.dest('./build/fonts/'));
  });

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({title:preffix, message: err.message });
    this.emit("end");
  }

  // Default Gulp Task
  gulp.task('default', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'startLocalhost', 'watch']);
  gulp.task('dev', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'watch']);

}());<commit_msg>Add safe option to cssnano to prevent styles errors<commit_after>(function () {
  'use strict';

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    watch = require('gulp-watch'),
    newer = require('gulp-newer'),
    concat = require('gulp-concat'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    cssnano = require('gulp-cssnano'),
    debug = require('gulp-debug'),
    connect = require('gulp-connect'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('gulp-rimraf'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    iconfont = require('gulp-iconfont'),
    iconfontCss = require('gulp-iconfont-css'),

    imgDest = 'build/images',
    imgSource = './images/**/*';

  /**
   * Build custom js
   */
  gulp.task('buildCustomJS', function () {
    browserify({entries: './js/app.js', debug: true})
      .transform('babelify', {presets: ['es2015']})
      .bundle().on('error', function (err) {
        showError.apply(this, ['JS error', err])
      })
      .pipe(source('app.js'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build js vendor (concatenate vendor array)
   */
  gulp.task('buildJsVendors', function () {
    gulp.src(require('./vendor_entries/vendor.js'))
      .pipe(concat('vendor.js'))
      .pipe(uglify())
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for application from SASS
   */
  gulp.task('buildSass', function () {
    gulp.src('./scss/app.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Build styles for vendor from SASS
   */
  gulp.task('buildStylesVendors', function () {
    gulp.src('./vendor_entries/vendor.scss')
      .pipe(sass().on('error', function (err) {
        showError.apply(this, ['Sass compile error (vendor)', err]);
      }))
      .pipe(cssnano({safe: true}))
      .pipe(gulp.dest('./build/'));
  });

  /**
   * Images minification
   */
  gulp.task('imageMin', function () {
    gulp.src(imgSource)
      .pipe(newer(imgDest))
      .pipe(imagemin({
        progressive: true,
        svgoPlugins: [{removeViewBox: false}],
        use: [pngquant()]
      }))
      .pipe(gulp.dest(imgDest));
  });

  /**
   * Clean image build directory
   */
  gulp.task('imageClean', function () {
    gulp.src(imgDest).pipe(rimraf());
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch('./js/**/*', ['buildCustomJS']);
    gulp.watch('./vendor_entries/vendor.js', ['buildJsVendors']);
    gulp.watch('./scss/**/*', ['buildSass']);
    gulp.watch('./vendor_entries/vendor.scss', ['buildStylesVendors']);
    watch('./images/**/*', function () {
      gulp.run('imageMin');
    });
    gulp.watch(['./build/*', './*.html']).on('change', function (file) {
      gulp.src(file.path).pipe(connect.reload());
    });
  });

  /**
   * Starting local server
   */
  gulp.task('startLocalhost', function () {
    connect.server({
      livereload: true
    });
  });

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', ['cleanProduction'], function () {
    gulp.src(['./**/*',
      '!vendor_entries',
      '!vendor_entries/**/*',
      '!images/',
      '!images/**/*',
      '!bower/',
      '!bower/**/*',
      '!js/',
      '!js/**/*',
      '!node_modules/**/*',
      '!node_modules/',
      '!scss/**/*',
      '!scss/',
      '!build/**.map',
      '!.bowerrc',
      '!bower.json',
      '!.gitignore',
      '!gulpfile.js',
      '!LICENSE',
      '!package.json',
      '!production',
      '!README.md'])
          .pipe(gulp.dest('./production'));
  });

  /**
   * Clean production folder
   */
  gulp.task('cleanProduction', function () {
    return gulp.src('./production/', {read: false})
      .pipe(rimraf());
  });

  /**
   * Make iconfont from svg icons
   */
  gulp.task('makeIconFont', function () {
    var fontName = 'iconfont';
    gulp.src(['./fonts/icons/*.svg'])
      .pipe(iconfontCss({
        fontName: fontName,
        fontPath: 'fonts/iconfont/'
      }))
      .pipe(iconfont({
        fontName: fontName,
        normalize: true
       }))
      .pipe(gulp.dest('./scss/fonts/iconfont/'));
  });

  /**
   * Copy iconfont to the build folder
   */
  gulp.task('iconFont', ['makeIconFont'], function() {
    gulp.src('./scss/fonts/**/*')
      .pipe(gulp.dest('./build/fonts/'));
  });

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({title:preffix, message: err.message });
    this.emit("end");
  }

  // Default Gulp Task
  gulp.task('default', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'startLocalhost', 'watch']);
  gulp.task('dev', ['buildCustomJS', 'buildSass', 'buildJsVendors', 'buildStylesVendors', 'imageMin', 'watch']);

}());<|endoftext|>