<commit_before>var gulp = require("gulp");
var tsc = require("gulp-typescript");
var sourcemaps = require("gulp-sourcemaps");
var nodemon = require('gulp-nodemon');
var livereload = require('gulp-livereload');
var tslint = require('gulp-tslint');
var ignore = require('gulp-ignore');
var ciDevVersion = require('./scripts/ci-version-devbuild');
//var nodeDebug = require("gulp-node-debug");

var tsProject = tsc.createProject('tsconfig.json', { sortOutput: true });

gulp.task('compile-ts', function () {
    var errors = 0;
    var tsResult = tsProject.src()//gulp.src()
                       .pipe(sourcemaps.init())
        .pipe(tsc(tsProject))
        .on("error", function() {
            errors++;
        })
        .on("finish", function() {
            if (errors !== 0) {
                console.error("Typescript error(s) found. Build Failed");
                process.exit(1);
            }
        });

    tsResult.dts.pipe(gulp.dest("./"));
    return tsResult.js
                        .pipe(sourcemaps.write('.'))
                        .pipe(gulp.dest("./"));
});

gulp.task('live-reload', function () {
    gulp.src(["**/*.js", "!node_modules/**/*.*"])
			.pipe(livereload());
});

gulp.task("tslint", function () {
	return tsProject.src()
		.pipe(ignore.exclude('*.d.ts'))
        .pipe(tslint({
            rulesDirectory: ['node_modules/tslint-microsoft-contrib']
        }))
        .pipe(tslint.report("verbose"))
});

gulp.task("nodemon", ["compile-ts"], function () {
    // listen for changes
    livereload.listen();
    // configure nodemon
    nodemon({
        // the script to run the app
        script: "server.js",
        ext: 'js'
    }).on('start', function () {
        // when the app has restarted, run livereload.
        gulp.src("server.js")
			.pipe(livereload());
    })
});

gulp.task("watch", function () {
    gulp.watch("./**/*.ts", ["compile-ts", "live-reload"]);
})

gulp.task("ci-dev", function () {
    ciDevVersion.setNewDevBuildVersion('package.json');
});

// Task
gulp.task('default', ["nodemon", "watch"]);

gulp.task('ts', ["compile-ts","unit-test"]);
<commit_msg>removed gulp task<commit_after>var gulp = require("gulp");
var tsc = require("gulp-typescript");
var sourcemaps = require("gulp-sourcemaps");
var nodemon = require('gulp-nodemon');
var livereload = require('gulp-livereload');
var tslint = require('gulp-tslint');
var ignore = require('gulp-ignore');
var ciDevVersion = require('./scripts/ci-version-devbuild');
//var nodeDebug = require("gulp-node-debug");

var tsProject = tsc.createProject('tsconfig.json', { sortOutput: true });

gulp.task('compile-ts', function () {
    var errors = 0;
    var tsResult = tsProject.src()//gulp.src()
                       .pipe(sourcemaps.init())
        .pipe(tsc(tsProject))
        .on("error", function() {
            errors++;
        })
        .on("finish", function() {
            if (errors !== 0) {
                console.error("Typescript error(s) found. Build Failed");
                process.exit(1);
            }
        });

    tsResult.dts.pipe(gulp.dest("./"));
    return tsResult.js
                        .pipe(sourcemaps.write('.'))
                        .pipe(gulp.dest("./"));
});

gulp.task('live-reload', function () {
    gulp.src(["**/*.js", "!node_modules/**/*.*"])
			.pipe(livereload());
});

gulp.task("tslint", function () {
	return tsProject.src()
		.pipe(ignore.exclude('*.d.ts'))
        .pipe(tslint({
            rulesDirectory: ['node_modules/tslint-microsoft-contrib']
        }))
        .pipe(tslint.report("verbose"))
});

gulp.task("nodemon", ["compile-ts"], function () {
    // listen for changes
    livereload.listen();
    // configure nodemon
    nodemon({
        // the script to run the app
        script: "server.js",
        ext: 'js'
    }).on('start', function () {
        // when the app has restarted, run livereload.
        gulp.src("server.js")
			.pipe(livereload());
    })
});

gulp.task("watch", function () {
    gulp.watch("./**/*.ts", ["compile-ts", "live-reload"]);
})

gulp.task("ci-dev", function () {
    ciDevVersion.setNewDevBuildVersion('package.json');
});

// Task
gulp.task('default', ["nodemon", "watch"]);

gulp.task('ts', ["compile-ts"]);
<|endoftext|>


<commit_before>import cleanText from "./clean-text";
import toFunctionCall from "./ast/to-function-call";
import injectRenderArbitrary from "./runtime/render-arbitrary";
import iDOMMethod from "./idom-method";
import isLiteralOrUndefined from "./ast/is-literal-or-undefined";

// Filters out empty children, and transform JSX expressions
// into function calls.
export default function buildChildren(t, scope, file, children, { eager }) {
  let renderArbitraryRef;
  const eagerChildren = [];

  children = children.reduce((children, child) => {
    const wasInExpressionContainer = t.isJSXExpressionContainer(child);
    if (wasInExpressionContainer) {
      child = child.expression;
    }

    if (t.isJSXEmptyExpression(child)) { return children; }

    if (isLiteralOrUndefined(t, child)) {
      let value = child.value;
      const type = typeof value;

      if (type === "string") {
        value = cleanText(value);
        if (!value) { return children; }
      }

      if (type === "string" || type === "number") {
        child = toFunctionCall(t, iDOMMethod(file, "text"), [t.stringLiteral(value)]);
      }
    } else if (wasInExpressionContainer && !child._iDOMwasJSX) {
      renderArbitraryRef = renderArbitraryRef || injectRenderArbitrary(t, file);

      if (eager) {
        const ref = scope.generateUidIdentifierBasedOnNode(child);
        eagerChildren.push(t.variableDeclarator(ref, child));
        child = ref;
      }

      child = toFunctionCall(t, renderArbitraryRef, [child]);
    }

    children.push(child);
    return children;
  }, []);

  return { children, eagerChildren };
}
<commit_msg>Detect JSXTexts as text<commit_after>import cleanText from "./clean-text";
import toFunctionCall from "./ast/to-function-call";
import injectRenderArbitrary from "./runtime/render-arbitrary";
import iDOMMethod from "./idom-method";
import isLiteralOrUndefined from "./ast/is-literal-or-undefined";

// Filters out empty children, and transform JSX expressions
// into function calls.
export default function buildChildren(t, scope, file, children, { eager }) {
  let renderArbitraryRef;
  const eagerChildren = [];

  children = children.reduce((children, child) => {
    const wasInExpressionContainer = child.isJSXExpressionContainer();
    if (wasInExpressionContainer) {
      child = child.get("expression");
    }
    const isJSXText = child.isJSXText();

    if (child.isJSXEmptyExpression()) { return children; }
    child = child.node;

    if (isLiteralOrUndefined(t, child) || isJSXText) {
      let value = child.value;
      const type = typeof value;

      if (type === "string") {
        value = cleanText(value);
        if (!value) { return children; }
      }

      if (type === "string" || type === "number") {
        child = toFunctionCall(t, iDOMMethod(file, "text"), [t.stringLiteral(value)]);
      }
    } else if (wasInExpressionContainer && !child._iDOMwasJSX) {
      renderArbitraryRef = renderArbitraryRef || injectRenderArbitrary(t, file);

      if (eager) {
        const ref = scope.generateUidIdentifierBasedOnNode(child);
        eagerChildren.push(t.variableDeclarator(ref, child));
        child = ref;
      }

      child = toFunctionCall(t, renderArbitraryRef, [child]);
    }

    children.push(child);
    return children;
  }, []);

  return { children, eagerChildren };
}
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')

const gulp = require('gulp')
const gutil = require('gulp-util')
const source = require('vinyl-source-stream')
const buffer = require('vinyl-buffer')
const through = require('through2')
const merge = require('merge2')

const ts = require('gulp-typescript')
const tsify = require('tsify')
const typedoc = require('gulp-typedoc')
const sourcemaps = require('gulp-sourcemaps')

const mocha = require('gulp-mocha')

const browserify = require('browserify')

const tsSourceProject = ts.createProject('./configs/tsconfig.json')
const tsTestProject = ts.createProject('./configs/tsconfig.json')

gulp.task('create-module-file', () => {
  return gulp.src(['./src/**'])
    .pipe(
      through.obj((file, encoding, callback) => {
        if (!file.path) {
          callback()
          return
        }

        // It file is not directory, do nothing
        if (!fs.statSync(file.path).isDirectory()) {
          callback()
          return
        }

        const modulePath = path.resolve(file.path, 'module.ts')

        let text = ''

        const children = fs.readdirSync(file.path, encoding)
        children.forEach(x => {
          if (x === 'module.ts') return

          let fileName = path.basename(x, '.ts')

          if (fs.statSync(path.resolve(file.path, x)).isDirectory()) {
            fileName = path.relative(file.path, path.resolve(file.path, x, 'module'))
            text += `import * as _${x} from "./${fileName}"\n`
            text += `export const ${x} = _${x}\n`
          } else {
            text += `export * from "./${fileName}"\n`
          }
        })

        const wStream = fs.createWriteStream(modulePath, { defaultEncoding: encoding })
        wStream.write(text)
        wStream.end()
        callback(null, wStream)
      })
    )
})

// compile source files
gulp.task('compile-src', ['create-module-file'], () => {
  const tsResult = gulp.src(['./src/**/*.ts'])
    .pipe(sourcemaps.init())
    .pipe(tsSourceProject(ts.reporter.defaultReporter()))

  return merge([
    tsResult.dts.pipe(gulp.dest('./target/interface')),
    tsResult.js
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./target/src'))
  ])
})

// compile test files
gulp.task('compile-test', ['compile-src'], () => {
  return gulp.src(['./test/**/*.ts'])
    .pipe(tsTestProject(ts.reporter.defaultReporter()))
    .pipe(gulp.dest('./target/test'))
})

// Run test program
gulp.task('test', ['compile-src', 'compile-test'], () => {
  return gulp.src(['./target/test/**/*.js'])
    .pipe(mocha({ repoter: 'list' }))
    .on('error', gutil.log)
})
gulp.task('watch-test', () => gulp.watch(['src/**/*.ts', 'test/**/*.ts'], ['test']))

// Create a documentation
gulp.task('docs', ['create-module-file'], () => {
  const tsconfigs = require('./configs/tsconfig.json').compilerOptions
  const packageOption = require('./package.json')
  const configs = {
    target: tsconfigs.target,
    module: tsconfigs.module,
    out: './docs',
    includeDeclarations: true,
    name: packageOption.name,
    version: true
  }
  gulp.src(['./src/**/*.ts'], { read: false })
    .pipe(typedoc(configs))
})

// Browserify this module
gulp.task('browserify', () => {
  const tsconfigs = require('./configs/tsconfig.json').compilerOptions
  browserify({entries: ['browser/index.ts']})
  .plugin(tsify, tsconfigs)
  .bundle()
  .pipe(source('diplomacy.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('browser/'))
})
<commit_msg>Fix gulpfile<commit_after>const fs = require('fs')
const path = require('path')

const gulp = require('gulp')
const gutil = require('gulp-util')
const source = require('vinyl-source-stream')
const buffer = require('vinyl-buffer')
const through = require('through2')
const merge = require('merge2')

const ts = require('gulp-typescript')
const tsify = require('tsify')
const typedoc = require('gulp-typedoc')
const sourcemaps = require('gulp-sourcemaps')

const mocha = require('gulp-mocha')

const browserify = require('browserify')

const tsSourceProject = ts.createProject('./configs/tsconfig.json')
const tsTestProject = ts.createProject('./configs/tsconfig.json')

gulp.task('create-module-file', () => {
  return gulp.src(['./src/**'])
    .pipe(
      through.obj((file, encoding, callback) => {
        if (!file.path) {
          callback()
          return
        }

        // It file is not directory, do nothing
        if (!fs.statSync(file.path).isDirectory()) {
          callback()
          return
        }

        const modulePath = path.resolve(file.path, 'module.ts')

        let text = ''

        const children = fs.readdirSync(file.path, encoding)
        children.forEach(x => {
          if (x === 'module.ts') return

          let fileName = path.basename(x, '.ts')

          if (fs.statSync(path.resolve(file.path, x)).isDirectory()) {
            fileName = path.relative(file.path, path.resolve(file.path, x, 'module'))
            text += `import * as _${x} from "./${fileName}"\n`
            text += `export const ${x} = _${x}\n`
          } else {
            if (!x.endsWith('.ts')) return

            text += `export * from "./${fileName}"\n`
          }
        })

        const wStream = fs.createWriteStream(modulePath, { defaultEncoding: encoding })
        wStream.write(text)
        wStream.end()
        callback(null, wStream)
      })
    )
})

// compile source files
gulp.task('compile-src', ['create-module-file'], () => {
  const tsResult = gulp.src(['./src/**/*.ts'])
    .pipe(sourcemaps.init())
    .pipe(tsSourceProject(ts.reporter.defaultReporter()))

  return merge([
    tsResult.dts.pipe(gulp.dest('./target/interface')),
    tsResult.js
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./target/src'))
  ])
})

// compile test files
gulp.task('compile-test', ['compile-src'], () => {
  return gulp.src(['./test/**/*.ts'])
    .pipe(tsTestProject(ts.reporter.defaultReporter()))
    .pipe(gulp.dest('./target/test'))
})

// Run test program
gulp.task('test', ['compile-src', 'compile-test'], () => {
  return gulp.src(['./target/test/**/*.js'])
    .pipe(mocha({ repoter: 'list' }))
    .on('error', gutil.log)
})
gulp.task('watch-test', () => gulp.watch(['src/**/*.ts', 'test/**/*.ts'], ['test']))

// Create a documentation
gulp.task('docs', ['create-module-file'], () => {
  const tsconfigs = require('./configs/tsconfig.json').compilerOptions
  const packageOption = require('./package.json')
  const configs = {
    target: tsconfigs.target,
    module: tsconfigs.module,
    out: './docs',
    includeDeclarations: true,
    name: packageOption.name,
    version: true
  }
  gulp.src(['./src/**/*.ts'], { read: false })
    .pipe(typedoc(configs))
})

// Browserify this module
gulp.task('browserify', () => {
  const tsconfigs = require('./configs/tsconfig.json').compilerOptions
  browserify({entries: ['browser/index.ts']})
  .plugin(tsify, tsconfigs)
  .bundle()
  .pipe(source('diplomacy.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init())
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('browser/'))
})
<|endoftext|>


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

var eslint = require('gulp-eslint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sass = require('gulp-ruby-sass');
var sourcemaps = require('gulp-sourcemaps');
var ngHtml2Js = require('gulp-ng-html2js');
var addStream = require('add-stream');
var minifyHtml = require("gulp-minify-html");

var minificationSuffix = '.min';
var jsPath = ['app/**/*.js'];
var jsTestPath = ['app/**/*Test.js'];
var jsAppPath = [jsPath[0], '!' + jsTestPath[0]];
var sassPath = ['app/*.scss'];
var angularTemplatesPath = ['app/**/*.html'];
var indexPath = ['app/index.html'];
var buildDirectory = './build/';
var defaultTasks = [
    'lint',
    'lint-test',
    'scripts',
    'sass',
    'templates',
    'copy-index',
    'copy-lib'
];

gulp.task('lint', function() {
    return gulp.src(jsAppPath)
        .pipe(eslint({
            "configFile": "eslint/browser.json"
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('lint-test', function() {
    return gulp.src(jsTestPath)
        .pipe(eslint({
            "configFile": "eslint/jasmine.json"
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('scripts', function() {
    return gulp.src(jsAppPath)
        .pipe(sourcemaps.init())
            .pipe(concat('main.js'))
            .pipe(rename({suffix: minificationSuffix}))
            .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(buildDirectory + 'js'));
});

gulp.task('templates', function() {
    return gulp.src(angularTemplatesPath)
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(ngHtml2Js({
            moduleName: 'templates',
            prefix: 'app/'
        }))
        .pipe(concat('templates.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest(buildDirectory + 'js'));
});

gulp.task('sass', function() {
    return sass(sassPath, {
            style: 'compressed',
            sourcemap: true
        })
        .pipe(rename({suffix: minificationSuffix}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(buildDirectory + 'css'));
});

gulp.task('copy-index', function() {
    return gulp.src(indexPath)
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(gulp.dest(buildDirectory));
});

gulp.task('copy-lib', function() {
    return gulp.src(['bower_components/**', 'lib/**'])
        .pipe(gulp.dest(buildDirectory + 'lib'));
})

gulp.task('watch', function() {
    gulp.watch(jsPath
        .concat(sassPath)
        .concat(angularTemplatesPath)
        .concat(indexPath), defaultTasks);
});

gulp.task('build', defaultTasks)

gulp.task('default', ['build', 'watch']);
<commit_msg>Add karma tests to gulp<commit_after>var gulp = require('gulp');

var eslint = require('gulp-eslint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sass = require('gulp-ruby-sass');
var sourcemaps = require('gulp-sourcemaps');
var ngHtml2Js = require('gulp-ng-html2js');
var addStream = require('add-stream');
var minifyHtml = require("gulp-minify-html");
var Server = require('karma').Server;

var minificationSuffix = '.min';
var jsPath = ['app/**/*.js'];
var jsTestPath = ['app/**/*Test.js'];
var jsAppPath = [jsPath[0], '!' + jsTestPath[0]];
var sassPath = ['app/*.scss'];
var angularTemplatesPath = ['app/**/*.html'];
var indexPath = ['app/index.html'];
var buildDirectory = './build/';

gulp.task('lint', function() {
    return gulp.src(jsAppPath)
        .pipe(eslint({
            "configFile": "eslint/browser.json"
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('lint-test', function() {
    return gulp.src(jsTestPath)
        .pipe(eslint({
            "configFile": "eslint/jasmine.json"
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('scripts', function() {
    return gulp.src(jsAppPath)
        .pipe(sourcemaps.init())
            .pipe(concat('main.js'))
            .pipe(rename({suffix: minificationSuffix}))
            .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(buildDirectory + 'js'));
});

gulp.task('templates', function() {
    return gulp.src(angularTemplatesPath)
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(ngHtml2Js({
            moduleName: 'templates',
            prefix: 'app/'
        }))
        .pipe(concat('templates.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest(buildDirectory + 'js'));
});

gulp.task('sass', function() {
    return sass(sassPath, {
            style: 'compressed',
            sourcemap: true
        })
        .pipe(rename({suffix: minificationSuffix}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(buildDirectory + 'css'));
});

gulp.task('copy-index', function() {
    return gulp.src(indexPath)
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(gulp.dest(buildDirectory));
});

gulp.task('copy-lib', function() {
    return gulp.src(['bower_components/**', 'lib/**'])
        .pipe(gulp.dest(buildDirectory + 'lib'));
});

gulp.task('build', [
    'lint',
    'lint-test',
    'scripts',
    'sass',
    'templates',
    'copy-index',
    'copy-lib'
]);

gulp.task('test', ['build'], function(done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});

gulp.task('tdd', ['test'], function() {
    gulp.watch(jsPath
        .concat(sassPath)
        .concat(angularTemplatesPath)
        .concat(indexPath), ['test']);
});

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


<commit_before>'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');
const cache = require('gulp-cache');
const istanbul = require('gulp-istanbul');

gulp.task('pre-test', function() {
  return gulp.src(['./lib/*.js', './model/*.js', '!node_modules/**'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function() {
  gulp.src('./test/*-test.js', { read: false})
  .pipe(mocha({ report: 'spec'}))
  .pipe(istanbul.writeReports())
  .pipe(istanbul.enforceThresholds({thresholds: {global: 90}}));
});

gulp.task('lint', function() {
  return gulp.src(['**/*.js', '!node_modules/**', '**/**/*.js', '!coverage/**'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
});

gulp.task('dev', function() {
  gulp.watch(['**/*.js', '!node_modules/**', '**/**/*.js'], ['lint', 'test']);
});

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

gulp.task('clear', function (done) {
  return cache.clearAll(done);
});
<commit_msg>fix package json to pass linter<commit_after>'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');
const cache = require('gulp-cache');
const istanbul = require('gulp-istanbul');

gulp.task('pre-test', function() {
  return gulp.src(['./lib/*.js', './model/*.js', '!node_modules/**'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function() {
  gulp.src('./test/*-test.js', { read: false})
  .pipe(mocha({ report: 'spec'}))
  .pipe(istanbul.writeReports())
  .pipe(istanbul.enforceThresholds({thresholds: {global: 90}}));
});

gulp.task('lint', function() {
  return gulp.src(['**/*.js', '!node_modules/**', '!public/**', '**/**/*.js', '!coverage/**'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
});

gulp.task('dev', function() {
  gulp.watch(['**/*.js', '!node_modules/**', '**/**/*.js'], ['lint', 'test']);
});

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

gulp.task('clear', function (done) {
  return cache.clearAll(done);
});
<|endoftext|>


<commit_before>var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var less   = require('gulp-less');
var path   = require('path');
var app    = require('./app');
var debug  = require('debug')('podplay:server');
var http   = require('http');

// compile less stylesheets
gulp.task('style', function() {
  return gulp.src('./styles/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'styles', 'includes') ]
    }))
    .pipe(gulp.dest('./public/stylesheets'));
});

// lint javascript
gulp.task('lint', function() {
  return gulp.src('./public/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default')); // maybe install a better reporter
});

// run the express server
gulp.task('serve', function() {
  var port = '8080';
  app.set('port', port);

  var server = http.createServer(app);

  server.listen(port);
  console.log('server running on port ' + port);
  server.on('error', function(error) {

    if (error.syscall !== 'listen') {
      throw error;
    }

    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  });

  server.on('listening', function() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  });

})

// build less, lint JS and run application
gulp.task('default', ['style', 'lint', 'serve'], function() {
  console.log('all done');
});

<commit_msg>Changed port back to 80 for master branch<commit_after>var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var less   = require('gulp-less');
var path   = require('path');
var app    = require('./app');
var debug  = require('debug')('podplay:server');
var http   = require('http');

// compile less stylesheets
gulp.task('style', function() {
  return gulp.src('./styles/**/*.less')
    .pipe(less({
      paths: [ path.join(__dirname, 'styles', 'includes') ]
    }))
    .pipe(gulp.dest('./public/stylesheets'));
});

// lint javascript
gulp.task('lint', function() {
  return gulp.src('./public/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default')); // maybe install a better reporter
});

// run the express server
gulp.task('serve', function() {
  var port = '80';
  app.set('port', port);

  var server = http.createServer(app);

  server.listen(port);
  console.log('server running on port ' + port);
  server.on('error', function(error) {

    if (error.syscall !== 'listen') {
      throw error;
    }

    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  });

  server.on('listening', function() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  });

})

// build less, lint JS and run application
gulp.task('default', ['style', 'lint', 'serve'], function() {
  console.log('all done');
});

<|endoftext|>


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

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

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

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

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

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

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

gulp.task('coveralls', ['test'], function() {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['test', 'coveralls']);
<commit_msg>Change gulp-mocha timeout to 20000<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

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

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

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

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

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

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

gulp.task('coveralls', ['test'], function() {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

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


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import hoist, { extractRef } from 'hocs/hoist';
import joinKeys from 'utils/joinKeys';
import withModalStore from 'hocs/withModalStore';
import withStore from 'hocs/withStore';
import withIssuer from 'hocs/withIssuer';
import { MODAL } from 'utils/Issuers';
import { UPDATE, CREATE, REF } from 'constants/Actions';
import routerStore from 'stores/routerStore';

// Notice that this `Action` is NOT Redux or MobX action.
export default function withActions(WrappedComponent) {
	@hoist(WrappedComponent)
	@withIssuer()
	@withStore()
	@withModalStore()
	@observer
	class WithActions extends Component {
		static propTypes = {
			modalStore: PropTypes.object.isRequired,
			store: PropTypes.object.isRequired,
			issuers: PropTypes.instanceOf(Set).isRequired,
		};

		static contextTypes = {
			tableRowKey: PropTypes.string,
		};

		constructor(props, context) {
			super(props, context);
			const { tableRowKey } = context;
			if (tableRowKey) {
				this._selectedKeys = [tableRowKey];
			}
		}

		getSelectedKeys() {
			const { context: { tableRowKey }, props: { store } } = this;
			return tableRowKey ? [tableRowKey] : store.selectedKeys;
		}

		getSelectedKeysString = () => {
			return joinKeys(this.getSelectedKeys());
		};

		open = (name, params = {}, options) => {
			const { modalStore, issuers } = this.props;
			const keys = joinKeys(this.getSelectedKeys());
			if ((name === CREATE || name === UPDATE) && !issuers.has(MODAL)) {
				const path =
					params.path || (name === UPDATE ? `/update/${keys}` : '/create');
				routerStore.location.pathname += path;
			} else {
				modalStore.open(
					{
						keys,
						...params,
						name,
					},
					options
				);
			}
		};

		openCreaterModal = (params = {}, options) => {
			params.keys = params.keys || '';
			this.open(CREATE, params, options);
		};

		openUpdaterModal = (params = {}, options) => {
			const { select, ...config } = params;
			if (select && select.length) {
				config.select = select.join(',');
			}
			this.open(UPDATE, config, options);
		};

		openRefModal = (params = {}, options) => {
			const {
				table,
				title,
				noQuery,
				fetch = 'fetch',
				save = 'request',
				width = 880,
			} = params;
			const config = { table, title, fetch, save, width };
			if (noQuery) config.noQuery = '✓';
			this.open(REF, config, options);
		};

		_getData = () => {
			const selectedKeys = this.getSelectedKeys();
			return this.props.store.getData(selectedKeys[0]);
		};

		render() {
			const { props: { modalStore, store, ...props } } = this;
			return (
				<WrappedComponent
					{...extractRef(props)}
					actions={{
						store,
						open: this.open,
						openCreaterModal: this.openCreaterModal,
						openUpdaterModal: this.openUpdaterModal,
						openRefModal: this.openRefModal,
						selectedKeys: this._selectedKeys || store.selectedKeys,
						getSelectedKeysString: this.getSelectedKeysString,
						getData: this._getData,
						issuers: props.issuers,
					}}
				/>
			);
		}
	}

	return WithActions;
}
<commit_msg>use updater or creater modal outside toolbar<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import hoist, { extractRef } from 'hocs/hoist';
import joinKeys from 'utils/joinKeys';
import withModalStore from 'hocs/withModalStore';
import withStore from 'hocs/withStore';
import withIssuer from 'hocs/withIssuer';
import { MODAL, TOOLBAR } from 'utils/Issuers';
import { UPDATE, CREATE, REF } from 'constants/Actions';
import routerStore from 'stores/routerStore';

// Notice that this `Action` is NOT Redux or MobX action.
export default function withActions(WrappedComponent) {
	@hoist(WrappedComponent)
	@withIssuer()
	@withStore()
	@withModalStore()
	@observer
	class WithActions extends Component {
		static propTypes = {
			modalStore: PropTypes.object.isRequired,
			store: PropTypes.object.isRequired,
			issuers: PropTypes.instanceOf(Set).isRequired,
		};

		static contextTypes = {
			tableRowKey: PropTypes.string,
		};

		constructor(props, context) {
			super(props, context);
			const { tableRowKey } = context;
			if (tableRowKey) {
				this._selectedKeys = [tableRowKey];
			}
		}

		getSelectedKeys() {
			const { context: { tableRowKey }, props: { store } } = this;
			return tableRowKey ? [tableRowKey] : store.selectedKeys;
		}

		getSelectedKeysString = () => {
			return joinKeys(this.getSelectedKeys());
		};

		open = (name, params = {}, options) => {
			const { modalStore, issuers } = this.props;
			const keys = joinKeys(this.getSelectedKeys());
			if (
				(name === CREATE || name === UPDATE) &&
				issuers.has(TOOLBAR) &&
				!issuers.has(MODAL)
			) {
				const path =
					params.path || (name === UPDATE ? `/update/${keys}` : '/create');
				routerStore.location.pathname += path;
			} else {
				modalStore.open(
					{
						keys,
						...params,
						name,
					},
					options
				);
			}
		};

		openCreaterModal = (params = {}, options) => {
			params.keys = params.keys || '';
			this.open(CREATE, params, options);
		};

		openUpdaterModal = (params = {}, options) => {
			const { select, ...config } = params;
			if (select && select.length) {
				config.select = select.join(',');
			}
			this.open(UPDATE, config, options);
		};

		openRefModal = (params = {}, options) => {
			const {
				table,
				title,
				noQuery,
				fetch = 'fetch',
				save = 'request',
				width = 880,
			} = params;
			const config = { table, title, fetch, save, width };
			if (noQuery) config.noQuery = '✓';
			this.open(REF, config, options);
		};

		_getData = () => {
			const selectedKeys = this.getSelectedKeys();
			return this.props.store.getData(selectedKeys[0]);
		};

		render() {
			const { props: { modalStore, store, ...props } } = this;
			return (
				<WrappedComponent
					{...extractRef(props)}
					actions={{
						store,
						open: this.open,
						openCreaterModal: this.openCreaterModal,
						openUpdaterModal: this.openUpdaterModal,
						openRefModal: this.openRefModal,
						selectedKeys: this._selectedKeys || store.selectedKeys,
						getSelectedKeysString: this.getSelectedKeysString,
						getData: this._getData,
						issuers: props.issuers,
					}}
				/>
			);
		}
	}

	return WithActions;
}
<|endoftext|>


<commit_before>'use strict';
const gulp = require('gulp'),
    gulpJsdoc2md = require('gulp-jsdoc-to-markdown'),
    rename = require('gulp-rename'),
    istanbul = require('gulp-istanbul'),
    istanbulHarmony = require('istanbul-harmony'),
    mocha = require('gulp-mocha'),
    eslint = require('gulp-eslint'),
    git = require('gulp-git');

const files = ['*.js', '!./gulpfile.js', '!node_modules/**', '!test/**'],
    docs = ['README.md', 'docs/**/*.md'],
    tests = ['test/**/*.js'];

const JobNumber = process.env.TRAVIS_JOB_NUMBER,
    runDocs = !JobNumber || /[.]1$/.test(JobNumber);

/**
 * Pull git branch locally (solves detached head issue in CI)
 */
gulp.task('gitBranch', (done) => {
    let complete = false;
    const branch = process.env.TRAVIS_BRANCH;
    // Abort(successfully) early if not running in CI
    if (!(JobNumber && runDocs && branch)) {
        return done();
    }
    git.checkout(branch, () => {
        // Make sure we have full log history.
        git.pull('origin', branch, {}, () => {
            if (!complete) {
                done();
            }
            complete = true;
        });
    });
});

/**
 * Generate API documentation for all js files, place markup in the correct folder for readthedocs.org
 */
gulp.task('docs', ['gitBranch'], (done) => {
    // Abort(successfully) early if running in CI and not job #1
    if (!runDocs) {
        return done();
    }
    gulp.src(files)
        .pipe(gulpJsdoc2md({}))
        .on('error', done)
        .pipe(rename((path) => {
            path.extname = '.md';
        }))
        .pipe(gulp.dest('docs/api'))
        .on('finish', done);
});

/**
 * Run all js files through eslint and report status.
 */
gulp.task('lintCore', () => {
    return gulp.src(files)
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Run all tests through eslint and report status.
 */
gulp.task('lintTests', () => {
    return gulp.src(tests)
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Set git username/email to CI user
 */
gulp.task('gitConfig', (done) => {
    // Abort(successfully) early if not running in CI
    if (!JobNumber) {
        return done();
    }
    git.exec({
        args: 'config user.name "Travis-CI"'
    }, () => {
        git.exec({
            args: 'config user.email "Travis-CI@servercooties.com"'
        }, () => {
            done();
        });
    });
});

/**
 * Commit generated documentation to be picked up by readthedocs.org
 *
 * Add CI tag to commit to prevent CI jobs from being created by checking in docs
 */
gulp.task('commitDocs', ['gitConfig'], (done) => {
    gulp.src(docs)
        .pipe(git.add())
        .pipe(git.commit('Automatically push updated documentation [ci skip]'))
        .on('error', () => 0)
        .on('finish', done);
});

/**
 * Commit and push docs to github to be picked up by readthedocs.org
 */
gulp.task('pushDocs', ['gitConfig', 'commitDocs'], (done) => {
    //Abort(successfully) early if running in CI and not job #1
    if (!runDocs) {
        return done();
    }
    git.addRemote('github', 'https://github.com/SockDrawer/SockBot.git', (e) => {
        if (e) {
            done();
        } else {
            git.push('github', 'HEAD', {
                args: ['-q']
            }, () => {
                done();
            });
        }
    });
});

/**
 * Run code coverage instrumented tests
 */
gulp.task('test', ['lintCore', 'lintTests'], (done) => {
    gulp.src(files)
        // Instrument code files with istanbulHarmony
        .pipe(istanbul({
            instrumenter: istanbulHarmony.Instrumenter,
            includeUntested: true
        }))
        // hook require function for complete code coverage
        .pipe(istanbul.hookRequire())
        .on('finish', () => {
            // Run all tests
            gulp.src(tests)
                .pipe(mocha({
                    reporter: 'dot'
                }))
                .on('error', done)
                // Write code coverage reports
                .pipe(istanbul.writeReports())
                .on('finish', done);
        });
});

// Meta tasks
gulp.task('buildDocs', ['docs'], () => 0);
gulp.task('preBuild', ['buildDocs'], () => 0);
gulp.task('postBuild', ['pushDocs'], () => 0);
gulp.task('default', ['lint'], () => 0);
gulp.task('lint', ['lintCore', 'lintTests'], () => 0);
<commit_msg>Fixing repo URL in gulpfile<commit_after>'use strict';
const gulp = require('gulp'),
    gulpJsdoc2md = require('gulp-jsdoc-to-markdown'),
    rename = require('gulp-rename'),
    istanbul = require('gulp-istanbul'),
    istanbulHarmony = require('istanbul-harmony'),
    mocha = require('gulp-mocha'),
    eslint = require('gulp-eslint'),
    git = require('gulp-git');

const files = ['*.js', '!./gulpfile.js', '!node_modules/**', '!test/**'],
    docs = ['README.md', 'docs/**/*.md'],
    tests = ['test/**/*.js'];

const JobNumber = process.env.TRAVIS_JOB_NUMBER,
    runDocs = !JobNumber || /[.]1$/.test(JobNumber);

/**
 * Pull git branch locally (solves detached head issue in CI)
 */
gulp.task('gitBranch', (done) => {
    let complete = false;
    const branch = process.env.TRAVIS_BRANCH;
    // Abort(successfully) early if not running in CI
    if (!(JobNumber && runDocs && branch)) {
        return done();
    }
    git.checkout(branch, () => {
        // Make sure we have full log history.
        git.pull('origin', branch, {}, () => {
            if (!complete) {
                done();
            }
            complete = true;
        });
    });
});

/**
 * Generate API documentation for all js files, place markup in the correct folder for readthedocs.org
 */
gulp.task('docs', ['gitBranch'], (done) => {
    // Abort(successfully) early if running in CI and not job #1
    if (!runDocs) {
        return done();
    }
    gulp.src(files)
        .pipe(gulpJsdoc2md({}))
        .on('error', done)
        .pipe(rename((path) => {
            path.extname = '.md';
        }))
        .pipe(gulp.dest('docs/api'))
        .on('finish', done);
});

/**
 * Run all js files through eslint and report status.
 */
gulp.task('lintCore', () => {
    return gulp.src(files)
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Run all tests through eslint and report status.
 */
gulp.task('lintTests', () => {
    return gulp.src(tests)
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Set git username/email to CI user
 */
gulp.task('gitConfig', (done) => {
    // Abort(successfully) early if not running in CI
    if (!JobNumber) {
        return done();
    }
    git.exec({
        args: 'config user.name "Travis-CI"'
    }, () => {
        git.exec({
            args: 'config user.email "Travis-CI@servercooties.com"'
        }, () => {
            done();
        });
    });
});

/**
 * Commit generated documentation to be picked up by readthedocs.org
 *
 * Add CI tag to commit to prevent CI jobs from being created by checking in docs
 */
gulp.task('commitDocs', ['gitConfig'], (done) => {
    gulp.src(docs)
        .pipe(git.add())
        .pipe(git.commit('Automatically push updated documentation [ci skip]'))
        .on('error', () => 0)
        .on('finish', done);
});

/**
 * Commit and push docs to github to be picked up by readthedocs.org
 */
gulp.task('pushDocs', ['gitConfig', 'commitDocs'], (done) => {
    //Abort(successfully) early if running in CI and not job #1
    if (!runDocs) {
        return done();
    }
    git.addRemote('github', 'https://github.com/RaceProUK/SockBot-Markov.git', (e) => {
        if (e) {
            done();
        } else {
            git.push('github', 'HEAD', {
                args: ['-q']
            }, () => {
                done();
            });
        }
    });
});

/**
 * Run code coverage instrumented tests
 */
gulp.task('test', ['lintCore', 'lintTests'], (done) => {
    gulp.src(files)
        // Instrument code files with istanbulHarmony
        .pipe(istanbul({
            instrumenter: istanbulHarmony.Instrumenter,
            includeUntested: true
        }))
        // hook require function for complete code coverage
        .pipe(istanbul.hookRequire())
        .on('finish', () => {
            // Run all tests
            gulp.src(tests)
                .pipe(mocha({
                    reporter: 'dot'
                }))
                .on('error', done)
                // Write code coverage reports
                .pipe(istanbul.writeReports())
                .on('finish', done);
        });
});

// Meta tasks
gulp.task('buildDocs', ['docs'], () => 0);
gulp.task('preBuild', ['buildDocs'], () => 0);
gulp.task('postBuild', ['pushDocs'], () => 0);
gulp.task('default', ['lint'], () => 0);
gulp.task('lint', ['lintCore', 'lintTests'], () => 0);
<|endoftext|>


<commit_before>'use strict';

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

var lint = ['index.js', 'lib/*.js'];

gulp.task('coverage', function () {
  return gulp.src(lint)
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['coverage'], function () {
  return gulp.src('test/*.js')
    .pipe(mocha())
    .pipe(istanbul.writeReports())
    .pipe(istanbul.writeReports({
      reporters: [ 'text' ],
      reportOpts: {dir: 'coverage', file: 'summary.txt'}
    }))
});

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

gulp.task('default', ['lint', 'test']);
<commit_msg>100% test coverage<commit_after>'use strict';

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

var lint = ['index.js', 'utils.js', 'lib/*.js'];

gulp.task('coverage', function () {
  return gulp.src(lint)
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
});

gulp.task('test', ['coverage'], function () {
  return gulp.src('test/*.js')
    .pipe(mocha())
    .pipe(istanbul.writeReports())
    .pipe(istanbul.writeReports({
      reporters: [ 'text' ],
      reportOpts: {dir: 'coverage', file: 'summary.txt'}
    }))
});

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

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


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var header = require('gulp-header');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var pkg = require('./package.json');

// Set the banner content
var banner = ['/*!\n',
    ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
    ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
    ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n',
    ' */\n',
    ''
].join('');

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/agency.less')
        .pipe(less())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
    return gulp.src('css/agency.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Minify JS
gulp.task('minify-js', function() {
    return gulp.src('js/agency.js')
        .pipe(uglify())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('js'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function() {
    gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
        .pipe(gulp.dest('vendor/bootstrap'))

    gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest('vendor/jquery'))

    gulp.src([
            'node_modules/font-awesome/**',
            '!node_modules/font-awesome/**/*.map',
            '!node_modules/font-awesome/.npmignore',
            '!node_modules/font-awesome/*.txt',
            '!node_modules/font-awesome/*.md',
            '!node_modules/font-awesome/*.json'
        ])
        .pipe(gulp.dest('vendor/font-awesome'))
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: ''
        },
    })
})

// Watch Task that compiles LESS and watches for HTML or JS changes and reloads with browserSync
gulp.task('watch', ['browserSync', 'less', 'minify-css', 'minify-js'], function() {
    gulp.watch('less/*.less', ['less']);
    gulp.watch('css/*.css', ['minify-css']);
    gulp.watch('js/*.js', ['minify-js']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('*.html', browserSync.reload);
    gulp.watch('js/**/*.js', browserSync.reload);
});

// Compiles SCSS files from /scss into /css
// NOTE: This theme uses LESS by default. To swtich to SCSS you will need to update this gulpfile by changing the 'less' tasks to run 'sass'!
gulp.task('sass', function() {
    return gulp.src('scss/agency.scss')
        .pipe(sass())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});
<commit_msg>i like 'dev' better than 'watch'<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var header = require('gulp-header');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var pkg = require('./package.json');

// Set the banner content
var banner = ['/*!\n',
    ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
    ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
    ' * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n',
    ' */\n',
    ''
].join('');

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/agency.less')
        .pipe(less())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
    return gulp.src('css/agency.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Minify JS
gulp.task('minify-js', function() {
    return gulp.src('js/agency.js')
        .pipe(uglify())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('js'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function() {
    gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
        .pipe(gulp.dest('vendor/bootstrap'))

    gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest('vendor/jquery'))

    gulp.src([
            'node_modules/font-awesome/**',
            '!node_modules/font-awesome/**/*.map',
            '!node_modules/font-awesome/.npmignore',
            '!node_modules/font-awesome/*.txt',
            '!node_modules/font-awesome/*.md',
            '!node_modules/font-awesome/*.json'
        ])
        .pipe(gulp.dest('vendor/font-awesome'))
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: ''
        },
    })
})

// Dev task with browserSync
gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js'], function() {
    gulp.watch('less/*.less', ['less']);
    gulp.watch('css/*.css', ['minify-css']);
    gulp.watch('js/*.js', ['minify-js']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('*.html', browserSync.reload);
    gulp.watch('js/**/*.js', browserSync.reload);
});

// Compiles SCSS files from /scss into /css
// NOTE: This theme uses LESS by default. To swtich to SCSS you will need to update this gulpfile by changing the 'less' tasks to run 'sass'!
gulp.task('sass', function() {
    return gulp.src('scss/agency.scss')
        .pipe(sass())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});
<|endoftext|>


<commit_before>'use strict';

var SERVER = {
        HOST: '127.0.0.1',
        PORT: 8080
    },
    PATH = {
        BUILD: './',
        SOURCE: './src/'
    };

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    inject = require('gulp-inject'),
    jshint = require('gulp-jshint'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    prochtml = require('gulp-processhtml'),
    requirejs = require('requirejs'),
    rimraf = require('rimraf'),
    runSequence = require('run-sequence'),
    size = require('gulp-size'),
    stylish = require('jshint-stylish'),
    webserver = require('gulp-webserver');

gulp.task('lint', function() {
    return gulp.src(PATH.SOURCE + 'scripts/**/*.js')
        .pipe(jshint({
            // Enforcing options
            "bitwise": true,
            "camelcase": true,
            "curly": true,
            "eqeqeq": true,
            "immed": true,
            "indent": 4,
            "latedef": true,
            "newcap": true,
            "noarg": true,
            "nonbsp": true,
            "quotmark": "single",
            "undef": true,
            "unused": true,
            "strict": true,
            "trailing": true,

            // Relaxing options
            "esnext": true,
            "smarttabs": true,

            // Environments
            "browser": true,
            "devel": true,
            "node": true,

            // Custom globals
            "globals": {
                "CONFIG": true,
                "define": true
            }
        }))
        .pipe(jshint.reporter(stylish));
});

gulp.task('requirejs', ['lint'], function() {
    requirejs.optimize({
        baseUrl: PATH.SOURCE + 'scripts/',
        out: PATH.BUILD + 'scripts/site.min.js',
        mainConfigFile: PATH.SOURCE + 'scripts/main.js',
        include: ['../vendor/requirejs/require.min.js', 'main'],
        insertRequire: ['main'],
        wrap: true,
        optimize: 'uglify2',
        preserveLicenseComments: false
    }, function() {
        return 0;
    }, function(err) {
        console.log(err);
        return 1;
    });
});

gulp.task('styles', function() {
    gulp.src([
            PATH.SOURCE + 'styles/**/*.css',
            PATH.SOURCE + 'vendor/ngDialog/css/ngDialog.min.css',
            PATH.SOURCE + 'vendor/ngDialog/css/ngDialog-theme-default.min.css',
            PATH.SOURCE + 'fonts/**/*.css'
        ])
        .pipe(concat('site.css'))
        .pipe(minifyCSS())
        .pipe(gulp.dest(PATH.BUILD + 'styles/'));
});

gulp.task('images', function() {
    return gulp.src(PATH.SOURCE + 'media/images/**/*')
        .pipe(imagemin())
        .pipe(gulp.dest(PATH.BUILD + 'media/images/'));
});

gulp.task('html', function() {
    gulp.src(PATH.SOURCE + 'index.html')
        .pipe(gulp.dest(PATH.BUILD));

    gulp.src([
            PATH.SOURCE + 'partials/**/*.html',
            '!' + PATH.SOURCE + 'partials/views/projectList.html',
            '!' + PATH.SOURCE + 'partials/views/projectDetail.html',
        ])
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/'));

    gulp.src(PATH.SOURCE + 'partials/views/projectList.html')
        .pipe(prochtml('projectList.html'))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/views/'));

    gulp.src(PATH.SOURCE + 'partials/views/projectDetail.html')
        .pipe(prochtml('projectDetail.html'))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/views/'));
});

gulp.task('copy', function() {
    gulp.src([
            PATH.SOURCE + 'fonts/**/*.eot',
            PATH.SOURCE + 'fonts/**/*.svg',
            PATH.SOURCE + 'fonts/**/*.ttf',
            PATH.SOURCE + 'fonts/**/*.woff'
        ])
        .pipe(gulp.dest(PATH.BUILD + 'fonts/'));
});

gulp.task('concat', function() {
    gulp.src([
            PATH.SOURCE + 'tasks/licence.js',
            PATH.BUILD + 'scripts/site.min.js'
        ])
        .pipe(concat('site.min.js'))
        .pipe(gulp.dest(PATH.BUILD + 'scripts/'));

    gulp.src([
            PATH.SOURCE + 'tasks/licence.css',
            PATH.BUILD + 'styles/site.css'
        ])
        .pipe(concat('site.css'))
        .pipe(gulp.dest(PATH.BUILD + 'styles/'));
});

gulp.task('inject-scripts', ['requirejs'], function() {
    return gulp.src(PATH.BUILD + 'index.html')
        .pipe(inject(gulp.src(PATH.BUILD + 'scripts/site.min.js'), {
            starttag: '<!-- inject:head:js -->',
            transform: function(filePath, file) {
                return '<script>' + file.contents.toString('utf8') + '</script>';
            }
        }))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD));
});

gulp.task('inject-styles', ['styles'], function() {
    return gulp.src(PATH.BUILD + 'index.html')
        .pipe(inject(gulp.src(PATH.BUILD + 'styles/site.css'), {
            starttag: '<!-- inject:head:css -->',
            transform: function(filePath, file) {
                return '<style>' + file.contents.toString('utf8') + '</style>';
            }
        }))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD));
});

gulp.task('clean', function() {
    rimraf.sync(PATH.BUILD + 'index.html', function() {});
    rimraf.sync(PATH.BUILD + 'fonts/', function() {});
    rimraf.sync(PATH.BUILD + 'media/', function() {});
    rimraf.sync(PATH.BUILD + 'partials/', function() {});
    rimraf.sync(PATH.BUILD + 'scripts/', function() {});
    rimraf.sync(PATH.BUILD + 'styles/', function() {});
});

gulp.task('size', function() {
    return gulp.src([
            PATH.BUILD + 'index.html',
            PATH.BUILD + 'fonts/**/*',
            PATH.BUILD + 'media/**/*',
            PATH.BUILD + 'partial/**/*',
            PATH.BUILD + 'scripts/**/*',
            PATH.BUILD + 'styles/**/*',
        ])
        .pipe(size({
            gzip: true,
            title: 'build -->'
        }));
});

gulp.task('webserver-dev', function() {
    gulp.src(PATH.SOURCE)
        .pipe(webserver({
            host: SERVER.HOST,
            port: SERVER.PORT,
            livereload: true
        }));
});

gulp.task('webserver', function() {
    gulp.src(PATH.BUILD)
        .pipe(webserver({
            host: SERVER.HOST,
            port: SERVER.PORT
        }));
});

gulp.task('build', function() {
    runSequence(
        'clean',
        'html',
        'inject-scripts',
        'inject-styles',
        ['copy', 'images'],
        //'concat',
        'size',
        'webserver'
    );
});
<commit_msg>Fixed race condition with inject gulp tasks.<commit_after>'use strict';

var SERVER = {
        HOST: '127.0.0.1',
        PORT: 8080
    },
    PATH = {
        BUILD: './',
        SOURCE: './src/'
    };

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    inject = require('gulp-inject'),
    jshint = require('gulp-jshint'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    prochtml = require('gulp-processhtml'),
    requirejs = require('requirejs'),
    rimraf = require('rimraf'),
    runSequence = require('run-sequence'),
    size = require('gulp-size'),
    stylish = require('jshint-stylish'),
    webserver = require('gulp-webserver');

gulp.task('lint', function() {
    return gulp.src(PATH.SOURCE + 'scripts/**/*.js')
        .pipe(jshint({
            // Enforcing options
            "bitwise": true,
            "camelcase": true,
            "curly": true,
            "eqeqeq": true,
            "immed": true,
            "indent": 4,
            "latedef": true,
            "newcap": true,
            "noarg": true,
            "nonbsp": true,
            "quotmark": "single",
            "undef": true,
            "unused": true,
            "strict": true,
            "trailing": true,

            // Relaxing options
            "esnext": true,
            "smarttabs": true,

            // Environments
            "browser": true,
            "devel": true,
            "node": true,

            // Custom globals
            "globals": {
                "CONFIG": true,
                "define": true
            }
        }))
        .pipe(jshint.reporter(stylish));
});

gulp.task('requirejs', ['lint'], function() {
    requirejs.optimize({
        baseUrl: PATH.SOURCE + 'scripts/',
        out: PATH.BUILD + 'scripts/site.min.js',
        mainConfigFile: PATH.SOURCE + 'scripts/main.js',
        include: ['../vendor/requirejs/require.min.js', 'main'],
        insertRequire: ['main'],
        wrap: true,
        optimize: 'uglify2',
        preserveLicenseComments: false
    }, function() {
        return 0;
    }, function(err) {
        console.log(err);
        return 1;
    });
});

gulp.task('styles', function() {
    return gulp.src([
            PATH.SOURCE + 'styles/**/*.css',
            PATH.SOURCE + 'vendor/ngDialog/css/ngDialog.min.css',
            PATH.SOURCE + 'vendor/ngDialog/css/ngDialog-theme-default.min.css',
            PATH.SOURCE + 'fonts/**/*.css'
        ])
        .pipe(concat('site.min.css'))
        .pipe(minifyCSS())
        .pipe(gulp.dest(PATH.BUILD + 'styles/'));
});

gulp.task('images', function() {
    return gulp.src(PATH.SOURCE + 'media/images/**/*')
        .pipe(imagemin())
        .pipe(gulp.dest(PATH.BUILD + 'media/images/'));
});

gulp.task('html', function() {
    gulp.src(PATH.SOURCE + 'index.html')
        .pipe(gulp.dest(PATH.BUILD));

    gulp.src([
            PATH.SOURCE + 'partials/**/*.html',
            '!' + PATH.SOURCE + 'partials/views/projectList.html',
            '!' + PATH.SOURCE + 'partials/views/projectDetail.html',
        ])
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/'));

    gulp.src(PATH.SOURCE + 'partials/views/projectList.html')
        .pipe(prochtml('projectList.html'))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/views/'));

    gulp.src(PATH.SOURCE + 'partials/views/projectDetail.html')
        .pipe(prochtml('projectDetail.html'))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD + 'partials/views/'));
});

gulp.task('copy', function() {
    gulp.src([
            PATH.SOURCE + 'fonts/**/*.eot',
            PATH.SOURCE + 'fonts/**/*.svg',
            PATH.SOURCE + 'fonts/**/*.ttf',
            PATH.SOURCE + 'fonts/**/*.woff'
        ])
        .pipe(gulp.dest(PATH.BUILD + 'fonts/'));
});

gulp.task('concat', function() {
    gulp.src([
            PATH.SOURCE + 'tasks/licence.js',
            PATH.BUILD + 'scripts/site.min.js'
        ])
        .pipe(concat('site.min.js'))
        .pipe(gulp.dest(PATH.BUILD + 'scripts/'));

    gulp.src([
            PATH.SOURCE + 'tasks/licence.css',
            PATH.BUILD + 'styles/site.min.css'
        ])
        .pipe(concat('site.min.css'))
        .pipe(gulp.dest(PATH.BUILD + 'styles/'));
});

gulp.task('inject-scripts', ['requirejs'], function() {
    return gulp.src(PATH.BUILD + 'index.html')
        .pipe(inject(gulp.src(PATH.BUILD + 'scripts/site.min.js'), {
            starttag: '<!-- inject:head:js -->',
            transform: function(filePath, file) {
                return '<script>' + file.contents.toString('utf8') + '</script>';
            }
        }))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD));
});

gulp.task('inject-styles', ['styles'], function() {
    return gulp.src(PATH.BUILD + 'index.html')
        .pipe(inject(gulp.src(PATH.BUILD + 'styles/site.min.css'), {
            starttag: '<!-- inject:head:css -->',
            transform: function(filePath, file) {
                return '<style>' + file.contents.toString('utf8') + '</style>';
            }
        }))
        //.pipe(minifyHTML())
        .pipe(gulp.dest(PATH.BUILD));
});

gulp.task('clean', function() {
    rimraf.sync(PATH.BUILD + 'index.html', function() {});
    rimraf.sync(PATH.BUILD + 'fonts/', function() {});
    rimraf.sync(PATH.BUILD + 'media/', function() {});
    rimraf.sync(PATH.BUILD + 'partials/', function() {});
    rimraf.sync(PATH.BUILD + 'scripts/', function() {});
    rimraf.sync(PATH.BUILD + 'styles/', function() {});
});

gulp.task('size', function() {
    return gulp.src([
            PATH.BUILD + 'index.html',
            PATH.BUILD + 'fonts/**/*',
            PATH.BUILD + 'media/**/*',
            PATH.BUILD + 'partial/**/*',
            PATH.BUILD + 'scripts/**/*',
            PATH.BUILD + 'styles/**/*',
        ])
        .pipe(size({
            gzip: true,
            title: 'build -->'
        }));
});

gulp.task('webserver-dev', function() {
    gulp.src(PATH.SOURCE)
        .pipe(webserver({
            host: SERVER.HOST,
            port: SERVER.PORT,
            livereload: true
        }));
});

gulp.task('webserver', function() {
    gulp.src(PATH.BUILD)
        .pipe(webserver({
            host: SERVER.HOST,
            port: SERVER.PORT
        }));
});

gulp.task('build', function() {
    runSequence(
        'clean',
        ['html', 'copy', 'images'],
        'concat',
        'inject-scripts',
        'inject-styles',
        'size',
        'webserver'
    );
});
<|endoftext|>


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

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src(['app/images/**/*', '!app/images/inject-svg/*.svg'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.scss',
      'app/styles/**/*.css'
    ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.rubySass({
        style: 'expanded',
        precision: 10
      })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  var svgs = gulp.src(['app/images/inject-svg/*.svg'])
                 .pipe($.svgmin([{cleanupIDs: false }]))
                 .pipe($.svgstore({ prefix: 'inject-icon-', inlineSvg: true }));

  function fileContents (filePath, file) {
    return file.contents.toString('utf8');
  }

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // inject svg icon into html
    .pipe($.inject(svgs, { transform: fileContents }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>disable remove quote of html attributes, 會導致 svg 炸裂<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src(['app/images/**/*', '!app/images/inject-svg/*.svg'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.scss',
      'app/styles/**/*.css'
    ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.rubySass({
        style: 'expanded',
        precision: 10
      })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  var svgs = gulp.src(['app/images/inject-svg/*.svg'])
                 .pipe($.svgmin([{cleanupIDs: false }]))
                 .pipe($.svgstore({ prefix: 'inject-icon-', inlineSvg: true }));

  function fileContents (filePath, file) {
    return file.contents.toString('utf8');
  }

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // inject svg icon into html
    .pipe($.inject(svgs, { transform: fileContents }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({quotes: true})))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist'
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>'use strict';
// generated on 2014-10-10 using generator-gulp-webapp 0.1.0

var source     = require('vinyl-source-stream');
var browserify = require('browserify');
var gulp       = require('gulp');
var del        = require('del');
var exec       = require('child_process').exec;

// load plugins
var $ = require('gulp-load-plugins')();

var path = {
	main      : './ui/js/PolioScape.js',
	components: './ui/js/**/*.{js,html,css,sass,scss}',
	js        : './ui/js/**/*.js',
	sass      : ['./ui/styles/**/{screen,print,ie,non-ie-print}.scss', './ui/js/**/*.{sass,scss}', './bower_components/**/*.min.css'],
	images    : './ui/img/**/*',
	test      : './ui/test/**/*.js',
	output    : './static',
	clean     : ['dist', 'build', 'static/**/*.js', 'static/{css,fonts}'],
	dist      : 'dist',
	zipfile   : 'uf04-frontend.zip'
};

function err(e) {
	$.util.log(e.message);
	exec('say -v Fred "Build failed"');
	this.emit('end');
}

function build(src, dst, opts) {
	var bundleStream = browserify(src, opts).bundle()
		.on('error', err);

	return bundleStream
		.pipe(source(src))
		.pipe($.rename('main.js'))
		.pipe(gulp.dest(dst));
};

gulp.task('styles', function () {
	var filter = $.filter(['**/*', '!non-ie-print.css', '!ie.css', '!print.css', '!font-awesome.min.css']);

	return gulp.src(path.sass)
		.pipe($.rubySass({
			compass: true,
			style: 'expanded',
			precision: 10
		}))
		.on('error', err)
		.pipe($.flatten())
		.pipe(filter)
		.pipe($.concat('screen.css'))
		.pipe(filter.restore())
		.pipe($.autoprefixer('last 1 version'))
		.pipe(gulp.dest(path.output + '/css'))
		.on('end', function () {
			exec('say -v Fred "CSS compiled"');
		});
});

gulp.task('scripts', function () {
	return gulp.src(path.js)
		.pipe($.jshint())
		.pipe($.jshint.reporter(require('jshint-stylish')));
});

gulp.task('browserify', ['scripts'], function () {
	return build(path.main, path.output, {
		debug: true,
		standalone: 'Polio',
		paths: ['./ui/js']
	})
	.on('end', function () {
		exec('say -v Fred "App compiled"');
	});
});

gulp.task('fonts', function () {
	var fonts = $.filter('**/*.{eot,svg,ttf,woff}');

	return $.bowerFiles()
		.pipe($.filter(['**/*.{eot,svg,ttf,woff}']))
		.pipe($.flatten())
		.pipe(gulp.dest(path.output + '/fonts'))
		.pipe($.size());
});

gulp.task('clean', function (cb) {
	del(path.clean, cb);
});

gulp.task('build', ['fonts', 'browserify', 'styles']);
gulp.task('default', ['clean', 'build']);

gulp.task('livereload', function () {
	var server = $.livereload();

	// watch for changes

	gulp.watch(path.output + '/**/*').on('change', function (file) {
		server.changed(file.path);
	});
});

gulp.task('watch', ['browserify', 'styles', 'livereload'], function () {
	gulp.watch('**/*.{scss,sass}', ['styles']);
	gulp.watch(path.components, ['browserify']);
});

gulp.task('test', ['scripts'], function () {
	return gulp.src(path.test).pipe($.mocha());
});

gulp.task('collectstatic', ['build'], function (cb) {
	exec('python manage.py collectstatic --noinput -v 0', function (err) {
		if (err) {
			return cb(err);
		}

		cb();
	});
});

gulp.task('dist-py', function () {
	return gulp.src([
			'**/*.{py,sql,html,sh}',
			'requirements.txt',
			'!sql_backups/**/*',
			'!db.sql',
			'!{node_modules,bower_components}/**/*',
			'!**/prod_settings.py'
		])
		.pipe($.zip('uf04-backend.zip'))
		.pipe($.size({ title: 'Backend'}))
		.pipe(gulp.dest(path.dist))
});

gulp.task('dist-ui', ['collectstatic'], function () {
	var jsFilter  = $.filter('**/main.js');
	var cssFilter = $.filter('**/{print,screen,ie}.css');

	return gulp.src('build/**/*')
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe($.size({ title: 'JavaScript' }))
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe($.size({ title: 'CSS' }))
		.pipe(cssFilter.restore())
		.pipe($.zip(path.zipfile))
		.pipe($.filter('*.zip'))
		.pipe($.size({ title: 'Zip' }))
		.pipe(gulp.dest(path.dist));
});

gulp.task('dist', ['dist-py', 'dist-ui']);
<commit_msg>Fix the default task so that clean is run first<commit_after>'use strict';
// generated on 2014-10-10 using generator-gulp-webapp 0.1.0

var source     = require('vinyl-source-stream');
var browserify = require('browserify');
var gulp       = require('gulp');
var del        = require('del');
var exec       = require('child_process').exec;

// load plugins
var $ = require('gulp-load-plugins')();

var path = {
	main      : './ui/js/PolioScape.js',
	components: './ui/js/**/*.{js,html,css,sass,scss}',
	js        : './ui/js/**/*.js',
	sass      : ['./ui/styles/**/{screen,print,ie,non-ie-print}.scss', './ui/js/**/*.{sass,scss}', './bower_components/**/*.min.css'],
	images    : './ui/img/**/*',
	test      : './ui/test/**/*.js',
	output    : './static',
	clean     : ['dist', 'build', 'static/**/*.js', 'static/{css,fonts}'],
	dist      : 'dist',
	zipfile   : 'uf04-frontend.zip'
};

function err(e) {
	$.util.log(e.message);
	exec('say -v Fred "Build failed"');
	this.emit('end');
}

function build(src, dst, opts) {
	var bundleStream = browserify(src, opts).bundle()
		.on('error', err);

	return bundleStream
		.pipe(source(src))
		.pipe($.rename('main.js'))
		.pipe(gulp.dest(dst));
};

gulp.task('styles', function () {
	var filter = $.filter(['**/*', '!non-ie-print.css', '!ie.css', '!print.css', '!font-awesome.min.css']);

	return gulp.src(path.sass)
		.pipe($.rubySass({
			compass: true,
			style: 'expanded',
			precision: 10
		}))
		.on('error', err)
		.pipe($.flatten())
		.pipe(filter)
		.pipe($.concat('screen.css'))
		.pipe(filter.restore())
		.pipe($.autoprefixer('last 1 version'))
		.pipe(gulp.dest(path.output + '/css'))
		.on('end', function () {
			exec('say -v Fred "CSS compiled"');
		});
});

gulp.task('scripts', function () {
	return gulp.src(path.js)
		.pipe($.jshint())
		.pipe($.jshint.reporter(require('jshint-stylish')));
});

gulp.task('browserify', ['scripts'], function () {
	return build(path.main, path.output, {
		debug: true,
		standalone: 'Polio',
		paths: ['./ui/js']
	})
	.on('end', function () {
		exec('say -v Fred "App compiled"');
	});
});

gulp.task('fonts', function () {
	var fonts = $.filter('**/*.{eot,svg,ttf,woff}');

	return $.bowerFiles()
		.pipe($.filter(['**/*.{eot,svg,ttf,woff}']))
		.pipe($.flatten())
		.pipe(gulp.dest(path.output + '/fonts'))
		.pipe($.size());
});

gulp.task('clean', function (cb) {
	del(path.clean, cb);
});

gulp.task('build', ['fonts', 'browserify', 'styles']);

gulp.task('default', ['clean'], function () {
	return gulp.start('build');
});

gulp.task('livereload', function () {
	var server = $.livereload();

	// watch for changes

	gulp.watch(path.output + '/**/*').on('change', function (file) {
		server.changed(file.path);
	});
});

gulp.task('watch', ['browserify', 'styles', 'livereload'], function () {
	gulp.watch('**/*.{scss,sass}', ['styles']);
	gulp.watch(path.components, ['browserify']);
});

gulp.task('test', ['scripts'], function () {
	return gulp.src(path.test).pipe($.mocha());
});

gulp.task('collectstatic', ['build'], function (cb) {
	exec('python manage.py collectstatic --noinput -v 0', function (err) {
		if (err) {
			return cb(err);
		}

		cb();
	});
});

gulp.task('dist-py', function () {
	return gulp.src([
			'**/*.{py,sql,html,sh}',
			'requirements.txt',
			'!sql_backups/**/*',
			'!db.sql',
			'!{node_modules,bower_components}/**/*',
			'!**/prod_settings.py'
		])
		.pipe($.zip('uf04-backend.zip'))
		.pipe($.size({ title: 'Backend'}))
		.pipe(gulp.dest(path.dist))
});

gulp.task('dist-ui', ['collectstatic'], function () {
	var jsFilter  = $.filter('**/main.js');
	var cssFilter = $.filter('**/{print,screen,ie}.css');

	return gulp.src('build/**/*')
		.pipe(jsFilter)
		.pipe($.uglify())
		.pipe($.size({ title: 'JavaScript' }))
		.pipe(jsFilter.restore())
		.pipe(cssFilter)
		.pipe($.csso())
		.pipe($.size({ title: 'CSS' }))
		.pipe(cssFilter.restore())
		.pipe($.zip(path.zipfile))
		.pipe($.filter('*.zip'))
		.pipe($.size({ title: 'Zip' }))
		.pipe(gulp.dest(path.dist));
});

gulp.task('dist', ['dist-py', 'dist-ui']);
<|endoftext|>


<commit_before>/**
 *
 * Gulp Site
 * A barebones site generator using Gulp
 *
 * MIT License
 *
 */

'use strict';

/**
 * Initialize
 * ========================
 */

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    config = require('./config.json'),
    plugins = require('gulp-load-plugins')({
        camelize: true
    }),
    merge = require('merge-stream'),
    browserSync = require('browser-sync'),
    reload = browserSync.reload;

/**
 * Default Error Handling
 * ========================
 */

var onError = function(err) {
    plugins.notify.onError({
        title:    "Gulp Site Generator",
        subtitle: "Error",
        message:  "<%= error.message %>",
        sound:    "Beep"
    })(err);

    this.emit('end');
};

/**
 * Task: Styles
 * ========================
 */

gulp.task('styles', function () {
    return gulp.src([config.paths.src.scss + '*.scss', '!' + config.paths.src.scss + '_*.scss'])
    .pipe(plugins.plumber({errorHandler: onError}))
    .pipe(plugins.sass())
    .pipe(plugins.autoprefixer(config.autoprefixer))
    .pipe(plugins.bless())
    .pipe(gulp.dest(config.paths.build.css))
    .pipe(reload({stream:true}))
    .pipe(plugins.csso({
        keepSpecialComments: 1
    }))
    .pipe(plugins.rename({
        suffix: '.min'
    }))
    .pipe(gulp.dest(config.paths.build.css))
    .pipe(reload({stream:true}))
    .pipe(plugins.notify({ message: config.notifications.sass }));
});

/**
 * Task: JS Scripts
 * ========================
 * Todo: This only concats alphabetically. May make sense to switch to Browserify.
 */

gulp.task('scripts', function () {
    return gulp.src(config.paths.src.js + '*.js')
    .pipe(plugins.plumber({errorHandler: onError}))
    .pipe(plugins.jshint('.jshintrc'))
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'))
    .pipe(plugins.concat(config.files.jsFinal + '.js'))
    .pipe(gulp.dest(config.paths.build.js))
    .pipe(plugins.rename({
        suffix: '.min'
    }))
    .pipe(plugins.uglify())
    .pipe(gulp.dest(config.paths.build.js))
    .pipe(reload({stream:true, once:true}))
    .pipe(plugins.notify({ message: config.notifications.scripts }));
});

/**
 * Task: Images
 * ========================
 */

gulp.task('images', function () {
    return gulp.src(config.paths.src.img + '**/*')
    .pipe(plugins.imagemin(config.imagemin))
    .pipe(gulp.dest(config.paths.build.img))
    .pipe(reload({stream:true, once:true}))
    .pipe(plugins.notify({ message: config.notifications.images }));
});

/**
 * Task: Reload
 * ========================
 */

gulp.task('reload', function () {
    browserSync.reload();
});

/**
 * Task: Bower Packages
 * ================
 * This is a manual process for components that should be included.
 * However the advantage is Gulp will fetch the latest version on bower update.
 * This function is not included in the default Gulp process.
 * Run 'gulp bower' to use.
 */

gulp.task('bower-packages', function () {

    // Normalize
    gulp.src([config.paths.bower + 'normalize.css/normalize.css'])
    .pipe(plugins.rename('_base_normalize.scss'))
    .pipe(gulp.dest(config.paths.src.scssVendor));

});

/**
 * Task: NPM Components
 * ================
 * This is a manual process for components that should be included.
 * This function is not included in the default Gulp process.
 * Run 'gulp npm-packages' to use.
 */

gulp.task('npm-packages', function () {

	if ( config.includeBourbon === true ) {
	    return merge(

	        // Node Bourbon
	        gulp.src(config.paths.npm + 'node-bourbon/assets/stylesheets/**/*.*', ['clean'])
	            .pipe(gulp.dest(config.paths.src.scssVendor + 'node-bourbon')),

	        // Node Neat
	        gulp.src(config.paths.npm + 'node-neat/assets/stylesheets/**/*.*', ['clean'])
	            .pipe(gulp.dest(config.paths.src.scssVendor + 'node-neat'))
	    );
	} else {
		// TODO: If not included, clean the directories using plugins.del()
	}

});

/**
 * Task: Compiles HTML
 * ========================
 * Compiles HTML files with includes
 */

gulp.task('html', function() {
    gulp.src([config.paths.src.base + '**/*.html', '!' + config.paths.src.base + '**/_*.html'])
    .pipe(plugins.fileInclude({
        prefix: '@@',
        basepath: '@file'
    }))
    .pipe(gulp.dest(config.paths.build.base))
    .pipe(reload({stream:true}))
    .pipe(plugins.notify({ message: config.notifications.markup }));
});

/**
 * Task: Deploy
 * ========================
 * Deployes to Github Pages
 */

gulp.task('deploy', function() {
    gulp.src(config.paths.build.base + '**/*')
    .pipe(plugins.ghPages())
    .pipe(plugins.notify({ message: config.notifications.deployed }));
});

/**
 * Task: Watch
 * ========================
 * Initiates BrowserSync and watches files for any tasks.
 */

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

    browserSync.init({
        server: {
            baseDir: config.devServer.path
        },
        open: false,
        port: config.devServer.port
    });
    gulp.watch(config.paths.src.scss + '**/*.scss', ['styles']);
    gulp.watch(config.paths.src.js + '**/*.js', ['scripts']);
    gulp.watch([config.paths.src.img + '**/*', config.paths.build.img + '**/*'], ['images']);
    gulp.watch(config.paths.src.base + '**/*.html', ['html']);
});

/**
 * Task: Default
 * ========================
 */

gulp.task('default', ['html', 'styles', 'scripts', 'images', 'watch']);

/**
 * Task: Test
 * ========================
 * Used for testing builds without watch.
 */

gulp.task('test', ['html', 'styles', 'scripts', 'images']);<commit_msg>Indent to adhere to structure<commit_after>/**
 *
 * Gulp Site
 * A barebones site generator using Gulp
 *
 * MIT License
 *
 * + Table of Contents
 *     - Initialize
 *     - Funcitons
 *     + Tasks
 *         - Styles
 *         - Scripts
 *         - Images
 *         - Reload
 *         - Bower Packages
 *         - NPM Packages
 *         - Compile HTML
 *         - Deploy
 *         - Watch
 *         - Default
 *         - Test
 */

'use strict';

/**
 * ========================
 *     INITIALIZE
 * ========================
 */

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    config = require('./config.json'),
    plugins = require('gulp-load-plugins')({
        camelize: true
    }),
    merge = require('merge-stream'),
    browserSync = require('browser-sync'),
    reload = browserSync.reload;

/**
 * ========================
 *     FUNCTIONS
 * ========================
 */

    /**
     * Default Error Handling
     * ========================
     */

    var onError = function(err) {
        plugins.notify.onError({
            title:    "Gulp Site Generator",
            subtitle: "Error",
            message:  "<%= error.message %>",
            sound:    "Beep"
        })(err);

        this.emit('end');
    };

/**
 * ========================
 *     TASKS
 * ========================
 */

    /**
     * Task: Styles
     * ========================
     */

    gulp.task('styles', function () {
        return gulp.src([config.paths.src.scss + '*.scss', '!' + config.paths.src.scss + '_*.scss'])
        .pipe(plugins.plumber({errorHandler: onError}))
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer(config.autoprefixer))
        .pipe(plugins.bless())
        .pipe(gulp.dest(config.paths.build.css))
        .pipe(reload({stream:true}))
        .pipe(plugins.csso({
            keepSpecialComments: 1
        }))
        .pipe(plugins.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(config.paths.build.css))
        .pipe(reload({stream:true}))
        .pipe(plugins.notify({ message: config.notifications.sass }));
    });

    /**
     * Task: JS Scripts
     * ========================
     * Todo: This only concats alphabetically. May make sense to switch to Browserify.
     */

    gulp.task('scripts', function () {
        return gulp.src(config.paths.src.js + '*.js')
        .pipe(plugins.plumber({errorHandler: onError}))
        .pipe(plugins.jshint('.jshintrc'))
        .pipe(plugins.jshint.reporter('jshint-stylish'))
        .pipe(plugins.jshint.reporter('fail'))
        .pipe(plugins.concat(config.files.jsFinal + '.js'))
        .pipe(gulp.dest(config.paths.build.js))
        .pipe(plugins.rename({
            suffix: '.min'
        }))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(config.paths.build.js))
        .pipe(reload({stream:true, once:true}))
        .pipe(plugins.notify({ message: config.notifications.scripts }));
    });

    /**
     * Task: Images
     * ========================
     */

    gulp.task('images', function () {
        return gulp.src(config.paths.src.img + '**/*')
        .pipe(plugins.imagemin(config.imagemin))
        .pipe(gulp.dest(config.paths.build.img))
        .pipe(reload({stream:true, once:true}))
        .pipe(plugins.notify({ message: config.notifications.images }));
    });

    /**
     * Task: Reload
     * ========================
     */

    gulp.task('reload', function () {
        browserSync.reload();
    });

    /**
     * Task: Bower Packages
     * ================
     * This is a manual process for components that should be included.
     * However the advantage is Gulp will fetch the latest version on bower update.
     * This function is not included in the default Gulp process.
     * Run 'gulp bower' to use.
     */

    gulp.task('bower-packages', function () {

        // Normalize
        gulp.src([config.paths.bower + 'normalize.css/normalize.css'])
        .pipe(plugins.rename('_base_normalize.scss'))
        .pipe(gulp.dest(config.paths.src.scssVendor));

    });

    /**
     * Task: NPM Components
     * ================
     * This is a manual process for components that should be included.
     * This function is not included in the default Gulp process.
     * Run 'gulp npm-packages' to use.
     */

    gulp.task('npm-packages', function () {

    	if ( config.includeBourbon === true ) {
    	    return merge(

    	        // Node Bourbon
    	        gulp.src(config.paths.npm + 'node-bourbon/assets/stylesheets/**/*.*', ['clean'])
    	            .pipe(gulp.dest(config.paths.src.scssVendor + 'node-bourbon')),

    	        // Node Neat
    	        gulp.src(config.paths.npm + 'node-neat/assets/stylesheets/**/*.*', ['clean'])
    	            .pipe(gulp.dest(config.paths.src.scssVendor + 'node-neat'))
    	    );
    	} else {
    		// TODO: If not included, clean the directories using plugins.del()
    	}

    });

    /**
     * Task: Compiles HTML
     * ========================
     * Compiles HTML files with includes
     */

    gulp.task('html', function() {
        gulp.src([config.paths.src.base + '**/*.html', '!' + config.paths.src.base + '**/_*.html'])
        .pipe(plugins.fileInclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest(config.paths.build.base))
        .pipe(reload({stream:true}))
        .pipe(plugins.notify({ message: config.notifications.markup }));
    });

    /**
     * Task: Deploy
     * ========================
     * Deployes to Github Pages
     */

    gulp.task('deploy', function() {
        gulp.src(config.paths.build.base + '**/*')
        .pipe(plugins.ghPages())
        .pipe(plugins.notify({ message: config.notifications.deployed }));
    });

    /**
     * Task: Watch
     * ========================
     * Initiates BrowserSync and watches files for any tasks.
     */

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

        browserSync.init({
            server: {
                baseDir: config.devServer.path
            },
            open: false,
            port: config.devServer.port
        });
        gulp.watch(config.paths.src.scss + '**/*.scss', ['styles']);
        gulp.watch(config.paths.src.js + '**/*.js', ['scripts']);
        gulp.watch([config.paths.src.img + '**/*', config.paths.build.img + '**/*'], ['images']);
        gulp.watch(config.paths.src.base + '**/*.html', ['html']);
    });

    /**
     * Task: Default
     * ========================
     */

    gulp.task('default', ['html', 'styles', 'scripts', 'images', 'watch']);

    /**
     * Task: Test
     * ========================
     * Used for testing builds without watch.
     */

    gulp.task('test', ['html', 'styles', 'scripts', 'images']);<|endoftext|>