<commit_before>'use strict';

var gulp = require('gulp');
gulp.ngHtml2js = require('gulp-ng-html2js');
gulp.ngAnnotate = require('gulp-ng-annotate');
gulp.sourcemaps = require('gulp-sourcemaps');
gulp.jshint = require('gulp-jshint');
gulp.less = require('gulp-less');
gulp.uglify = require('gulp-uglify');
gulp.header = require('gulp-header');
gulp.footer = require('gulp-footer');
gulp.filter = require('gulp-filter');
gulp.rename = require('gulp-rename');
gulp.concat = require('gulp-concat');
gulp.bower = require('gulp-bower');
gulp.ngdocs = require('gulp-ngdocs');
gulp.bump = require('gulp-bump');
gulp.git = require('gulp-git');
gulp.util = require('gulp-util');
gulp.header = require('gulp-header');

var q = require('q');
var prettyTime = require('pretty-hrtime');
var path = require('path');
var mergeStream = require('merge-stream');
var KarmaServer = require('karma').Server;
var lodash = require('lodash');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var request = require('request');
var webjarDeploy = require('./bower-webjar-deploy.js');

var license = '/*!\n ' +
    '* Copyright 2014-2015 the original author or authors.\n ' +
    '*\n ' +
    '* Licensed under the Apache License, Version 2.0 (the "License");\n ' +
    '* you may not use this file except in compliance with the License.\n ' +
    '* You may obtain a copy of the License at\n ' +
    '*\n ' +
    '*      http://www.apache.org/licenses/LICENSE-2.0\n ' +
    '*\n ' +
    '* Unless required by applicable law or agreed to in writing, software\n ' +
    '* distributed under the License is distributed on an "AS IS" BASIS,\n ' +
    '* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ' +
    '* See the License for the specific language governing permissions and\n ' +
    '* limitations under the License.\n ' +
    '*/\n';

var config = {
    pkg: require('./bower.json'),
    paths: {
        // configurable paths
        src: 'src/main/javascript',
        resources: 'src/main/resources',
        test: 'src/test/javascript',
        dist: 'dist'
    },
    jshint: {
        reporters: {
            dev: 'jshint-stylish',
            prod: 'fail'
        }
    },
    karma: {
        configFile: path.resolve('./karma.conf.js')
    }
};

function getVersion() {
    return require('./' + config.paths.dist + '/bower.json').version;
}

function getVersionTag() {
    return 'v' + getVersion();
}

function template(templateString, data) {
    var options = data || config;
    if (lodash.isArray(templateString)) {
        return lodash.map(templateString, function (temp) {
            return template(temp, options);
        });
    }
    return lodash.template(templateString)(options);
}

// add support for lodash templates
var gulpSrc = gulp.src;
gulp.src = function (glob, options) {
    return gulpSrc(template(glob), options);
};
var gulpWatch = gulp.watch;
gulp.watch = function (glob, opt, fn) {
    return gulpWatch.apply(this, [template(glob), opt, fn]);
};
var gulpDest = gulp.dest;
gulp.dest = function (glob) {
    return gulpDest(template(glob));
};

var watchLog = function (event) {
    gulp.util.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
};

var watch = function () {
    gulp.util.log(template('Watching <%= paths.src %>/**/*'));
    gulp.watch(template('<%= paths.src %>/**/*'), ['angular-js']).on('change', watchLog);

    gulp.util.log(template('Watching <%= paths.resources %>/**/*.html'));
    gulp.watch(template('<%= paths.resources %>/**/*.html'), ['angular-templates']).on('change', watchLog);

    gulp.util.log(template('Watching <%= paths.resources %>/**/*.less'));
    gulp.watch(template('<%= paths.resources %>/**/*.less'), ['less2css']).on('change', watchLog);
};

var test = function (watch, production) {
    return function (cb) {
        var options = {};
        if (production === true) {
            options.plugins = [
                'karma-junit-reporter',
                'karma-jasmine',
                'karma-coverage',
                'karma-phantomjs-launcher'
            ];

            options.reporters = [
                'progress',
                'coverage',
                'junit'
            ];

            options.junitReporter = {
                outputFile: 'test-results.xml',
                suite: ''
            };
        }
        new KarmaServer(lodash.assign(options, config.karma, {singleRun: !watch, autoWatch: watch}), cb)
            .start();
    };
};

var less2css = function () {
    var dest = template('<%= paths.dist %>');
    return gulp.src(['<%= paths.resources %>/styles/*.less'])
        .pipe(gulp.sourcemaps.init())
        .pipe(gulp.less())
        .pipe(gulp.header(license))
        .pipe(gulp.sourcemaps.write('.', {sourceRoot: 'src'}))
        .pipe(gulp.dest(dest));
};

var _concatenateAndUglify = function (name) {
    var jsFilter;

    function applyJsFilter() {
        jsFilter = gulp.filter('**/*.js', {restore: true});
        return jsFilter;
    }

    function restore() {
        return jsFilter.restore;
    }

    return lazypipe()
        .pipe(applyJsFilter) // filter out '*.js.tpl' files
        .pipe(gulp.ngAnnotate, {gulpWarnings: false})
        .pipe(restore) // restore all files
        .pipe(gulp.concat, name + '.js')
        .pipe(gulp.sourcemaps.write, '.', {sourceRoot: 'src'})
        .pipe(gulp.dest, config.paths.dist)
        .pipe(gulp.filter, ['**/*.js'])
        .pipe(gulp.uglify, {preserveComments: 'some', mangle: false})
        .pipe(gulp.rename, name + '.min.js')
        .pipe(gulp.sourcemaps.write, '.', {sourceRoot: 'src/../'})
        .pipe(gulp.dest, config.paths.dist)
    ();
};

var angularJs = function () {
    var defaultJs = gulp.src(['src/main/util/js-header.js.tpl', '<%= paths.src %>/**/*.js', 'src/main/util/js-footer.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(_concatenateAndUglify(config.pkg.name));

    var requireJs = gulp.src(['src/main/util/js-header-require.js.tpl', '<%= paths.src %>/**/*.js', 'src/main/util/js-footer-require.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(_concatenateAndUglify(config.pkg.name + '-require'));

    return mergeStream(defaultJs, requireJs);
};

var angularTemplates = function () {
    var htmlFilter = gulp.filter('**/*.html', {restore: true});
    var defaultJs = gulp.src(['src/main/util/tpl-header.js.tpl', '<%= paths.resources %>/**/*.html', 'src/main/util/tpl-footer.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(htmlFilter)
        .pipe(gulp.ngHtml2js({moduleName: 'cat.template', stripPrefix: 'resources/', declareModule: false}))
        .pipe(htmlFilter.restore)
        .pipe(_concatenateAndUglify(config.pkg.name + '.tpl'));

    var htmlFilter2 = gulp.filter('**/*.html', {restore: true});
    var requireJs = gulp.src(['src/main/util/tpl-header-require.js.tpl', '<%= paths.resources %>/**/*.html', 'src/main/util/tpl-footer-require.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(htmlFilter2)
        .pipe(gulp.ngHtml2js({moduleName: 'cat.template', stripPrefix: 'resources/', declareModule: false}))
        .pipe(htmlFilter2.restore)
        .pipe(_concatenateAndUglify(config.pkg.name + '-require.tpl'));

    return mergeStream(defaultJs, requireJs);
};

var bowerJson = function () {
    return gulp.src(['bower.dist.json'])
        .pipe(gulp.rename('bower.json'))
        .pipe(gulp.dest(config.paths.dist));
};

var cleanTask = function (cb) {
    rimraf(config.paths.dist, cb);
};

var bowerInstall = function () {
    return gulp.bower();
};

function jshint(src, env) {
    return function () {
        return gulp.src(src)
            .pipe(gulp.jshint())
            .pipe(gulp.jshint.reporter(config.jshint.reporters[env || 'dev']));
    };
}

gulp.task('jshint-main', jshint('<%= paths.src %>/**/*.js'));
gulp.task('jshint-test', jshint('<%= paths.test %>/**/*.js'));
gulp.task('jshint', ['jshint-main', 'jshint-test']);
gulp.task('jshint-main-prod', jshint('<%= paths.src %>/**/*.js', 'prod'));
gulp.task('jshint-test-prod', jshint('<%= paths.test %>/**/*.js', 'prod'));
gulp.task('jshint-prod', ['jshint-main-prod', 'jshint-test-prod']);
gulp.task('bower-install', bowerInstall);
gulp.task('watch', ['angular'], watch);
gulp.task('less2css', less2css);
gulp.task('default', ['build']);
gulp.task('bower-json', bowerJson);
gulp.task('build', ['test', 'less2css', 'bower-json']);
gulp.task('build-production', ['test-production', 'less2css', 'bower-json']);
gulp.task('test', ['angular', 'bower-install'], test(false));
gulp.task('test-production', ['jshint-prod', 'angular', 'bower-install'], test(false, true));
gulp.task('test-watch', ['angular', 'bower-install'], test(true));
gulp.task('angular', ['angular-js', 'angular-templates']);
gulp.task('angular-js', ['jshint'], angularJs);
gulp.task('angular-templates', angularTemplates);
gulp.task('clean', cleanTask);

// npm install -g http-server
// gulp docs && http-server docs/ -c -1 -p 8091

// ERROR:
// [TypeError: Cannot read property 'replace' of undefined]
// Solution:
// @name is missing in documentation?

gulp.task('docs', [], function () {
    var options = {
        html5Mode: false,
        startPage: '/api',
        title: config.pkg.name,
        titleLink: '/api'
    };
    return gulp.ngdocs
        .sections({
            api: {
                glob: [
                    'src/main/javascript/**/*.js'
                ],
                api: true,
                title: 'API Documentation'
            }
        })
        .pipe(gulp.ngdocs.process(options))
        .pipe(gulp.dest('./docs'));
});

gulp.task('watchDocs', ['docs'], function () {
    gulp.util.log(template('Watching <%= paths.src %>/**/*'));
    gulp
        .watch(template([
            '<%= paths.src %>/**/*',
            'gulpfile.js'
        ]), ['docs'])
        .on('change', watchLog);
});

function bumpVersion(type) {
    return gulp.src(['./package.json', 'bower.dist.json'])
        .pipe(gulp.bump({type: type}))
        .pipe(gulp.dest('./'));
}

gulp.task('bump-patch', function () {
    return bumpVersion('patch');
});

function preRelease(cb) {
    gulp.git.tag('pre-release', 'pre-release', {args: '-f'}, cb);
}

function releaseTag(cb) {
    var version = getVersionTag();
    gulp.git.tag(version, version, function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.tag(version, version, {cwd: config.paths.dist}, cb);
        }
    });
}

gulp.task('pre-release', [], preRelease);
gulp.task('release-tag', [], releaseTag);

gulp.task('release-commit-dist', function () {
    return gulp.src('./*', {cwd: config.paths.dist})
        .pipe(gulp.git.commit(getVersionTag(), {cwd: config.paths.dist}));
});

gulp.task('release-commit', ['release-commit-dist'], function () {
    return gulp.src(['./*.json', 'dist'])
        .pipe(gulp.git.commit(getVersionTag()));
});

gulp.task('release-push-dist', function (cb) {
    gulp.git.push('origin', 'master', {cwd: config.paths.dist}, function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.push('origin', getVersionTag(), {cwd: config.paths.dist}, cb);
        }
    });
});

gulp.task('release-push', ['release-push-dist'], function (cb) {
    gulp.git.push('origin', 'master', function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.push('origin', getVersionTag(), cb);
        }
    });
});

webjarDeploy('cat-angular', getVersion, {taskName: 'release-webjar'});

function runTaskFunction(task) {
    return function () {
        var deferred = q.defer();

        var start = process.hrtime();

        var onTaskErr = function (err) {
            deferred.reject(err);
        };
        var onTaskStop = function (e) {
            if (e.task === task) {
                gulp.removeListener('task_stop', onTaskStop);
                gulp.removeListener('task_err', onTaskErr);

                var time = prettyTime(process.hrtime(start));
                gulp.util.log(
                    'Finished', '\'' + gulp.util.colors.cyan(task) + '\' with dependencies',
                    'after', gulp.util.colors.magenta(time)
                );

                deferred.resolve(e);
            }
        };

        gulp.on('task_stop', onTaskStop);
        gulp.on('task_err', onTaskErr);
        gulp.util.log('Starting \'' + gulp.util.colors.cyan(task) + '\' with dependencies');
        gulp.start(task);

        return deferred.promise;
    };
}

function release(type) {
    return function (cb) {
        runTaskFunction('pre-release')()
            .then(runTaskFunction('bump-' + type))
            .then(runTaskFunction('build'))
            .then(runTaskFunction('release-commit'))
            .then(runTaskFunction('release-tag'))
            .then(runTaskFunction('release-push'))
            .then(runTaskFunction('release-webjar'))
            .then(function () {
                cb();
            }, cb);
    };
}

gulp.task('release-patch', [], release('patch'));

gulp.task('release-minor', [], release('minor'));

gulp.task('release-major', [], release('major'));<commit_msg>add task for minor and major version bump<commit_after>'use strict';

var gulp = require('gulp');
gulp.ngHtml2js = require('gulp-ng-html2js');
gulp.ngAnnotate = require('gulp-ng-annotate');
gulp.sourcemaps = require('gulp-sourcemaps');
gulp.jshint = require('gulp-jshint');
gulp.less = require('gulp-less');
gulp.uglify = require('gulp-uglify');
gulp.header = require('gulp-header');
gulp.footer = require('gulp-footer');
gulp.filter = require('gulp-filter');
gulp.rename = require('gulp-rename');
gulp.concat = require('gulp-concat');
gulp.bower = require('gulp-bower');
gulp.ngdocs = require('gulp-ngdocs');
gulp.bump = require('gulp-bump');
gulp.git = require('gulp-git');
gulp.util = require('gulp-util');
gulp.header = require('gulp-header');

var q = require('q');
var prettyTime = require('pretty-hrtime');
var path = require('path');
var mergeStream = require('merge-stream');
var KarmaServer = require('karma').Server;
var lodash = require('lodash');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var request = require('request');
var webjarDeploy = require('./bower-webjar-deploy.js');

var license = '/*!\n ' +
    '* Copyright 2014-2015 the original author or authors.\n ' +
    '*\n ' +
    '* Licensed under the Apache License, Version 2.0 (the "License");\n ' +
    '* you may not use this file except in compliance with the License.\n ' +
    '* You may obtain a copy of the License at\n ' +
    '*\n ' +
    '*      http://www.apache.org/licenses/LICENSE-2.0\n ' +
    '*\n ' +
    '* Unless required by applicable law or agreed to in writing, software\n ' +
    '* distributed under the License is distributed on an "AS IS" BASIS,\n ' +
    '* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ' +
    '* See the License for the specific language governing permissions and\n ' +
    '* limitations under the License.\n ' +
    '*/\n';

var config = {
    pkg: require('./bower.json'),
    paths: {
        // configurable paths
        src: 'src/main/javascript',
        resources: 'src/main/resources',
        test: 'src/test/javascript',
        dist: 'dist'
    },
    jshint: {
        reporters: {
            dev: 'jshint-stylish',
            prod: 'fail'
        }
    },
    karma: {
        configFile: path.resolve('./karma.conf.js')
    }
};

function getVersion() {
    return require('./' + config.paths.dist + '/bower.json').version;
}

function getVersionTag() {
    return 'v' + getVersion();
}

function template(templateString, data) {
    var options = data || config;
    if (lodash.isArray(templateString)) {
        return lodash.map(templateString, function (temp) {
            return template(temp, options);
        });
    }
    return lodash.template(templateString)(options);
}

// add support for lodash templates
var gulpSrc = gulp.src;
gulp.src = function (glob, options) {
    return gulpSrc(template(glob), options);
};
var gulpWatch = gulp.watch;
gulp.watch = function (glob, opt, fn) {
    return gulpWatch.apply(this, [template(glob), opt, fn]);
};
var gulpDest = gulp.dest;
gulp.dest = function (glob) {
    return gulpDest(template(glob));
};

var watchLog = function (event) {
    gulp.util.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
};

var watch = function () {
    gulp.util.log(template('Watching <%= paths.src %>/**/*'));
    gulp.watch(template('<%= paths.src %>/**/*'), ['angular-js']).on('change', watchLog);

    gulp.util.log(template('Watching <%= paths.resources %>/**/*.html'));
    gulp.watch(template('<%= paths.resources %>/**/*.html'), ['angular-templates']).on('change', watchLog);

    gulp.util.log(template('Watching <%= paths.resources %>/**/*.less'));
    gulp.watch(template('<%= paths.resources %>/**/*.less'), ['less2css']).on('change', watchLog);
};

var test = function (watch, production) {
    return function (cb) {
        var options = {};
        if (production === true) {
            options.plugins = [
                'karma-junit-reporter',
                'karma-jasmine',
                'karma-coverage',
                'karma-phantomjs-launcher'
            ];

            options.reporters = [
                'progress',
                'coverage',
                'junit'
            ];

            options.junitReporter = {
                outputFile: 'test-results.xml',
                suite: ''
            };
        }
        new KarmaServer(lodash.assign(options, config.karma, {singleRun: !watch, autoWatch: watch}), cb)
            .start();
    };
};

var less2css = function () {
    var dest = template('<%= paths.dist %>');
    return gulp.src(['<%= paths.resources %>/styles/*.less'])
        .pipe(gulp.sourcemaps.init())
        .pipe(gulp.less())
        .pipe(gulp.header(license))
        .pipe(gulp.sourcemaps.write('.', {sourceRoot: 'src'}))
        .pipe(gulp.dest(dest));
};

var _concatenateAndUglify = function (name) {
    var jsFilter;

    function applyJsFilter() {
        jsFilter = gulp.filter('**/*.js', {restore: true});
        return jsFilter;
    }

    function restore() {
        return jsFilter.restore;
    }

    return lazypipe()
        .pipe(applyJsFilter) // filter out '*.js.tpl' files
        .pipe(gulp.ngAnnotate, {gulpWarnings: false})
        .pipe(restore) // restore all files
        .pipe(gulp.concat, name + '.js')
        .pipe(gulp.sourcemaps.write, '.', {sourceRoot: 'src'})
        .pipe(gulp.dest, config.paths.dist)
        .pipe(gulp.filter, ['**/*.js'])
        .pipe(gulp.uglify, {preserveComments: 'some', mangle: false})
        .pipe(gulp.rename, name + '.min.js')
        .pipe(gulp.sourcemaps.write, '.', {sourceRoot: 'src/../'})
        .pipe(gulp.dest, config.paths.dist)
    ();
};

var angularJs = function () {
    var defaultJs = gulp.src(['src/main/util/js-header.js.tpl', '<%= paths.src %>/**/*.js', 'src/main/util/js-footer.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(_concatenateAndUglify(config.pkg.name));

    var requireJs = gulp.src(['src/main/util/js-header-require.js.tpl', '<%= paths.src %>/**/*.js', 'src/main/util/js-footer-require.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(_concatenateAndUglify(config.pkg.name + '-require'));

    return mergeStream(defaultJs, requireJs);
};

var angularTemplates = function () {
    var htmlFilter = gulp.filter('**/*.html', {restore: true});
    var defaultJs = gulp.src(['src/main/util/tpl-header.js.tpl', '<%= paths.resources %>/**/*.html', 'src/main/util/tpl-footer.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(htmlFilter)
        .pipe(gulp.ngHtml2js({moduleName: 'cat.template', stripPrefix: 'resources/', declareModule: false}))
        .pipe(htmlFilter.restore)
        .pipe(_concatenateAndUglify(config.pkg.name + '.tpl'));

    var htmlFilter2 = gulp.filter('**/*.html', {restore: true});
    var requireJs = gulp.src(['src/main/util/tpl-header-require.js.tpl', '<%= paths.resources %>/**/*.html', 'src/main/util/tpl-footer-require.js.tpl'])
        .pipe(gulp.sourcemaps.init())
        .pipe(htmlFilter2)
        .pipe(gulp.ngHtml2js({moduleName: 'cat.template', stripPrefix: 'resources/', declareModule: false}))
        .pipe(htmlFilter2.restore)
        .pipe(_concatenateAndUglify(config.pkg.name + '-require.tpl'));

    return mergeStream(defaultJs, requireJs);
};

var bowerJson = function () {
    return gulp.src(['bower.dist.json'])
        .pipe(gulp.rename('bower.json'))
        .pipe(gulp.dest(config.paths.dist));
};

var cleanTask = function (cb) {
    rimraf(config.paths.dist, cb);
};

var bowerInstall = function () {
    return gulp.bower();
};

function jshint(src, env) {
    return function () {
        return gulp.src(src)
            .pipe(gulp.jshint())
            .pipe(gulp.jshint.reporter(config.jshint.reporters[env || 'dev']));
    };
}

gulp.task('jshint-main', jshint('<%= paths.src %>/**/*.js'));
gulp.task('jshint-test', jshint('<%= paths.test %>/**/*.js'));
gulp.task('jshint', ['jshint-main', 'jshint-test']);
gulp.task('jshint-main-prod', jshint('<%= paths.src %>/**/*.js', 'prod'));
gulp.task('jshint-test-prod', jshint('<%= paths.test %>/**/*.js', 'prod'));
gulp.task('jshint-prod', ['jshint-main-prod', 'jshint-test-prod']);
gulp.task('bower-install', bowerInstall);
gulp.task('watch', ['angular'], watch);
gulp.task('less2css', less2css);
gulp.task('default', ['build']);
gulp.task('bower-json', bowerJson);
gulp.task('build', ['test', 'less2css', 'bower-json']);
gulp.task('build-production', ['test-production', 'less2css', 'bower-json']);
gulp.task('test', ['angular', 'bower-install'], test(false));
gulp.task('test-production', ['jshint-prod', 'angular', 'bower-install'], test(false, true));
gulp.task('test-watch', ['angular', 'bower-install'], test(true));
gulp.task('angular', ['angular-js', 'angular-templates']);
gulp.task('angular-js', ['jshint'], angularJs);
gulp.task('angular-templates', angularTemplates);
gulp.task('clean', cleanTask);

// npm install -g http-server
// gulp docs && http-server docs/ -c -1 -p 8091

// ERROR:
// [TypeError: Cannot read property 'replace' of undefined]
// Solution:
// @name is missing in documentation?

gulp.task('docs', [], function () {
    var options = {
        html5Mode: false,
        startPage: '/api',
        title: config.pkg.name,
        titleLink: '/api'
    };
    return gulp.ngdocs
        .sections({
            api: {
                glob: [
                    'src/main/javascript/**/*.js'
                ],
                api: true,
                title: 'API Documentation'
            }
        })
        .pipe(gulp.ngdocs.process(options))
        .pipe(gulp.dest('./docs'));
});

gulp.task('watchDocs', ['docs'], function () {
    gulp.util.log(template('Watching <%= paths.src %>/**/*'));
    gulp
        .watch(template([
            '<%= paths.src %>/**/*',
            'gulpfile.js'
        ]), ['docs'])
        .on('change', watchLog);
});

function bumpVersion(type) {
    return gulp.src(['./package.json', 'bower.dist.json'])
        .pipe(gulp.bump({type: type}))
        .pipe(gulp.dest('./'));
}

gulp.task('bump-patch', function () {
    return bumpVersion('patch');
});

gulp.task('bump-minor', function () {
    return bumpVersion('minor');
});

gulp.task('bump-major', function () {
    return bumpVersion('major');
});

function preRelease(cb) {
    gulp.git.tag('pre-release', 'pre-release', {args: '-f'}, cb);
}

function releaseTag(cb) {
    var version = getVersionTag();
    gulp.git.tag(version, version, function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.tag(version, version, {cwd: config.paths.dist}, cb);
        }
    });
}

gulp.task('pre-release', [], preRelease);
gulp.task('release-tag', [], releaseTag);

gulp.task('release-commit-dist', function () {
    return gulp.src('./*', {cwd: config.paths.dist})
        .pipe(gulp.git.commit(getVersionTag(), {cwd: config.paths.dist}));
});

gulp.task('release-commit', ['release-commit-dist'], function () {
    return gulp.src(['./*.json', 'dist'])
        .pipe(gulp.git.commit(getVersionTag()));
});

gulp.task('release-push-dist', function (cb) {
    gulp.git.push('origin', 'master', {cwd: config.paths.dist}, function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.push('origin', getVersionTag(), {cwd: config.paths.dist}, cb);
        }
    });
});

gulp.task('release-push', ['release-push-dist'], function (cb) {
    gulp.git.push('origin', 'master', function (err) {
        if (!!err) {
            cb(err);
        } else {
            gulp.git.push('origin', getVersionTag(), cb);
        }
    });
});

webjarDeploy('cat-angular', getVersion, {taskName: 'release-webjar'});

function runTaskFunction(task) {
    return function () {
        var deferred = q.defer();

        var start = process.hrtime();

        var onTaskErr = function (err) {
            deferred.reject(err);
        };
        var onTaskStop = function (e) {
            if (e.task === task) {
                gulp.removeListener('task_stop', onTaskStop);
                gulp.removeListener('task_err', onTaskErr);

                var time = prettyTime(process.hrtime(start));
                gulp.util.log(
                    'Finished', '\'' + gulp.util.colors.cyan(task) + '\' with dependencies',
                    'after', gulp.util.colors.magenta(time)
                );

                deferred.resolve(e);
            }
        };

        gulp.on('task_stop', onTaskStop);
        gulp.on('task_err', onTaskErr);
        gulp.util.log('Starting \'' + gulp.util.colors.cyan(task) + '\' with dependencies');
        gulp.start(task);

        return deferred.promise;
    };
}

function release(type) {
    return function (cb) {
        runTaskFunction('pre-release')()
            .then(runTaskFunction('bump-' + type))
            .then(runTaskFunction('build'))
            .then(runTaskFunction('release-commit'))
            .then(runTaskFunction('release-tag'))
            .then(runTaskFunction('release-push'))
            .then(runTaskFunction('release-webjar'))
            .then(function () {
                cb();
            }, cb);
    };
}

gulp.task('release-patch', [], release('patch'));

gulp.task('release-minor', [], release('minor'));

gulp.task('release-major', [], release('major'));<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  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;

// 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 () {
  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: ['--debug'],
    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.livereload.listen();

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

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

// CSS linting task
gulp.task('csslint', function (done) {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.reporter())
    .pipe(plugins.csslint.reporter(function (file) {
      if (!file.csslint.errorCount) {
        done();
      }
    }));
});

// JS linting task
gulp.task('jshint', 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.jshint())
    .pipe(plugins.jshint.reporter('default'))
    .pipe(plugins.jshint.reporter('fail'));
});

// 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
  );

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

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

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(plugins.rename(function (file) {
      file.dirname = file.dirname.replace(path.sep + 'scss', path.sep + 'css');
    }))
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(plugins.rename(function (file) {
      file.dirname = file.dirname.replace(path.sep + 'less', path.sep + 'css');
    }))
    .pipe(gulp.dest('./modules/'));
});

// Angular template cache task
gulp.task('templatecache', function () {
  var re = new RegExp('\\' + path.sep + 'client\\' + path.sep, 'g');

  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,
      transformUrl: function (url) {
        return url.replace(re, path.sep);
      }
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose.js');
  var error;

  // Connect mongoose
  mongoose.connect(function () {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testAssets.tests.server)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        // When the tests are done, disconnect mongoose and pass the error state back to gulp
        mongoose.disconnect(function () {
          done(error);
        });
      });
  });

});

// Karma test runner task
gulp.task('karma', function (done) {
  return gulp.src([])
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'run',
      singleRun: true
    }));
});

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

  mongoose.connect(function (db) {
    db.connection.db.dropDatabase(function (err) {
      if(err) {
        console.log(err);
      } else {
        console.log('Successfully dropped db: ', db.connection.db.databaseName);
      }
      db.connection.db.close(done);
    });
  });
});

// Downloads the selenium webdriver
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.log('E2E Tests failed');
      process.exit(1);
    });
});

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

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

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

gulp.task('test:server', function (done) {
  runSequence('env:test', 'lint', 'mocha', done);
});

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

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});
//
// Run the project in eroku
// gulp.task('heroku', function (done) {
//   runSequence('env:prod', done);
// });
// gulp.tasks('heroku', function (done) {
//   runSequence('templatecache', 'build', 'env:prod',['nodemon', 'watch'], done);});
gulp.task('default', function (done) {
  runSequence('env:dev',['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function (done) {
  runSequence('env:dev', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function (done) {
  runSequence('templatecache', 'build', 'env:prod',['nodemon', 'watch'], done);
});
<commit_msg>hero task<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
  defaultAssets = require('./config/assets/default'),
  testAssets = require('./config/assets/test'),
  gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  runSequence = require('run-sequence'),
  plugins = gulpLoadPlugins({
    rename: {
      'gulp-angular-templatecache': 'templateCache'
    }
  }),
  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;

// 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 () {
  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: ['--debug'],
    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.livereload.listen();

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

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

// CSS linting task
gulp.task('csslint', function (done) {
  return gulp.src(defaultAssets.client.css)
    .pipe(plugins.csslint('.csslintrc'))
    .pipe(plugins.csslint.reporter())
    .pipe(plugins.csslint.reporter(function (file) {
      if (!file.csslint.errorCount) {
        done();
      }
    }));
});

// JS linting task
gulp.task('jshint', 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.jshint())
    .pipe(plugins.jshint.reporter('default'))
    .pipe(plugins.jshint.reporter('fail'));
});

// 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
  );

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

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

// Sass task
gulp.task('sass', function () {
  return gulp.src(defaultAssets.client.sass)
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer())
    .pipe(plugins.rename(function (file) {
      file.dirname = file.dirname.replace(path.sep + 'scss', path.sep + 'css');
    }))
    .pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
  return gulp.src(defaultAssets.client.less)
    .pipe(plugins.less())
    .pipe(plugins.autoprefixer())
    .pipe(plugins.rename(function (file) {
      file.dirname = file.dirname.replace(path.sep + 'less', path.sep + 'css');
    }))
    .pipe(gulp.dest('./modules/'));
});

// Angular template cache task
gulp.task('templatecache', function () {
  var re = new RegExp('\\' + path.sep + 'client\\' + path.sep, 'g');

  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,
      transformUrl: function (url) {
        return url.replace(re, path.sep);
      }
    }))
    .pipe(gulp.dest('build'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose.js');
  var error;

  // Connect mongoose
  mongoose.connect(function () {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testAssets.tests.server)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function (err) {
        // If an error occurs, save it
        error = err;
      })
      .on('end', function () {
        // When the tests are done, disconnect mongoose and pass the error state back to gulp
        mongoose.disconnect(function () {
          done(error);
        });
      });
  });

});

// Karma test runner task
gulp.task('karma', function (done) {
  return gulp.src([])
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'run',
      singleRun: true
    }));
});

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

  mongoose.connect(function (db) {
    db.connection.db.dropDatabase(function (err) {
      if(err) {
        console.log(err);
      } else {
        console.log('Successfully dropped db: ', db.connection.db.databaseName);
      }
      db.connection.db.close(done);
    });
  });
});

// Downloads the selenium webdriver
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.log('E2E Tests failed');
      process.exit(1);
    });
});

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

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

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

gulp.task('test:server', function (done) {
  runSequence('env:test', 'lint', 'mocha', done);
});

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

gulp.task('test:e2e', function (done) {
  runSequence('env:test', 'lint', 'dropdb', 'nodemon', 'protractor', done);
});
//
// Run the project in eroku
// gulp.task('heroku', function (done) {
//   runSequence('env:prod', done);
// });
// gulp.tasks('heroku', function (done) {
//   runSequence('templatecache', 'build', 'env:prod',['nodemon', 'watch'], done);});
gulp.tasks('heroku:prod', [default]);

gulp.task('default', function (done) {
  runSequence('env:dev',['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function (done) {
  runSequence('env:dev', ['nodemon', 'watch'], done);
});

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


<commit_before>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"  : true,
        "keijiban" : true,
        "require"  : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "misc"], function() {
  return gulp.src("dist/*")
    .pipe(zip("appkit.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    .pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/assets/img"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<commit_msg>#21 Added some more global js variables to the eslint task<commit_after>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"      : true,
        "keijiban"     : true,
        "window"       : true,
        "baseSlice"    : true,
        "chunk"        : true,
        "buildToggler" : true,
        "require"      : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "misc"], function() {
  return gulp.src("dist/*")
    .pipe(zip("appkit.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    .pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/assets/img"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

// ---------- Watch task ----------

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<|endoftext|>


<commit_before>/* global require */

var gulp = require('gulp');
var concat = require('gulp-concat');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var php = require('gulp-connect-php');
var prettify = require('gulp-jsbeautifier');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var del = require('del');

// See the cssmin documentation for more details
var cssMinSettings = {
    keepSpecialComments: 0
};

// See the uglify documentation for more details
var uglifySettings = {
    compress: {
        comparisons: true,
        conditionals: true,
        dead_code: true,
        drop_console: true,
        unsafe: true,
        unused: true
    }
};

// Assets for the project
var Assets = {
    css: {
        dest: 'css',
        custom: {
            all: [
                // Note: /css/ is the same as Assets.css.dest

                // Select all js file(s) include sub-directories
                './css/**/*.css',

                // Ignore all css file(s) that have the .min.css prefix
                '!./css/**/*.min.css'
            ],
            // main: 'styles.css',
            minified: 'styles.min.css'
        },
        vendor: {
            // main: 'vendor.css',
            minified: 'vendor.min.css'
        }
    },
    js: {
        dest: 'js',
        custom: {
            all: [
                // Note: /js/ is the same as Assets.js.dest

                // Select all js file(s) include sub-directories
                './js/**/*.js',

                // Ignore all js file(s) that have the .min.js prefix
                '!./js/**/*.min.js'
            ],
            // main: 'scripts.js',
            minified: 'scripts.min.js'
        },
        vendor: {
            // main: 'vendor.js',
            minified: 'vendor.min.js'
        }
    }
};

// Clean the current directory
gulp.task('clean', function (cb) {
    del([
        './' + Assets.css.dest + '/' + Assets.css.custom.minified,
        './' + Assets.js.dest + '/' + Assets.js.custom.minified
    ], cb);
});

// Minify the main css file(s)
gulp.task('cssmin', function () {
    // Clean the css dest directory
    del(['./' + Assets.css.dest + '/' + Assets.css.custom.minified]);

    return gulp.src(Assets.css.custom.all)
        .pipe(concat(Assets.css.custom.minified))
        .pipe(cssmin(cssMinSettings))
        .pipe(rename(Assets.css.custom.minified))
        .pipe(gulp.dest('./' + Assets.css.dest));
});

// Check the code meets the following standards outlined in .jshintrc
gulp.task('jshint', function () {
    return gulp.src(Assets.js.custom.all)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Initialise the PHP server 'php -S localhost:8000'
gulp.task('php-server', function () {
    php.server({
        hostname: 'localhost',
        port: 8000,
        base: '.',
        keepalive: true,
        open: true
        // bin: ''
        // ini: ''
    });
});

// Prettify the main js file(s)
gulp.task('prettify-js', function () {
    gulp.src(Assets.js.custom.all)
        .pipe(prettify({
            config: '.jsbeautifyrc',
            mode: 'VERIFY_AND_WRITE'
        }))
        .pipe(gulp.dest('./' + Assets.js.dest));
});

// Uglify aka minify the main js file(s)
gulp.task('uglify', function () {
    // Store the destination directory
    var dest = './' + Assets.js.dest;

    // Clean the js dest directory
    del([dest + '/' + Assets.js.custom.minified]);

    return gulp.src([
            dest + '/core.js',
            dest + '/core.api.js',
            dest + '/core.features.js',
            dest + '/gists.js',
            dest + '/main.js',
            dest + '/navigation.js'
        ])
        .pipe(concat(Assets.js.custom.minified))
        .pipe(uglify(uglifySettings))
        .pipe(rename(Assets.js.custom.minified))
        .pipe(gulp.dest(dest));
});

// Concat and uglify the vendor scripts/styles
gulp.task('vendor', function () {
    // Store the bower_components directory
    var bowerComponents = './bower_components/';

    // Copy font-awesome fonts
    gulp.src(bowerComponents + 'font-awesome/fonts/**/*.{eof,svg,ttf,woff,woff2}')
        .pipe(gulp.dest('./fonts'));

    // Concatenate and minify styles
    gulp.src([
            bowerComponents + 'font-awesome/css/font-awesome.css',
            bowerComponents + 'normalize-css/normalize.css',
            bowerComponents + 'skeleton/css/skeleton.css',
            bowerComponents + 'nprogress/nprogress.css',
        ])
        .pipe(concat(Assets.css.vendor.minified))
        .pipe(cssmin(cssMinSettings))
        .pipe(gulp.dest('./' + Assets.css.dest));

    // Concatenate and uglify scripts
    gulp.src([
            bowerComponents + 'jquery/dist/jquery.js',
            bowerComponents + 'handlebars/handlebars.js',
            bowerComponents + 'momentjs/moment.js',
            bowerComponents + 'jquery-handlebars/jquery-handlebars.js',
            bowerComponents + 'nprogress/nprogress.js',
        ])
        .pipe(concat(Assets.js.vendor.minified))
        .pipe(uglify(uglifySettings))
        .pipe(gulp.dest('./' + Assets.js.dest));
});

// Build the main css and js file(s)
gulp.task('build', ['clean', 'cssmin', 'uglify']);

// Watch for changes to the main css and js file(s)
gulp.task('watch', function () {
    gulp.watch(Assets.css.custom.all, ['cssmin']);
    gulp.watch(Assets.js.custom.all, ['jshint', 'uglify']);
});

// Register the default task which is essentially 'build' and 'vendor' included
gulp.task('default', ['build', 'vendor']);

// 'gulp build' to build the main css and js file(s)
// 'gulp cssmin' to minify the main css file(s)
// 'gulp jshint' to check the syntax of the main js file(s)
// 'gulp php-server' to connect to the local PHP server
// 'gulp prettify-js' to prettify the main js file(s)
// 'gulp uglify' to uglify the main js file(s)
// 'gulp vendor' to build the vendor file(s)
// 'gulp watch' to watch for changes to the main css and js file(s)
// 'gulp' to build everything
<commit_msg>Explicit css minification<commit_after>/* global require */

var gulp = require('gulp');
var concat = require('gulp-concat');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var php = require('gulp-connect-php');
var prettify = require('gulp-jsbeautifier');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var del = require('del');

// See the cssmin documentation for more details
var cssMinSettings = {
    keepSpecialComments: 0
};

// See the uglify documentation for more details
var uglifySettings = {
    compress: {
        comparisons: true,
        conditionals: true,
        dead_code: true,
        drop_console: true,
        unsafe: true,
        unused: true
    }
};

// Assets for the project
var Assets = {
    css: {
        dest: 'css',
        custom: {
            all: [
                // Note: /css/ is the same as Assets.css.dest

                // Select all js file(s) include sub-directories
                './css/**/*.css',

                // Ignore all css file(s) that have the .min.css prefix
                '!./css/**/*.min.css'
            ],
            // main: 'styles.css',
            minified: 'styles.min.css'
        },
        vendor: {
            // main: 'vendor.css',
            minified: 'vendor.min.css'
        }
    },
    js: {
        dest: 'js',
        custom: {
            all: [
                // Note: /js/ is the same as Assets.js.dest

                // Select all js file(s) include sub-directories
                './js/**/*.js',

                // Ignore all js file(s) that have the .min.js prefix
                '!./js/**/*.min.js'
            ],
            // main: 'scripts.js',
            minified: 'scripts.min.js'
        },
        vendor: {
            // main: 'vendor.js',
            minified: 'vendor.min.js'
        }
    }
};

// Clean the current directory
gulp.task('clean', function (cb) {
    del([
        './' + Assets.css.dest + '/' + Assets.css.custom.minified,
        './' + Assets.js.dest + '/' + Assets.js.custom.minified
    ], cb);
});

// Minify the main css file(s)
gulp.task('cssmin', function () {
    // Store the destination directory
    var dest = './' + Assets.css.dest;

    // Clean the css dest directory
    del(['./' + Assets.css.dest + '/' + Assets.css.custom.minified]);

    return gulp.src([
            dest + '/styles.css',
        ])
        .pipe(concat(Assets.css.custom.minified))
        .pipe(cssmin(cssMinSettings))
        .pipe(rename(Assets.css.custom.minified))
        .pipe(gulp.dest('./' + Assets.css.dest));
});

// Check the code meets the following standards outlined in .jshintrc
gulp.task('jshint', function () {
    return gulp.src(Assets.js.custom.all)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Initialise the PHP server 'php -S localhost:8000'
gulp.task('php-server', function () {
    php.server({
        hostname: 'localhost',
        port: 8000,
        base: '.',
        keepalive: true,
        open: true
        // bin: ''
        // ini: ''
    });
});

// Prettify the main js file(s)
gulp.task('prettify-js', function () {
    gulp.src(Assets.js.custom.all)
        .pipe(prettify({
            config: '.jsbeautifyrc',
            mode: 'VERIFY_AND_WRITE'
        }))
        .pipe(gulp.dest('./' + Assets.js.dest));
});

// Uglify aka minify the main js file(s)
gulp.task('uglify', function () {
    // Store the destination directory
    var dest = './' + Assets.js.dest;

    // Clean the js dest directory
    del([dest + '/' + Assets.js.custom.minified]);

    return gulp.src([
            dest + '/core.js',
            dest + '/core.api.js',
            dest + '/core.features.js',
            dest + '/gists.js',
            dest + '/main.js',
            dest + '/navigation.js'
        ])
        .pipe(concat(Assets.js.custom.minified))
        .pipe(uglify(uglifySettings))
        .pipe(rename(Assets.js.custom.minified))
        .pipe(gulp.dest(dest));
});

// Concat and uglify the vendor scripts/styles
gulp.task('vendor', function () {
    // Store the bower_components directory
    var bowerComponents = './bower_components/';

    // Copy font-awesome fonts
    gulp.src(bowerComponents + 'font-awesome/fonts/**/*.{eof,svg,ttf,woff,woff2}')
        .pipe(gulp.dest('./fonts'));

    // Concatenate and minify styles
    gulp.src([
            bowerComponents + 'font-awesome/css/font-awesome.css',
            bowerComponents + 'normalize-css/normalize.css',
            bowerComponents + 'skeleton/css/skeleton.css',
            bowerComponents + 'nprogress/nprogress.css',
        ])
        .pipe(concat(Assets.css.vendor.minified))
        .pipe(cssmin(cssMinSettings))
        .pipe(gulp.dest('./' + Assets.css.dest));

    // Concatenate and uglify scripts
    gulp.src([
            bowerComponents + 'jquery/dist/jquery.js',
            bowerComponents + 'handlebars/handlebars.js',
            bowerComponents + 'momentjs/moment.js',
            bowerComponents + 'jquery-handlebars/jquery-handlebars.js',
            bowerComponents + 'nprogress/nprogress.js',
        ])
        .pipe(concat(Assets.js.vendor.minified))
        .pipe(uglify(uglifySettings))
        .pipe(gulp.dest('./' + Assets.js.dest));
});

// Build the main css and js file(s)
gulp.task('build', ['clean', 'cssmin', 'uglify']);

// Watch for changes to the main css and js file(s)
gulp.task('watch', function () {
    gulp.watch(Assets.css.custom.all, ['cssmin']);
    gulp.watch(Assets.js.custom.all, ['jshint', 'uglify']);
});

// Register the default task which is essentially 'build' and 'vendor' included
gulp.task('default', ['build', 'vendor']);

// 'gulp build' to build the main css and js file(s)
// 'gulp cssmin' to minify the main css file(s)
// 'gulp jshint' to check the syntax of the main js file(s)
// 'gulp php-server' to connect to the local PHP server
// 'gulp prettify-js' to prettify the main js file(s)
// 'gulp uglify' to uglify the main js file(s)
// 'gulp vendor' to build the vendor file(s)
// 'gulp watch' to watch for changes to the main css and js file(s)
// 'gulp' to build everything
<|endoftext|>


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

var GulpApp = {
  config: {
    testFiles: [
      'src/r7storage.js',
      'spec/*.js'
    ],

    action: "run"
  },

  test: function() {
    return gulp.src(GulpApp.config.testFiles)
      .pipe(
        karma({
          configFile: 'karma.conf.js',
          action: GulpApp.config.action
        })
      );
  },

  default: function() {
    GulpApp.config.action = "watch";
    return GulpApp.test();
  },

  build: function() {
    return gulp.src(GulpApp.config.testFiles[0])
     .pipe(uglify())
     .pipe(rename({ suffix: '.min' }))
     .pipe(gulp.dest('src/'));
  }
};

gulp.task('test', GulpApp.test);
gulp.task('default', GulpApp.default);
gulp.task('compress', GulpApp.build);
gulp.task('build', ['test', 'compress']);<commit_msg>just a small typo fix<commit_after>var gulp   = require('gulp');
var karma  = require('gulp-karma');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

var GulpApp = {
  config: {
    testFiles: [
      'src/r7storage.js',
      'spec/*.js'
    ],

    action: "run"
  },

  test: function() {
    return gulp.src(GulpApp.config.testFiles)
      .pipe(
        karma({
          configFile: 'karma.conf.js',
          action: GulpApp.config.action
        })
      );
  },

  default: function() {
    GulpApp.config.action = "watch";
    return GulpApp.test();
  },

  build: function() {
    return gulp.src(GulpApp.config.testFiles[0])
     .pipe(uglify())
     .pipe(rename({ suffix: '.min' }))
     .pipe(gulp.dest('src/'));
  }
};

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


<commit_before>'use strict'

// Foundation for Apps
//
// We use this Gulpfile to assemble the documentation, run unit tests,
// and deploy changes to the live documentation and CDN.
//
// The tasks are grouped into these categories:
//   1. Libraries
//   2. Variables
//   3. Cleaning files
//   4. Copying files
//   5. Stylesheets
//   6. JavaScript
//   7. Testing
//   8. Server
//   9. Deployment
//  10. Default tasks

// 1. LIBRARIES
// - - - - - - - - - - - - - - -

var gulp           = require('gulp'),
    $              = require('gulp-load-plugins')(),
    rimraf         = require('rimraf'),
    runSequence    = require('run-sequence'),
    modRewrite     = require('connect-modrewrite'),
    routes         = require('./bin/gulp-dynamic-routing'),
    merge          = require('merge-stream'),
    settingsParser = require('settings-parser')
;

var addVersions = function() {
  var pkg = require('./package.json');
  return $.rename(function(path) {
    // Inject the version number into the filename
    var base = path.basename.split('.');
    if (base.length === 1) {
      base = base + '-' + pkg.version;
    }
    else {
      base = base.slice(0, -1).join('') + '-' + pkg.version + '.' + base[base.length - 1];
    }
    path.basename = base;
    path.dirname = '';
  })
}

// 2. VARIABLES
// - - - - - - - - - - - - - - -

var paths = {
  html: {
    base: [
      './docs/**/*.*',
      '!./docs/templates/**/*.*',
      '!./docs/assets/{scss,js}/**/*.*'
    ],
    templates: [
      './docs/templates/**/*.html'
    ],
    partials: [
      'js/angular/components/**/*.html'
    ]
  },
  sass: {
    loadPaths: [
      'scss',
      'docs/assets/scss'
    ],
    testPaths: [
      'scss',
      'docs/assets/scss',
      'bower_components/bootcamp/dist'
    ]
  },
  javascript: {
    foundation: [
      'js/vendor/**/*.js',
      'js/angular/**/*.js',
      '!js/angular/app.js'
    ],
    libs: [
      'bower_components/fastclick/lib/fastclick.js',
      'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js',
      'bower_components/tether/tether.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/hammerjs/hammer.js'
    ],
    docs: [
      'bower_components/marked/lib/marked.js',
      'bower_components/angular-highlightjs/angular-highlightjs.js',
      'bower_components/highlightjs/highlight.pack.js',
      'bower_components/allmighty-autocomplete/script/autocomplete.js',
      'docs/assets/js/app.js'
    ]
  }
}

// 3. CLEANIN' FILES
// - - - - - - - - - - - - - - -

// Clean build directory
gulp.task('clean', function(cb) {
  rimraf('./build', cb);
});

// Clean the partials directory
gulp.task('clean:partials', function(cb) {
  rimraf('./build/partials', cb);
});

// Clean the dist directory
gulp.task('clean:dist', function(cb) {
  rimraf('./dist', cb);
});

// 4. COPYING FILES
// - - - - - - - - - - - - - - -

// Copy static files (but not the Angular templates, Sass, or JS)
gulp.task('copy', function() {
  gulp.src(paths.html.base, {
    base: './docs/'
  })
    .pipe(gulp.dest('build'));

  return gulp.src('./iconic/**/*')
    .pipe(gulp.dest('build/assets/img/iconic/'));
});

// Copy page templates and generate routes
gulp.task('copy:templates', ['javascript'], function() {
  var config = [];

  return gulp.src(paths.html.templates)
    .pipe(routes({
      path: 'build/assets/js/routes.js',
      root: 'docs'
    }))
    .pipe(gulp.dest('./build/templates'))
  ;
});

// Copy Foundation directive partials
gulp.task('copy:partials', ['clean:partials'], function() {
  gulp.src(paths.html.partials)
    .pipe(gulp.dest('./build/components/'));

  return gulp.src('./docs/partials/**/*.html')
    .pipe(gulp.dest('./build/partials/'));
});

// 5. STYLESHEETS
// - - - - - - - - - - - - - - -

// Inject styles for docs-specific libraries
gulp.task('css', ['sass'], function() {
  var dirs = [
    'bower_components/allmighty-autocomplete/style/autocomplete.css',
    'build/assets/css/app.css'
  ];
  return gulp.src(dirs)
    .pipe($.concat('app.css'))
    .pipe(gulp.dest('build/assets/css'))
  ;
});

// Compile stylesheets with Ruby Sass
gulp.task('sass', function() {
  var filter = $.filter(['*.css']);

  return $.rubySass('docs/assets/scss/', {
      loadPath: paths.sass.loadPaths,
      style: 'nested',
      bundleExec: true
    })
    .on('error', function(err) {
      console.log(err.message);
    })
    .pipe(filter)
      .pipe($.autoprefixer({
        browsers: ['last 2 versions', 'ie 10']
      }))
    .pipe(filter.restore())
    .pipe(gulp.dest('./build/assets/css/'));
});

// Compile stylesheets with node-sass
gulp.task('sass:node', function() {
  return gulp.src('docs/assets/scss/app.scss')
    .pipe($.sass({
      includePaths: paths.sass.loadPaths,
      outputStyle: 'nested',
      errLogToConsole: true
    }))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie 10']
    }))
    .pipe($.concat('app_node.css'))
    .pipe(gulp.dest('./build/assets/css/'));
});

// Generate Sass settings file
gulp.task('sass:settings', function() {
  settingsParser([
    'scss/_includes.scss',
    'scss/_global.scss',
    'scss/helpers/_breakpoints.scss',
    'scss/components/_typography.scss',
    'scss/components/_grid.scss',
    'scss/components/_button.scss',
    'scss/components/*.scss'
  ], {
    title: 'Foundation for Apps Settings'.toUpperCase(),
    partialsPath: 'docs/partials/scss',
    settingsPath: 'scss'
  });
});

// 6. JAVASCRIPT
// - - - - - - - - - - - - - - -

// Compile Foundation JavaScript
gulp.task('javascript', function() {
  var dirs = paths.javascript.libs.concat(
    paths.javascript.foundation,
    paths.javascript.docs
  );
  return gulp.src(dirs)
    .pipe($.uglify({
      beautify: true,
      mangle: false
    }).on('error', function(e) {
      console.log(e);
    }))
    .pipe($.concat('app.js'))
    .pipe(gulp.dest('./build/assets/js/'))
  ;
});

// 7. SERVER
// - - - - - - - - - - - - - - -

gulp.task('server:start', function() {
  $.connect.server({
    root: './build',
    middleware: function() {
      return [
        modRewrite(['^[^\\.]*$ /index.html [L]'])
      ];
    },
  });
});

// 8. TESTING
// - - - - - - - - - - - - - - -

gulp.task('test:karma', ['build', 'sass:node'], function() {
  var testFiles = [
    'build/assets/js/foundation.js',
    'build/assets/js/dependencies.js',
    'build/assets/js/app.js',
    'bower_components/angular-mocks/angular-mocks.js',
    'bower_components/jsdiff/diff.js',
    'build/assets/css/app.css',
    'build/assets/css/app_node.css',
    'tests/unit/common/*Spec.js'
  ];

  return gulp.src(testFiles)
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      throw err;
    })
  ;

});

gulp.task('test:sass', function() {
  return $.rubySass('./tests/unit/scss/tests.scss', {
    loadPath: paths.sass.testPaths,
    style: 'nested',
    bundleExec: true
  })
    .on('data', function(data) {
      console.log(data.contents.toString());
    });
});

gulp.task('test', ['test:karma', 'test:sass'], function() {
  console.log('Tests finished.');
});

gulp.task('compile-motion', ['clean', 'sass', 'javascript'], function() {
  gulp.src('./tests/motion/index.html')
    .pipe(gulp.dest('./build'));
  gulp.src('./tests/motion/templates/**/*.html')
    .pipe(routes({
      path: 'build/assets/js/routes.js',
      root: 'tests/motion'
    }))
    .pipe(gulp.dest('./build/templates'));
});

gulp.task('test:motion', ['server:start', 'compile-motion'], function() {
  gulp.watch(['js/**/*', 'tests/motion/**/*'], ['compile-motion']);
});

// 9. DEPLOYMENT
// - - - - - - - - - - - - - - -

// Deploy distribution files
gulp.task('deploy:dist', ['clean:dist'], function(cb) {
  var filter = $.filter(['*.css']);

  var css = $.rubySass('scss/', {
      loadPath: ['scss'],
      style: 'nested',
      bundleExec: true
    })
    .pipe(filter)
      .pipe($.autoprefixer({
        browsers: ['last 2 versions', 'ie 10']
      }))
    .pipe(filter.restore())
    .pipe($.rename('foundation-apps.css'))
    .pipe(gulp.dest('./dist/css'))
    .pipe($.minifyCss())
    .pipe($.rename('foundation-apps.min.css'))
    .pipe(gulp.dest('./dist/css'));

  var js = gulp.src(paths.javascript.foundation)
    .pipe($.concat('foundation-apps.js'))
    .pipe(gulp.dest('./dist/js'))
    .pipe($.uglify())
    .pipe($.rename('foundation-apps.min.js'))
    .pipe(gulp.dest('./dist/js'));

  var partials = gulp.src(paths.html.partials)
    .pipe($.ngHtml2js({
      prefix: 'components/',
      moduleName: 'foundation',
      declareModule: false
    }))
    .pipe($.concat('templates.js'))
    .pipe(gulp.dest('./dist/js'))
    .pipe($.uglify())
    .pipe($.rename('templates-min.js'))
    .pipe(gulp.dest('./dist/js'))

  cb();
});

// Deploy documentation
gulp.task('deploy:docs', ['build'], function() {
  return gulp.src('build/**')
    .pipe($.prompt.confirm("Make sure everything looks good before you deploy."))
    .pipe($.rsync({
      root: 'build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-apps/current'
    }));
});

// Deploy to CDN
gulp.task('deploy:cdn', ['deploy:dist'], function() {
  return gulp.src('./dist/**/*', {base:'./dist/'})
    .pipe($.filter(['**/*.css', '**/*.js']))
    .pipe(addVersions())
    .pipe($.rsync({
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-apps-cdn/current',
      relative: false
    }));
});

// 10. NOW BRING IT TOGETHER
// - - - - - - - - - - - - - - -

// Build the documentation once
gulp.task('build', function(cb) {
  runSequence('clean', ['copy', 'copy:partials', 'css', 'javascript', 'copy:templates'], function() {
    cb();
  });
});

// Build the documentation, start a test server, and re-compile when files change
gulp.task('default', ['build', 'server:start'], function() {

  // Watch static files
  gulp.watch(paths.html.base, ['copy']);

  // Watch Angular templates
  gulp.watch(paths.html.templates, ['copy:templates']);

  // Watch Angular partials
  gulp.watch(paths.html.partials, ['copy:partials']);

  // Watch Sass
  gulp.watch(['./docs/assets/scss/**/*', './scss/**/*'], ['css']);

  // Watch JavaScript
  gulp.watch(paths.javascript.foundation.concat(paths.javascript.docs), ['javascript']);
});
<commit_msg>Use ngHtml2Js to compile templates in docs, and rename dist file for templates<commit_after>'use strict'

// Foundation for Apps
//
// We use this Gulpfile to assemble the documentation, run unit tests,
// and deploy changes to the live documentation and CDN.
//
// The tasks are grouped into these categories:
//   1. Libraries
//   2. Variables
//   3. Cleaning files
//   4. Copying files
//   5. Stylesheets
//   6. JavaScript
//   7. Testing
//   8. Server
//   9. Deployment
//  10. Default tasks

// 1. LIBRARIES
// - - - - - - - - - - - - - - -

var gulp           = require('gulp'),
    $              = require('gulp-load-plugins')(),
    rimraf         = require('rimraf'),
    runSequence    = require('run-sequence'),
    modRewrite     = require('connect-modrewrite'),
    routes         = require('./bin/gulp-dynamic-routing'),
    merge          = require('merge-stream'),
    settingsParser = require('settings-parser')
;

var addVersions = function() {
  var pkg = require('./package.json');
  return $.rename(function(path) {
    // Inject the version number into the filename
    var base = path.basename.split('.');
    if (base.length === 1) {
      base = base + '-' + pkg.version;
    }
    else {
      base = base.slice(0, -1).join('') + '-' + pkg.version + '.' + base[base.length - 1];
    }
    path.basename = base;
    path.dirname = '';
  })
}

// 2. VARIABLES
// - - - - - - - - - - - - - - -

var paths = {
  html: {
    base: [
      './docs/**/*.*',
      '!./docs/templates/**/*.*',
      '!./docs/assets/{scss,js}/**/*.*'
    ],
    templates: [
      './docs/templates/**/*.html'
    ],
    partials: [
      'js/angular/components/**/*.html'
    ]
  },
  sass: {
    loadPaths: [
      'scss',
      'docs/assets/scss'
    ],
    testPaths: [
      'scss',
      'docs/assets/scss',
      'bower_components/bootcamp/dist'
    ]
  },
  javascript: {
    foundation: [
      'js/vendor/**/*.js',
      'js/angular/**/*.js',
      '!js/angular/app.js'
    ],
    libs: [
      'bower_components/fastclick/lib/fastclick.js',
      'bower_components/viewport-units-buggyfill/viewport-units-buggyfill.js',
      'bower_components/tether/tether.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/hammerjs/hammer.js'
    ],
    docs: [
      'bower_components/marked/lib/marked.js',
      'bower_components/angular-highlightjs/angular-highlightjs.js',
      'bower_components/highlightjs/highlight.pack.js',
      'bower_components/allmighty-autocomplete/script/autocomplete.js',
      'docs/assets/js/app.js'
    ]
  }
}

// 3. CLEANIN' FILES
// - - - - - - - - - - - - - - -

// Clean build directory
gulp.task('clean', function(cb) {
  rimraf('./build', cb);
});

// Clean the partials directory
gulp.task('clean:partials', function(cb) {
  rimraf('./build/partials', cb);
});

// Clean the dist directory
gulp.task('clean:dist', function(cb) {
  rimraf('./dist', cb);
});

// 4. COPYING FILES
// - - - - - - - - - - - - - - -

// Copy static files (but not the Angular templates, Sass, or JS)
gulp.task('copy', function() {
  gulp.src(paths.html.base, {
    base: './docs/'
  })
    .pipe(gulp.dest('build'));

  return gulp.src('./iconic/**/*')
    .pipe(gulp.dest('build/assets/img/iconic/'));
});

// Copy page templates and generate routes
gulp.task('copy:templates', ['javascript'], function() {
  var config = [];

  return gulp.src(paths.html.templates)
    .pipe(routes({
      path: 'build/assets/js/routes.js',
      root: 'docs'
    }))
    .pipe(gulp.dest('./build/templates'))
  ;
});

// Copy Foundation directive partials
gulp.task('copy:partials', ['clean:partials'], function(cb) {
  gulp.src(paths.html.partials)
    .pipe($.ngHtml2js({
      prefix: 'components/',
      moduleName: 'foundation',
      declareModule: false
    }))
    .pipe($.concat('templates.js'))
    .pipe(gulp.dest('./build/assets/js'));

  gulp.src('./docs/partials/**/*.html')
    .pipe(gulp.dest('./build/partials/'));

  cb();
});

// 5. STYLESHEETS
// - - - - - - - - - - - - - - -

// Inject styles for docs-specific libraries
gulp.task('css', ['sass'], function() {
  var dirs = [
    'bower_components/allmighty-autocomplete/style/autocomplete.css',
    'build/assets/css/app.css'
  ];
  return gulp.src(dirs)
    .pipe($.concat('app.css'))
    .pipe(gulp.dest('build/assets/css'))
  ;
});

// Compile stylesheets with Ruby Sass
gulp.task('sass', function() {
  var filter = $.filter(['*.css']);

  return $.rubySass('docs/assets/scss/', {
      loadPath: paths.sass.loadPaths,
      style: 'nested',
      bundleExec: true
    })
    .on('error', function(err) {
      console.log(err.message);
    })
    .pipe(filter)
      .pipe($.autoprefixer({
        browsers: ['last 2 versions', 'ie 10']
      }))
    .pipe(filter.restore())
    .pipe(gulp.dest('./build/assets/css/'));
});

// Compile stylesheets with node-sass
gulp.task('sass:node', function() {
  return gulp.src('docs/assets/scss/app.scss')
    .pipe($.sass({
      includePaths: paths.sass.loadPaths,
      outputStyle: 'nested',
      errLogToConsole: true
    }))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie 10']
    }))
    .pipe($.concat('app_node.css'))
    .pipe(gulp.dest('./build/assets/css/'));
});

// Generate Sass settings file
gulp.task('sass:settings', function() {
  settingsParser([
    'scss/_includes.scss',
    'scss/_global.scss',
    'scss/helpers/_breakpoints.scss',
    'scss/components/_typography.scss',
    'scss/components/_grid.scss',
    'scss/components/_button.scss',
    'scss/components/*.scss'
  ], {
    title: 'Foundation for Apps Settings'.toUpperCase(),
    partialsPath: 'docs/partials/scss',
    settingsPath: 'scss'
  });
});

// 6. JAVASCRIPT
// - - - - - - - - - - - - - - -

// Compile Foundation JavaScript
gulp.task('javascript', function() {
  var dirs = paths.javascript.libs.concat(
    paths.javascript.foundation,
    paths.javascript.docs
  );
  return gulp.src(dirs)
    .pipe($.uglify({
      beautify: true,
      mangle: false
    }).on('error', function(e) {
      console.log(e);
    }))
    .pipe($.concat('app.js'))
    .pipe(gulp.dest('./build/assets/js/'))
  ;
});

// 7. SERVER
// - - - - - - - - - - - - - - -

gulp.task('server:start', function() {
  $.connect.server({
    root: './build',
    middleware: function() {
      return [
        modRewrite(['^[^\\.]*$ /index.html [L]'])
      ];
    },
  });
});

// 8. TESTING
// - - - - - - - - - - - - - - -

gulp.task('test:karma', ['build', 'sass:node'], function() {
  var testFiles = [
    'build/assets/js/foundation.js',
    'build/assets/js/dependencies.js',
    'build/assets/js/app.js',
    'bower_components/angular-mocks/angular-mocks.js',
    'bower_components/jsdiff/diff.js',
    'build/assets/css/app.css',
    'build/assets/css/app_node.css',
    'tests/unit/common/*Spec.js'
  ];

  return gulp.src(testFiles)
    .pipe($.karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      throw err;
    })
  ;

});

gulp.task('test:sass', function() {
  return $.rubySass('./tests/unit/scss/tests.scss', {
    loadPath: paths.sass.testPaths,
    style: 'nested',
    bundleExec: true
  })
    .on('data', function(data) {
      console.log(data.contents.toString());
    });
});

gulp.task('test', ['test:karma', 'test:sass'], function() {
  console.log('Tests finished.');
});

gulp.task('compile-motion', ['clean', 'sass', 'javascript'], function() {
  gulp.src('./tests/motion/index.html')
    .pipe(gulp.dest('./build'));
  gulp.src('./tests/motion/templates/**/*.html')
    .pipe(routes({
      path: 'build/assets/js/routes.js',
      root: 'tests/motion'
    }))
    .pipe(gulp.dest('./build/templates'));
});

gulp.task('test:motion', ['server:start', 'compile-motion'], function() {
  gulp.watch(['js/**/*', 'tests/motion/**/*'], ['compile-motion']);
});

// 9. DEPLOYMENT
// - - - - - - - - - - - - - - -

// Deploy distribution files
gulp.task('deploy:dist', ['clean:dist'], function(cb) {
  var filter = $.filter(['*.css']);

  var css = $.rubySass('scss/', {
      loadPath: ['scss'],
      style: 'nested',
      bundleExec: true
    })
    .pipe(filter)
      .pipe($.autoprefixer({
        browsers: ['last 2 versions', 'ie 10']
      }))
    .pipe(filter.restore())
    .pipe($.rename('foundation-apps.css'))
    .pipe(gulp.dest('./dist/css'))
    .pipe($.minifyCss())
    .pipe($.rename('foundation-apps.min.css'))
    .pipe(gulp.dest('./dist/css'));

  var js = gulp.src(paths.javascript.foundation)
    .pipe($.concat('foundation-apps.js'))
    .pipe(gulp.dest('./dist/js'))
    .pipe($.uglify())
    .pipe($.rename('foundation-apps.min.js'))
    .pipe(gulp.dest('./dist/js'));

  var partials = gulp.src(paths.html.partials)
    .pipe($.ngHtml2js({
      prefix: 'components/',
      moduleName: 'foundation',
      declareModule: false
    }))
    .pipe($.concat('foundation-apps-templates.js'))
    .pipe(gulp.dest('./dist/js'))
    .pipe($.uglify())
    .pipe($.rename('foundation-apps-templates.min.js'))
    .pipe(gulp.dest('./dist/js'))

  cb();
});

// Deploy documentation
gulp.task('deploy:docs', ['build'], function() {
  return gulp.src('build/**')
    .pipe($.prompt.confirm("Make sure everything looks good before you deploy."))
    .pipe($.rsync({
      root: 'build',
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-apps/current'
    }));
});

// Deploy to CDN
gulp.task('deploy:cdn', ['deploy:dist'], function() {
  return gulp.src('./dist/**/*', {base:'./dist/'})
    .pipe($.filter(['**/*.css', '**/*.js']))
    .pipe(addVersions())
    .pipe($.rsync({
      hostname: 'deployer@72.32.134.77',
      destination: '/home/deployer/sites/foundation-apps-cdn/current',
      relative: false
    }));
});

// 10. NOW BRING IT TOGETHER
// - - - - - - - - - - - - - - -

// Build the documentation once
gulp.task('build', function(cb) {
  runSequence('clean', ['copy', 'copy:partials', 'css', 'javascript', 'copy:templates'], function() {
    cb();
  });
});

// Build the documentation, start a test server, and re-compile when files change
gulp.task('default', ['build', 'server:start'], function() {

  // Watch static files
  gulp.watch(paths.html.base, ['copy']);

  // Watch Angular templates
  gulp.watch(paths.html.templates, ['copy:templates']);

  // Watch Angular partials
  gulp.watch(paths.html.partials, ['copy:partials']);

  // Watch Sass
  gulp.watch(['./docs/assets/scss/**/*', './scss/**/*'], ['css']);

  // Watch JavaScript
  gulp.watch(paths.javascript.foundation.concat(paths.javascript.docs), ['javascript']);
});
<|endoftext|>