<commit_before>/* Dev-Dependencies */
var
  gulp = require('gulp'),
  sourcemaps = require('gulp-sourcemaps'),
  babel = require('gulp-babel'),
  mocha = require('gulp-spawn-mocha'),
  jshint = require('gulp-jshint'),
  beautify = require('gulp-jsbeautify'),
  shell = require('gulp-shell'),
  ghPages = require('gulp-gh-pages'),
  rimraf = require('rimraf'),
  config = require('./config'),
  semver = require('semver'),
  version = require('node-version').long,
  isHarmony = !semver.lt(version.toString(), '0.11.0'),
  changelog = require('gulp-changelog');

/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
 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.
 */

/**
 * node-harmonize (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/node-harmonize for details
 */
var child_process = require("child_process");

(function harmony() {
    if (typeof Proxy == 'undefined') { // We take direct proxies as our marker
        if (!isHarmony) return;

        var features = ['--harmony', '--harmony-proxies'];
        var node = child_process.spawn(process.argv[0], features.concat(process.argv.slice(1)), { stdio: 'inherit' });
        console.log('Enabled Harmony', node);
        node.on("close", function(code) {
            process.exit(code);
        });

        // Interrupt process flow in the parent
        process.once("uncaughtException", function(e) {});
        throw "harmony";
    }
})();

/** Backs up the files in case of emergency! */
gulp.task('backup', function () {
  return gulp
    .src('lib/**/**/**.js')
    .pipe(gulp.dest('./.backup'));
});

gulp.task('recover', function () {
  return gulp
    .src('./.backup/**/**/*.js')
    .pipe(gulp.dest('lib/'));
});

/* Formats the files */
gulp.task('beautify', ['backup'], function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(beautify(config.beautify))
    .pipe(gulp.dest('./lib'));
});

/*
 * Clean the docs themes folder
 */
gulp.task('clean-docs', ['gh-pages'], function (cb) {
  rimraf('./docs/themes', cb);
});

/*
 * Create the gh-pages branch - wont push automatically
 */
gulp.task('gh-pages', ['doc'], function () {
  return gulp.src('./docs/**/*')
    .pipe(ghPages());
});

/* Checks the coding style and builds from ES6 to ES5*/
gulp.task('lib', ['beautify'], function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(jshint(config.jshint))
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('./source maps/'))
    .pipe(gulp.dest('./'));
});

/* Watches for changes and applies the build task*/
gulp.task('watch', function () {
  return gulp.watch('./lib/**/**/*.js', ['build']);
});

/* Runs tests */

gulp.task('test', ['lib'], function (cb) {
  if (isHarmony)
    return gulp.src('./tests/**/*.js')
    .pipe(mocha());
  else return gulp.src([
    './tests/express/index.js',
    './tests/hapi/index.js'
  ]).pipe(mocha({
    bin:(function(){
      var bin ='./node_modules/mocha/bin/mocha';
       var flag = ' --harmony';
       return bin + flag;
    })()
  }));
});

gulp.task('changelog', function (cb) {
  changelog(require('./package.json')).then(function (stream) {
    stream.pipe(gulp.dest('./')).on('end', cb);
  });
});

/*
 * Runs the doxx command and builds the docs
* Install other themes here, generate docs for each.
*/
gulp.task('doc', ['build'], shell.task([
  (function(){
    var doc = 'node_modules/mr-doc/bin/mr-doc',
        cmd = {
          source: ' -s lib/',
          output: ' -o docs/',
          name:' -n "gengo.js/accept"',
          theme:' -t cayman'
        };
    return doc + cmd.source + cmd.output + cmd.name + cmd.theme;
  })()
]));

gulp.task('default', ['backup', 'beautify', 'lib', 'watch']);

gulp.task('build', ['backup', 'beautify', 'lib', 'test']);

gulp.task('docs', ['build', 'doc', 'gh-pages', 'clean-docs']);<commit_msg>Test Update<commit_after>/* Dev-Dependencies */
var
  gulp = require('gulp'),
  sourcemaps = require('gulp-sourcemaps'),
  babel = require('gulp-babel'),
  mocha = require('gulp-spawn-mocha'),
  jshint = require('gulp-jshint'),
  beautify = require('gulp-jsbeautify'),
  shell = require('gulp-shell'),
  ghPages = require('gulp-gh-pages'),
  rimraf = require('rimraf'),
  config = require('./config'),
  semver = require('semver'),
  version = require('node-version').long,
  isHarmony = !semver.lt(version.toString(), '0.11.0'),
  changelog = require('gulp-changelog');

/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
 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.
 */

/**
 * node-harmonize (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/node-harmonize for details
 */
var child_process = require("child_process");

(function harmony() {
    if (typeof Proxy == 'undefined') { // We take direct proxies as our marker
        if (!isHarmony) return;

        var features = ['--harmony', '--harmony-proxies'];
        var node = child_process.spawn(process.argv[0], features.concat(process.argv.slice(1)), { stdio: 'inherit' });
        console.log('Enabled Harmony', node);
        node.on("close", function(code) {
            process.exit(code);
        });

        // Interrupt process flow in the parent
        process.once("uncaughtException", function(e) {});
        throw "harmony";
    }
})();

/** Backs up the files in case of emergency! */
gulp.task('backup', function () {
  return gulp
    .src('lib/**/**/**.js')
    .pipe(gulp.dest('./.backup'));
});

gulp.task('recover', function () {
  return gulp
    .src('./.backup/**/**/*.js')
    .pipe(gulp.dest('lib/'));
});

/* Formats the files */
gulp.task('beautify', ['backup'], function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(beautify(config.beautify))
    .pipe(gulp.dest('./lib'));
});

/*
 * Clean the docs themes folder
 */
gulp.task('clean-docs', ['gh-pages'], function (cb) {
  rimraf('./docs/themes', cb);
});

/*
 * Create the gh-pages branch - wont push automatically
 */
gulp.task('gh-pages', ['doc'], function () {
  return gulp.src('./docs/**/*')
    .pipe(ghPages());
});

/* Checks the coding style and builds from ES6 to ES5*/
gulp.task('lib', ['beautify'], function () {
  return gulp.src('./lib/**/**/*.js')
    .pipe(jshint(config.jshint))
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('./source maps/'))
    .pipe(gulp.dest('./'));
});

/* Watches for changes and applies the build task*/
gulp.task('watch', function () {
  return gulp.watch('./lib/**/**/*.js', ['build']);
});

/* Runs tests */

gulp.task('test', ['lib'], function (cb) {
  if (isHarmony)
    return gulp.src('./tests/**/*.js')
    .pipe(mocha());
  else return gulp.src([
    './tests/express/index.js',
    './tests/hapi/index.js'
  ]).pipe(mocha({
    harmony:'harmony'
  }));
});

gulp.task('changelog', function (cb) {
  changelog(require('./package.json')).then(function (stream) {
    stream.pipe(gulp.dest('./')).on('end', cb);
  });
});

/*
 * Runs the doxx command and builds the docs
* Install other themes here, generate docs for each.
*/
gulp.task('doc', ['build'], shell.task([
  (function(){
    var doc = 'node_modules/mr-doc/bin/mr-doc',
        cmd = {
          source: ' -s lib/',
          output: ' -o docs/',
          name:' -n "gengo.js/accept"',
          theme:' -t cayman'
        };
    return doc + cmd.source + cmd.output + cmd.name + cmd.theme;
  })()
]));

gulp.task('default', ['backup', 'beautify', 'lib', 'watch']);

gulp.task('build', ['backup', 'beautify', 'lib', 'test']);

gulp.task('docs', ['build', 'doc', 'gh-pages', 'clean-docs']);<|endoftext|>


<commit_before>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
var gulp = require('gulp'),
  path = require('path'),
  browserSync = require('browser-sync').create(),
  sass = require('gulp-sass'),
  argv = require('minimist')(process.argv.slice(2));

/******************************************************
 * COPY TASKS - stream assets from source to destination
******************************************************/
// JS copy
gulp.task('pl-copy:js', function(){
  return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} )
    .pipe(gulp.dest(path.resolve(paths().public.js)));
});

// Images copy
gulp.task('pl-copy:img', function(){
  return gulp.src('**/*.*',{cwd: path.resolve(paths().source.images)} )
    .pipe(gulp.dest(path.resolve(paths().public.images)));
});

// Favicon copy
gulp.task('pl-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: path.resolve(paths().source.root)} )
    .pipe(gulp.dest(path.resolve(paths().public.root)));
});

// Fonts copy
gulp.task('pl-copy:font', function(){
  return gulp.src('*', {cwd: path.resolve(paths().source.fonts)})
    .pipe(gulp.dest(path.resolve(paths().public.fonts)))
    .pipe(gulp.dest('./../fonts/'));
});

// SASS Compilation
gulp.task('pl-sass', function(){
  return gulp.src(path.resolve(paths().source.css, '**/*.scss'))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(path.resolve(paths().source.css)));
});

gulp.task('copysass', function () {
  return gulp.src('source/css/*.scss') // Get source files with gulp.src
    .pipe(gulp.dest('./../_sass/')) // Outputs the file in the destination folder
});

gulp.task('copyvariables', function () {
  return gulp.src('source/css/abstracts/*.scss') // Get source files with gulp.src
    .pipe(gulp.dest('./../_sass/abstracts/')) // Outputs the file in the destination folder
});

// CSS Copy
gulp.task('pl-copy:css', function(){
  return gulp.src(path.resolve(paths().source.css, '*.css'))
    .pipe(gulp.dest(path.resolve(paths().public.css)))
    .pipe(browserSync.stream());
});

// Styleguide Copy everything but css
gulp.task('pl-copy:styleguide', function(){
  return gulp.src(path.resolve(paths().source.styleguide, '**/!(*.css)'))
    .pipe(gulp.dest(path.resolve(paths().public.root)))
    .pipe(browserSync.stream());
});

// Styleguide Copy and flatten css
gulp.task('pl-copy:styleguide-css', function(){
  return gulp.src(path.resolve(paths().source.styleguide, '**/*.css'))
    .pipe(gulp.dest(function(file){
      //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
      file.path = path.join(file.base, path.basename(file.path));
      return path.resolve(path.join(paths().public.styleguide, 'css'));
    }))
    .pipe(browserSync.stream());
});

/******************************************************
 * PATTERN LAB CONFIGURATION - API with core library
******************************************************/
//read all paths from our namespaced config file
var config = require('./patternlab-config.json'),
  patternlab = require('patternlab-node')(config);

function paths() {
  return config.paths;
}

function getConfiguredCleanOption() {
  return config.cleanPublic;
}

function build(done) {
  patternlab.build(done, getConfiguredCleanOption());
}

gulp.task('pl-assets', gulp.series(
  gulp.parallel(
    'pl-copy:js',
    'pl-copy:img',
    'pl-copy:favicon',
    'pl-copy:font',
    gulp.series('pl-sass', 'pl-copy:css', function(done){done();}),
    'pl-copy:styleguide',
    'pl-copy:styleguide-css'
  ),
  function(done){
    done();
  })
);

gulp.task('patternlab:version', function (done) {
  patternlab.version();
  done();
});

gulp.task('patternlab:help', function (done) {
  patternlab.help();
  done();
});

gulp.task('patternlab:patternsonly', function (done) {
  patternlab.patternsonly(done, getConfiguredCleanOption());
});

gulp.task('patternlab:liststarterkits', function (done) {
  patternlab.liststarterkits();
  done();
});

gulp.task('patternlab:loadstarterkit', function (done) {
  patternlab.loadstarterkit(argv.kit, argv.clean);
  done();
});

gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){
  done();
}));

/******************************************************
 * SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
  var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
  return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
  return getSupportedTemplateExtensions().map(function (dotExtension) {
    return path.resolve(paths().source.patterns, '**/*' + dotExtension);
  });
}

function reload() {
  browserSync.reload();
}

function watch() {
  gulp.watch(path.resolve(paths().source.css, '**/*.scss')).on('change', gulp.series('pl-sass'));
  gulp.watch(path.resolve(paths().source.css, '**/*.css')).on('change', gulp.series('pl-copy:css', reload));
  gulp.watch(path.resolve(paths().source.styleguide, '**/*.*')).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reload));

  var patternWatches = [
    path.resolve(paths().source.patterns, '**/*.json'),
    path.resolve(paths().source.patterns, '**/*.md'),
    path.resolve(paths().source.data, '*.json'),
    path.resolve(paths().source.fonts + '/*'),
    path.resolve(paths().source.images + '/*'),
    path.resolve(paths().source.meta, '*'),
    path.resolve(paths().source.annotations + '/*')
  ].concat(getTemplateWatches());

  gulp.watch(patternWatches).on('change', gulp.series(build, reload));
}

gulp.task('patternlab:connect', gulp.series(function(done) {
  browserSync.init({
    server: {
      baseDir: path.resolve(paths().public.root)
    },
    snippetOptions: {
      // Ignore all HTML files within the templates folder
      blacklist: ['/index.html', '/', '/?*']
    },
    notify: {
      styles: [
        'display: none',
        'padding: 15px',
        'font-family: sans-serif',
        'position: fixed',
        'font-size: 1em',
        'z-index: 9999',
        'bottom: 0px',
        'right: 0px',
        'border-top-left-radius: 5px',
        'background-color: #1B2032',
        'opacity: 0.4',
        'margin: 0',
        'color: white',
        'text-align: center'
      ]
    }
  }, function(){
    console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
  });
  done();
}));

/******************************************************
 * COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));
<commit_msg>Clean up gulpfile<commit_after>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
var gulp = require('gulp'),
  path = require('path'),
  browserSync = require('browser-sync').create(),
  sass = require('gulp-sass'),
  argv = require('minimist')(process.argv.slice(2));

/******************************************************
 * COPY TASKS - stream assets from source to destination
******************************************************/
// JS copy
gulp.task('pl-copy:js', function(){
  return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} )
    .pipe(gulp.dest(path.resolve(paths().public.js)));
});

// Images copy
gulp.task('pl-copy:img', function(){
  return gulp.src('**/*.*',{cwd: path.resolve(paths().source.images)} )
    .pipe(gulp.dest(path.resolve(paths().public.images)));
});

// Favicon copy
gulp.task('pl-copy:favicon', function(){
  return gulp.src('favicon.ico', {cwd: path.resolve(paths().source.root)} )
    .pipe(gulp.dest(path.resolve(paths().public.root)));
});

// Fonts copy
gulp.task('pl-copy:font', function(){
  return gulp.src('*', {cwd: path.resolve(paths().source.fonts)})
    .pipe(gulp.dest(path.resolve(paths().public.fonts)))
    .pipe(gulp.dest('./../fonts/'));
});

// SASS Compilation
gulp.task('pl-sass', function(){
  return gulp.src(path.resolve(paths().source.css, '**/*.scss'))
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(path.resolve(paths().source.css)));
});

gulp.task('copysass', function () {
  return gulp.src('source/css/*.scss') // Get source files with gulp.src
    .pipe(gulp.dest('./../_sass/')) // Outputs the file in the destination folder
});

gulp.task('copyvariables', function () {
  return gulp.src('source/css/abstracts/*.scss') // Get source files with gulp.src
    .pipe(gulp.dest('./../_sass/abstracts/')) // Outputs the file in the destination folder
});

// CSS Copy
gulp.task('pl-copy:css', function(){
  return gulp.src(path.resolve(paths().source.css, '*.css'))
    .pipe(gulp.dest(path.resolve(paths().public.css)))
    .pipe(browserSync.stream());
});

// Styleguide Copy everything but css
gulp.task('pl-copy:styleguide', function(){
  return gulp.src(path.resolve(paths().source.styleguide, '**/!(*.css)'))
    .pipe(gulp.dest(path.resolve(paths().public.root)))
    .pipe(browserSync.stream());
});

// Styleguide Copy and flatten css
gulp.task('pl-copy:styleguide-css', function(){
  return gulp.src(path.resolve(paths().source.styleguide, '**/*.css'))
    .pipe(gulp.dest(function(file){
      //flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
      file.path = path.join(file.base, path.basename(file.path));
      return path.resolve(path.join(paths().public.styleguide, 'css'));
    }))
    .pipe(browserSync.stream());
});

/******************************************************
 * PATTERN LAB CONFIGURATION - API with core library
******************************************************/
//read all paths from our namespaced config file
var config = require('./patternlab-config.json'),
  patternlab = require('patternlab-node')(config);

function paths() {
  return config.paths;
}

function getConfiguredCleanOption() {
  return config.cleanPublic;
}

function build(done) {
  patternlab.build(done, getConfiguredCleanOption());
}

gulp.task('pl-assets', gulp.series(
  gulp.parallel(
    'pl-copy:js',
    'pl-copy:img',
    'pl-copy:favicon',
    'pl-copy:font',
    gulp.series('pl-sass', 'pl-copy:css', function(done){done();}),
    'pl-copy:styleguide',
    'pl-copy:styleguide-css'
  ),
  function(done){
    done();
  })
);

gulp.task('patternlab:version', function (done) {
  patternlab.version();
  done();
});

gulp.task('patternlab:help', function (done) {
  patternlab.help();
  done();
});

gulp.task('patternlab:patternsonly', function (done) {
  patternlab.patternsonly(done, getConfiguredCleanOption());
});

gulp.task('patternlab:liststarterkits', function (done) {
  patternlab.liststarterkits();
  done();
});

gulp.task('patternlab:loadstarterkit', function (done) {
  patternlab.loadstarterkit(argv.kit, argv.clean);
  done();
});

gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){
  done();
}));

/******************************************************
 * SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
  var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
  return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
  return getSupportedTemplateExtensions().map(function (dotExtension) {
    return path.resolve(paths().source.patterns, '**/*' + dotExtension);
  });
}

function reload() {
  browserSync.reload();
}

function watch() {
  gulp.watch(path.resolve(paths().source.css, '**/*.scss')).on('change', gulp.series('pl-sass'));
  gulp.watch(path.resolve(paths().source.css, '**/*.css')).on('change', gulp.series('pl-copy:css', reload));
  gulp.watch(path.resolve(paths().source.styleguide, '**/*.*')).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reload));

  var patternWatches = [
    path.resolve(paths().source.patterns, '**/*.json'),
    path.resolve(paths().source.patterns, '**/*.md'),
    path.resolve(paths().source.data, '*.json'),
    path.resolve(paths().source.fonts + '/*'),
    path.resolve(paths().source.images + '/*'),
    path.resolve(paths().source.meta, '*'),
    path.resolve(paths().source.annotations + '/*')
  ].concat(getTemplateWatches());

  gulp.watch(patternWatches).on('change', gulp.series(build, reload));
}

gulp.task('patternlab:connect', gulp.series(function(done) {
  browserSync.init({
    server: {
      baseDir: path.resolve(paths().public.root)
    },
    snippetOptions: {
      // Ignore all HTML files within the templates folder
      blacklist: ['/index.html', '/', '/?*']
    },
    notify: {
      styles: [
        'display: none',
        'padding: 15px',
        'font-family: sans-serif',
        'position: fixed',
        'font-size: 1em',
        'z-index: 9999',
        'bottom: 0px',
        'right: 0px',
        'border-top-left-radius: 5px',
        'background-color: #1B2032',
        'opacity: 0.4',
        'margin: 0',
        'color: white',
        'text-align: center'
      ]
    }
  }, function(){
    console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
  });
  done();
}));

/******************************************************
 * COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
$.ngAnnotate = require('gulp-ng-annotate');
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var pagespeed = require('psi');
var fs = require('graceful-fs');
var packageJSON = require("./package.json");
var modRewrite = require('connect-modrewrite');
var mkdirp = require("mkdirp");

var habitat = require("habitat");

habitat.load();

var env = new habitat("gdc", {
  api: "https://portal.gdc.nci.nih.gov",
  base: "/"
});

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

var production = process.env.NODE_ENV === "production";
$.util.log('Environment', $.util.colors.blue(production ? 'Production' : 'Development'));

// <paths>
var paths = {
  "src": "./src",
  "dev": "./dist",
  "stage": "./dist",
  "bower": "./bower_components/**/*.{js,css,map,eot,svg,ttf,woff,woff2}",
  js: {},
  html: {}
};
paths.ddest = production ? paths.stage : paths.dev;
paths.js.src = paths.src + "/app/**/*";
paths.js.dest = paths.ddest + "/js";
paths.vendor = paths.ddest + "/libs";
paths.html.src = paths.src + "/index.html";
paths.html.dest = paths.dest + "/index.html";
// </paths>

gulp.task('logs', function () {
  require('conventional-changelog')({
    repository: packageJSON.repository,
    version: packageJSON.version,
    issueLink: function (id) {
      return '[OICR-' + id + '](https://jira.opensciencedatacloud.org/browse/OICR-' + id + ')'
    }
  }, function (err, log) {
    fs.writeFile('CHANGELOG.md', log);
  });
});

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

gulp.task('i18n:pot', function () {
  return gulp.src(['app/scripts/**/*.html', 'app/scripts/**/*.js'])
      .pipe($.angularGettext.extract('template.pot'))
      .pipe(gulp.dest('translations/'));
});

gulp.task('i18n:translations', ['i18n:pot'], function () {
  return gulp.src('translations/**/*.po')
      .pipe($.angularGettext.compile({
        format: 'javascript',
        defaultLanguage: 'en'
      }))
      .pipe(gulp.dest('dist/translations/'));
});

gulp.task('i18n:build', ['i18n:translations'], function () {
  var f = production ? 'translations.min.js' : 'translations.js';

  return gulp.src('dist/translations/**/*.js')
      .pipe($.concat(f))
      .pipe(gulp.dest('dist/js'));
});

// No file gets built in the case no translations exist.
// Build one to prevent 404s in browser.
gulp.task('i18n:exists', function () {
  var f = production ? "translations.min.js" : "translations.js";

  fs.readFile("dist/js/" + f, function (err) {
    if (err) {
      mkdirp("dist/js", function (err) {
        if (err) {
          throw err;
        }

        fs.writeFile("dist/js/" + f, "");
      });
    }
  });
});

gulp.task('i18n:clean', del.bind(null, ['dist/translations', 'dist/js/translations.js', 'dist/js/translations.min.js']));

gulp.task('i18n', function (cb) {
  runSequence('i18n:clean', ['i18n:build', 'i18n:exists'], cb);
});

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

gulp.task("config", function () {
  var f = production ? "config.min.js" : "config.js";

  fs.readFile("app/config.js", "UTF-8", function (err, content) {
    if (err) {
      throw err;
    }

    $.git.exec({args: "rev-parse --short HEAD"}, function (err, stdout) {
      if (err) {
        throw err;
      }

      content = content.replace(/__VERSION__/g, packageJSON.version);
      content = content.replace(/__COMMIT__/g, stdout.replace(/[\r\n]/, ""));
      content = content.replace(/__API__/, env.get("api"));

      // Ensures path is in place, as I've had occurances where it may not be.
      mkdirp("dist/js", function (err) {
        if (err) {
          throw err;
        }

        fs.writeFileSync("dist/js/" + f, content);
      });
    });
  });
});

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

// Copy External non Bower Libraries To Dist
gulp.task('vendor', function () {
  return gulp.src(['app/vendor/**'])
      .pipe(gulp.dest('dist/libs'))
      .pipe($.size({title: 'vendor'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  var f = production ? 'styles.min.css' : 'styles.css';

  return gulp.src('app/styles/app.less')
      .pipe($.changed('styles', {extension: '.less'}))
      .pipe($.less().on('error', $.util.log))
      .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
      .pipe($.concat(f))
      //.pipe($.if(production, $.csso()))
    // Concatenate And Minify Styles
      .pipe(gulp.dest('dist/css'))
      .pipe($.size({title: 'styles'}));
});

gulp.task('js:bower', function () {
  var stream = gulp.src(paths.bower);

  if (production) {
    var filter = $.filter('**/*.min.{js,css,map}');

    stream
        .pipe(filter)
        .pipe($.foreach(function (stream, file) {
          if (file.relative.indexOf(".js")) {
            var fileName = file.relative.substr(file.relative.lastIndexOf("/") + 1);
            fileName = fileName.substr(0, fileName.lastIndexOf(".min") + 4) + ".js.map";

            var path = file.relative.substr(0, file.relative.lastIndexOf("/") + 1) + fileName;
            return stream
                .pipe($.replace(fileName, "/libs/" + path));
          }

          return stream;
        }))
        .pipe($.rev())
        .pipe(gulp.dest(paths.vendor))
        .pipe($.rev.manifest())
        .pipe(gulp.dest(paths.vendor))
        .pipe(filter.restore());
  }

  return stream.pipe(gulp.dest('dist/libs'))
      .pipe($.size({title: 'js:bower'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('rev', ['html'], function () {
  var stream = gulp.src('dist/index.html');

  if (production) {
    var manifest = paths.vendor + "/rev-manifest.json";
    var vendorFiles = fs.existsSync(manifest) ? require(manifest) : [];
    var assets = $.useref.assets({searchPath: 'dist'});

    for (var file in vendorFiles) {
      if (vendorFiles.hasOwnProperty(file)) {
        stream = stream.pipe($.replace(file, vendorFiles[file]));
      }
    }

    stream.pipe(assets)
        .pipe($.rev())
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace())
        .pipe(gulp.dest('dist'))
        .pipe($.gzip())
        .pipe(gulp.dest('dist'));
  }

  return stream
      .pipe(gulp.dest('dist'))
      .pipe($.size({title: 'rev'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', ['js:bower', 'ng:templates'], function () {
  var stream = gulp.src('app/index.html');

  if (production) {
    stream
        .pipe($.replace('.js', '.min.js'))
        .pipe($.replace('d3-tip/index.min.js', 'd3-tip/index.js'))
        .pipe($.replace('moment/moment.min.js', 'moment/min/moment.min.js'))
        .pipe($.replace('analytics.min.js', 'analytics.js'))
        .pipe($.replace('FileSaver.min.min.js', 'FileSaver.min.js'))
        .pipe($.replace('.css', '.min.css'))
        .pipe($.replace('src/css/bootcards-desktop.min.css', 'src/css/bootcards-desktop.css'))
        .pipe($.replace('ngprogress-lite.min.css', 'ngprogress-lite.css'));
    // .pipe(
    // $.cdnizer({
    //   allowRev: true,
    //   allowMin: true,
    //   fallbackScript: "<script>function cdnizerLoad(u) {document.write('<scr'+'ipt src=\"'+u+'\"></scr'+'ipt>');}</script>",
    //   fallbackTest: '<script>if(typeof ${ test } === "undefined") cdnizerLoad("${ filepath }");</script>',
    //   files: [
    //     'google:angular',
    //     {
    //       cdn: 'cdnjs:lodash.js',
    //       package: 'lodash',
    //       test: '_'
    //     }
    //   ]}))
  }
  return stream
      .pipe($.replace('__BASE__', env.get("base")))
      .pipe(gulp.dest('dist'))
      .pipe($.size({title: 'html'}));
});

// <tests>
gulp.task('test', ['clean', 'ts:compile', 'ng:templates'], function () {
  runSequence('karma:once')
});

gulp.task('plato', function () {
  return gulp.src('.tmp/scripts/**/*.js')
      .pipe($.plato('report'));
});

gulp.task('karma:once', function () {
  // Be sure to return the stream
  return gulp.src('app/scripts/*.js')
      .pipe($.karma({
        configFile: 'karma.conf.js',
        action: 'run'
      }))
      .on('error', function (err) {
        // Make sure failed tests cause gulp to exit non-zero
        throw err;
      });
});

gulp.task('karma:watch', function () {
  return gulp.src('app/scripts/*.js')
      .pipe($.karma({
        configFile: 'karma.conf.js',
        action: 'watch'
      }));
});

gulp.task('webdriver', $.protractor.webdriver_update);

gulp.task('protractor', ['webdriver'], function () {
  return gulp.src('app/tests/**/*.spec.js')
      .pipe($.protractor.protractor({configFile: 'protractor.conf.js'}));
});
// </tests>

// <typescript>
gulp.task('ts:lint', function () {
  return gulp.src('app/scripts/**/*.ts')
      .pipe($.tslint())
      .pipe($.tslint.report('prose', {emitError: true}));
});

var tsProject = $.typescript.createProject({
  sortOutput: true,
  declarationFiles: true,
  noExternalResolve: false
});

gulp.task('ts:compile', function () {
  var f = production ? 'app.min.js' : 'app.js';
  var tsResult = gulp.src('app/**/*.ts')

      .pipe($.typescript(tsProject));

  tsResult.dts.pipe(gulp.dest('dist/dts'));
  tsResult.js.pipe(gulp.dest('.tmp'));

  return tsResult.js
      .pipe($.sourcemaps.init())
      .pipe($.concat(f))
      .pipe($.ngAnnotate())
      .pipe($.if(production, $.uglify()))
      .pipe($.wrap({src: './iife.txt'}))
      .pipe($.sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe($.size({title: 'typescript'}));
});
// </typescript>

// <ng-templates>
gulp.task('ng:templates', function () {
  var f = production ? 'templates.min.js' : 'templates.js';

  return gulp.src('app/scripts/**/templates/*.html')
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe($.ngHtml2js({
        moduleName: function (file) {
          var path = file.path.split('/'),
              folder = path[path.length - 2];
          return folder.replace(/-[a-z]/g, function (match) {
            return match.substr(1).toUpperCase() + 'templates';
          });
        }
      }))
      .pipe($.concat(f))
      .pipe($.if(production, $.uglify()))
      .pipe(gulp.dest('dist/js'))
      .pipe($.size({title: 'ng:templates'}));
});
// </ng-templates>

// Watch Files For Changes & Reload
gulp.task('serve:web', function (cb) {
  var bsOpts = {
    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: {
      middleware: [
        modRewrite(['!\\.html|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg /index.html [L]'])
      ],
      baseDir: 'dist'
    },
    host: "portal.gdc.nci.nih.gov",
    open: "external"
  };
//    bsOpts.tunnel = production ? 'oicrgdcdev' : false;

  browserSync(bsOpts);

  if (!production) {
    gulp.watch(['app/**/*.html'], ['html', reload]);
    gulp.watch(['app/**/*.{less,css}'], ['styles', reload]);
    gulp.watch(['app/scripts/**/*.ts'], ['ts:compile', reload]);
    gulp.watch(['app/scripts/**/*.html'], ['ng:templates', reload]);
    gulp.watch(['app/images/**/*'], ['images', reload]);
  }
});

gulp.task('pegjs', function () {
  var PEG = require('pegjs');
  var input = fs.readFileSync("gql.pegjs", {encoding: 'utf8'});
  var parser = PEG.buildParser(input, {output: "source"});
  mkdirp("dist/js", function (err) {
    if (err) {
      throw err;
    }
    var out = production ? "dist/js/gql.min.js" : "dist/js/gql.js";
    fs.writeFileSync(out, "window.gql = " + parser);
    if (production) {
      gulp.src(out)
        .pipe($.uglify())
        .pipe(gulp.dest('dist/js'))
        .pipe($.size({title: 'GQL'}));
    }

  });
});

gulp.task('serve', function (cb) {
  runSequence('default', ['karma:watch', 'serve:web'], cb);
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['rev', 'images', 'fonts', 'vendor', 'ts:compile', 'i18n', 'config', 'pegjs'], 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://oicrgdcdev.localtunnel.me',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try {
  require('require-dir')('tasks');
} catch (err) {
}
<commit_msg>fix(build): Fix production builds<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
$.ngAnnotate = require('gulp-ng-annotate');
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var pagespeed = require('psi');
var fs = require('graceful-fs');
var packageJSON = require("./package.json");
var modRewrite = require('connect-modrewrite');
var mkdirp = require("mkdirp");

var habitat = require("habitat");

habitat.load();

var env = new habitat("gdc", {
  api: "https://portal.gdc.nci.nih.gov",
  base: "/"
});

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

var production = process.env.NODE_ENV === "production";
$.util.log('Environment', $.util.colors.blue(production ? 'Production' : 'Development'));

// <paths>
var paths = {
  "src": "./src",
  "dev": "./dist",
  "stage": "./dist",
  "bower": "./bower_components/**/*.{js,css,map,eot,svg,ttf,woff,woff2}",
  js: {},
  html: {}
};
paths.ddest = production ? paths.stage : paths.dev;
paths.js.src = paths.src + "/app/**/*";
paths.js.dest = paths.ddest + "/js";
paths.vendor = paths.ddest + "/libs";
paths.html.src = paths.src + "/index.html";
paths.html.dest = paths.dest + "/index.html";
// </paths>

gulp.task('logs', function () {
  require('conventional-changelog')({
    repository: packageJSON.repository,
    version: packageJSON.version,
    issueLink: function (id) {
      return '[OICR-' + id + '](https://jira.opensciencedatacloud.org/browse/OICR-' + id + ')'
    }
  }, function (err, log) {
    fs.writeFile('CHANGELOG.md', log);
  });
});

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

gulp.task('i18n:pot', function () {
  return gulp.src(['app/scripts/**/*.html', 'app/scripts/**/*.js'])
      .pipe($.angularGettext.extract('template.pot'))
      .pipe(gulp.dest('translations/'));
});

gulp.task('i18n:translations', ['i18n:pot'], function () {
  return gulp.src('translations/**/*.po')
      .pipe($.angularGettext.compile({
        format: 'javascript',
        defaultLanguage: 'en'
      }))
      .pipe(gulp.dest('dist/translations/'));
});

gulp.task('i18n:build', ['i18n:translations'], function () {
  var f = production ? 'translations.min.js' : 'translations.js';

  return gulp.src('dist/translations/**/*.js')
      .pipe($.concat(f))
      .pipe(gulp.dest('dist/js'));
});

// No file gets built in the case no translations exist.
// Build one to prevent 404s in browser.
gulp.task('i18n:exists', function () {
  var f = production ? "translations.min.js" : "translations.js";

  fs.readFile("dist/js/" + f, function (err) {
    if (err) {
      mkdirp("dist/js", function (err) {
        if (err) {
          throw err;
        }

        fs.writeFile("dist/js/" + f, "");
      });
    }
  });
});

gulp.task('i18n:clean', del.bind(null, ['dist/translations', 'dist/js/translations.js', 'dist/js/translations.min.js']));

gulp.task('i18n', function (cb) {
  runSequence('i18n:clean', ['i18n:build', 'i18n:exists'], cb);
});

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

gulp.task("config", function () {
  var f = production ? "config.min.js" : "config.js";

  fs.readFile("app/config.js", "UTF-8", function (err, content) {
    if (err) {
      throw err;
    }

    $.git.exec({args: "rev-parse --short HEAD"}, function (err, stdout) {
      if (err) {
        throw err;
      }

      content = content.replace(/__VERSION__/g, packageJSON.version);
      content = content.replace(/__COMMIT__/g, stdout.replace(/[\r\n]/, ""));
      content = content.replace(/__API__/, env.get("api"));

      // Ensures path is in place, as I've had occurances where it may not be.
      mkdirp("dist/js", function (err) {
        if (err) {
          throw err;
        }

        fs.writeFileSync("dist/js/" + f, content);
      });
    });
  });
});

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

// Copy External non Bower Libraries To Dist
gulp.task('vendor', function () {
  return gulp.src(['app/vendor/**'])
      .pipe(gulp.dest('dist/libs'))
      .pipe($.size({title: 'vendor'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  var f = production ? 'styles.min.css' : 'styles.css';

  return gulp.src('app/styles/app.less')
      .pipe($.changed('styles', {extension: '.less'}))
      .pipe($.less().on('error', $.util.log))
      .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
      .pipe($.concat(f))
      //.pipe($.if(production, $.csso()))
    // Concatenate And Minify Styles
      .pipe(gulp.dest('dist/css'))
      .pipe($.size({title: 'styles'}));
});

gulp.task('js:bower', function () {
  var stream = gulp.src(paths.bower);

  if (production) {
    var filter = $.filter('**/*.min.{js,css,map}');

    stream
        .pipe(filter)
        .pipe($.foreach(function (stream, file) {
          if (file.relative.indexOf(".js")) {
            var fileName = file.relative.substr(file.relative.lastIndexOf("/") + 1);
            fileName = fileName.substr(0, fileName.lastIndexOf(".min") + 4) + ".js.map";

            var path = file.relative.substr(0, file.relative.lastIndexOf("/") + 1) + fileName;
            return stream
                .pipe($.replace(fileName, "/libs/" + path));
          }

          return stream;
        }))
        .pipe($.rev())
        .pipe(gulp.dest(paths.vendor))
        .pipe($.rev.manifest())
        .pipe(gulp.dest(paths.vendor))
        .pipe(filter.restore());
  }

  return stream.pipe(gulp.dest('dist/libs'))
      .pipe($.size({title: 'js:bower'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('rev', ['html'], function () {
  var stream = gulp.src('dist/index.html');

  if (production) {
    var manifest = paths.vendor + "/rev-manifest.json";
    var vendorFiles = fs.existsSync(manifest) ? require(manifest) : [];
    var assets = $.useref.assets({searchPath: 'dist'});

    for (var file in vendorFiles) {
      if (vendorFiles.hasOwnProperty(file)) {
        stream = stream.pipe($.replace(file, vendorFiles[file]));
      }
    }

    stream.pipe(assets)
        .pipe($.rev())
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace())
        .pipe(gulp.dest('dist'))
        .pipe($.gzip())
        .pipe(gulp.dest('dist'));
  }

  return stream
      .pipe(gulp.dest('dist'))
      .pipe($.size({title: 'rev'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', ['js:bower', 'ng:templates'], function () {
  var stream = gulp.src('app/index.html');

  if (production) {
    stream
        .pipe($.replace('.js', '.min.js'))
        .pipe($.replace('d3-tip/index.min.js', 'd3-tip/index.js'))
        .pipe($.replace('moment/moment.min.js', 'moment/min/moment.min.js'))
        .pipe($.replace('analytics.min.js', 'analytics.js'))
        .pipe($.replace('angular-lz-string.min.js', 'angular-lz-string.js'))
        .pipe($.replace('FileSaver.min.min.js', 'FileSaver.min.js'))
        .pipe($.replace('.css', '.min.css'))
        .pipe($.replace('src/css/bootcards-desktop.min.css', 'src/css/bootcards-desktop.css'))
        .pipe($.replace('ngprogress-lite.min.css', 'ngprogress-lite.css'));
    // .pipe(
    // $.cdnizer({
    //   allowRev: true,
    //   allowMin: true,
    //   fallbackScript: "<script>function cdnizerLoad(u) {document.write('<scr'+'ipt src=\"'+u+'\"></scr'+'ipt>');}</script>",
    //   fallbackTest: '<script>if(typeof ${ test } === "undefined") cdnizerLoad("${ filepath }");</script>',
    //   files: [
    //     'google:angular',
    //     {
    //       cdn: 'cdnjs:lodash.js',
    //       package: 'lodash',
    //       test: '_'
    //     }
    //   ]}))
  }
  return stream
      .pipe($.replace('__BASE__', env.get("base")))
      .pipe(gulp.dest('dist'))
      .pipe($.size({title: 'html'}));
});

// <tests>
gulp.task('test', ['clean', 'ts:compile', 'ng:templates'], function () {
  runSequence('karma:once')
});

gulp.task('plato', function () {
  return gulp.src('.tmp/scripts/**/*.js')
      .pipe($.plato('report'));
});

gulp.task('karma:once', function () {
  // Be sure to return the stream
  return gulp.src('app/scripts/*.js')
      .pipe($.karma({
        configFile: 'karma.conf.js',
        action: 'run'
      }))
      .on('error', function (err) {
        // Make sure failed tests cause gulp to exit non-zero
        throw err;
      });
});

gulp.task('karma:watch', function () {
  return gulp.src('app/scripts/*.js')
      .pipe($.karma({
        configFile: 'karma.conf.js',
        action: 'watch'
      }));
});

gulp.task('webdriver', $.protractor.webdriver_update);

gulp.task('protractor', ['webdriver'], function () {
  return gulp.src('app/tests/**/*.spec.js')
      .pipe($.protractor.protractor({configFile: 'protractor.conf.js'}));
});
// </tests>

// <typescript>
gulp.task('ts:lint', function () {
  return gulp.src('app/scripts/**/*.ts')
      .pipe($.tslint())
      .pipe($.tslint.report('prose', {emitError: true}));
});

var tsProject = $.typescript.createProject({
  sortOutput: true,
  declarationFiles: true,
  noExternalResolve: false
});

gulp.task('ts:compile', function () {
  var f = production ? 'app.min.js' : 'app.js';
  var tsResult = gulp.src('app/**/*.ts')

      .pipe($.typescript(tsProject));

  tsResult.dts.pipe(gulp.dest('dist/dts'));
  tsResult.js.pipe(gulp.dest('.tmp'));

  return tsResult.js
      .pipe($.sourcemaps.init())
      .pipe($.concat(f))
      .pipe($.ngAnnotate())
      .pipe($.if(production, $.uglify()))
      .pipe($.wrap({src: './iife.txt'}))
      .pipe($.sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe($.size({title: 'typescript'}));
});
// </typescript>

// <ng-templates>
gulp.task('ng:templates', function () {
  var f = production ? 'templates.min.js' : 'templates.js';

  return gulp.src('app/scripts/**/templates/*.html')
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe($.ngHtml2js({
        moduleName: function (file) {
          var path = file.path.split('/'),
              folder = path[path.length - 2];
          return folder.replace(/-[a-z]/g, function (match) {
            return match.substr(1).toUpperCase() + 'templates';
          });
        }
      }))
      .pipe($.concat(f))
      .pipe($.if(production, $.uglify()))
      .pipe(gulp.dest('dist/js'))
      .pipe($.size({title: 'ng:templates'}));
});
// </ng-templates>

// Watch Files For Changes & Reload
gulp.task('serve:web', function (cb) {
  var bsOpts = {
    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: {
      middleware: [
        modRewrite(['!\\.html|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg /index.html [L]'])
      ],
      baseDir: 'dist'
    },
    host: "portal.gdc.nci.nih.gov",
    open: "external"
  };
//    bsOpts.tunnel = production ? 'oicrgdcdev' : false;

  browserSync(bsOpts);

  if (!production) {
    gulp.watch(['app/**/*.html'], ['html', reload]);
    gulp.watch(['app/**/*.{less,css}'], ['styles', reload]);
    gulp.watch(['app/scripts/**/*.ts'], ['ts:compile', reload]);
    gulp.watch(['app/scripts/**/*.html'], ['ng:templates', reload]);
    gulp.watch(['app/images/**/*'], ['images', reload]);
  }
});

gulp.task('pegjs', function () {
  var PEG = require('pegjs');
  var input = fs.readFileSync("gql.pegjs", {encoding: 'utf8'});
  var parser = PEG.buildParser(input, {output: "source"});
  mkdirp("dist/js", function (err) {
    if (err) {
      throw err;
    }
    var out = production ? "dist/js/gql.min.js" : "dist/js/gql.js";
    fs.writeFileSync(out, "window.gql = " + parser);
    if (production) {
      gulp.src(out)
        .pipe($.uglify())
        .pipe(gulp.dest('dist/js'))
        .pipe($.size({title: 'GQL'}));
    }

  });
});

gulp.task('serve', function (cb) {
  runSequence('default', ['karma:watch', 'serve:web'], cb);
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['rev', 'images', 'fonts', 'vendor', 'ts:compile', 'i18n', 'config', 'pegjs'], 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://oicrgdcdev.localtunnel.me',
  strategy: 'mobile'
}));

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


<commit_before>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var cssMin = require('gulp-cssmin');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var nodemon = require('gulp-nodemon');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var install = require('gulp-install');
// We store the files we want to watch in an object for easy reference
var paths = {
  scripts: [
    './client/lib/angular/angular.min.js',
    './client/lib/angular-route/angular-route.min.js',
    './client/lib/angular-notify/angular-notify.js',

    './client/app/home/home.js',

    './client/app/grid/grid-module.js',
    './client/app/grid/tilemodel.js',
    './client/app/grid/gridservice.js',
    './client/app/grid/grid-controller.js',

    './client/app/deck/deck.js',
    './client/app/meeple/meeple.js',
    '.client/app/directives/*.js',
    './client/app/app.js'
  ],
  stylesheets: [
    './client/assets/css/grid-reset.css',
    './client/assets/css/grid.css',
    './client/assets/css/deck.css',
    './client/assets/css/meeple.css',
    './client/assets/css/home.css'
  ],
  sass: [
    './client/assets/sass/*.scss'
  ]
};

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(sourcemaps.init())
      .pipe(concat('main.js'))
    .pipe(sourcemaps.write())
    // Output to app/dist
    // TODO: UGLIFY AND RENAME FILE FOR MINIFY VERSION
    .pipe(gulp.dest('./client/app/dist'));
});

gulp.task('stylesheets', function() {
  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.dest('./client/assets/css'))
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./client/assets/dist'))
          .pipe(cssMin())
          .pipe(rename('main.min.css'))
          .pipe(sourcemaps.write())
          .pipe(gulp.dest('./client/assets/dist'));
});

gulp.task('test', function() {
  return gulp.src([
    './client/app/**/*.js',
    './server/**/*.js'
  ]).pipe(jshint())
    .pipe(jshint.reporter('default'));
});
gulp.task('install', function() {
  return gulp.src(['./bower.json'])
    .pipe(install());
});

gulp.task('deploy', ['install'], function() {
  gulp.start('stylesheets');
  gulp.start('scripts');
});

gulp.task('watch', function() {
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.sass, ['stylesheets']);
});

gulp.task('develop', function() {
  nodemon({
    script: 'app.js',
    ext: 'html js css scss',
    tasks: ['scripts', 'stylesheets']
  }).on('restart', function() {
    console.log('restarted nodemon');
  });
});

gulp.task('default', ['develop', 'watch']);<commit_msg>got rid of nonexistent script in gulpfile<commit_after>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var cssMin = require('gulp-cssmin');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var nodemon = require('gulp-nodemon');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var install = require('gulp-install');
// We store the files we want to watch in an object for easy reference
var paths = {
  scripts: [
    './client/lib/angular/angular.min.js',
    './client/lib/angular-route/angular-route.min.js',
    './client/lib/angular-notify/angular-notify.js',

    './client/app/home/home.js',

    './client/app/grid/grid-module.js',
    './client/app/grid/tilemodel.js',
    './client/app/grid/gridservice.js',
    './client/app/grid/grid-controller.js',

    './client/app/deck/deck.js',
    './client/app/meeple/meeple.js',
    './client/app/app.js'
  ],
  stylesheets: [
    './client/assets/css/grid-reset.css',
    './client/assets/css/grid.css',
    './client/assets/css/deck.css',
    './client/assets/css/meeple.css',
    './client/assets/css/home.css'
  ],
  sass: [
    './client/assets/sass/*.scss'
  ]
};

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(sourcemaps.init())
      .pipe(concat('main.js'))
    .pipe(sourcemaps.write())
    // Output to app/dist
    // TODO: UGLIFY AND RENAME FILE FOR MINIFY VERSION
    .pipe(gulp.dest('./client/app/dist'));
});

gulp.task('stylesheets', function() {
  return gulp.src(paths.sass)
    .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.dest('./client/assets/css'))
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./client/assets/dist'))
          .pipe(cssMin())
          .pipe(rename('main.min.css'))
          .pipe(sourcemaps.write())
          .pipe(gulp.dest('./client/assets/dist'));
});

gulp.task('test', function() {
  return gulp.src([
    './client/app/**/*.js',
    './server/**/*.js'
  ]).pipe(jshint())
    .pipe(jshint.reporter('default'));
});
gulp.task('install', function() {
  return gulp.src(['./bower.json'])
    .pipe(install());
});

gulp.task('deploy', ['install'], function() {
  gulp.start('stylesheets');
  gulp.start('scripts');
});

gulp.task('watch', function() {
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.sass, ['stylesheets']);
});

gulp.task('develop', function() {
  nodemon({
    script: 'app.js',
    ext: 'html js css scss',
    tasks: ['scripts', 'stylesheets']
  }).on('restart', function() {
    console.log('restarted nodemon');
  });
});

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


<commit_before>var gulp = require('gulp-help')(require('gulp'));
var zip = require('gulp-zip');
var gutil = require('gulp-util');
var st = require('st');
var http = require('http');
var port = process.env.PORT || 3000;

gulp.task('serve', 'Serve the local files using a development server', function(cb) {
  var mount = st({
    path: process.cwd(),
    index: 'index.html',
    cache: false
  });

  http.createServer(mount).listen(port, function(err) {
    if (! err) {
      gutil.log('server running @ http://localhost:' + port + '/');
    }

    cb(err);
  });
});

gulp.task('package', 'Package for upload to build.rtc.io', function() {
  return gulp.src([
    './*',
    '!*.zip',
    'vendor/*',
    '!vendor/*.zip',
    'css/*',
    '!css/*.zip',
    'icons/*',
    '!icons/*.zip',
    '!gulpfile.js',
    '!package.json'
  ], { base: '.' })
  .pipe(zip('archive.zip'))
  .pipe(gulp.dest('.//'));
});

gulp.task('vendor', 'Rebuild vendor scripts from node package dependencies', [
  'vendor-rtc',
  'plugin-ios',
  'plugin-temasys'
]);

gulp.task('vendor-rtc', function() {
  return gulp
    .src('node_modules/rtc/dist/*')
    .pipe(gulp.dest('vendor/'));
});

gulp.task('plugin-ios', function() {
  return gulp
    .src('node_modules/rtc-plugin-nicta-ios/dist/*')
    .pipe(gulp.dest('vendor/'));
});

gulp.task('plugin-temasys', function() {
  return gulp
    .src('node_modules/rtc-plugin-temasys/dist/*')
    .pipe(gulp.dest('vendor/'));
});
<commit_msg>Don't include ipa files into the zip tarball.<commit_after>var gulp = require('gulp-help')(require('gulp'));
var zip = require('gulp-zip');
var gutil = require('gulp-util');
var st = require('st');
var http = require('http');
var port = process.env.PORT || 3000;

gulp.task('serve', 'Serve the local files using a development server', function(cb) {
  var mount = st({
    path: process.cwd(),
    index: 'index.html',
    cache: false
  });

  http.createServer(mount).listen(port, function(err) {
    if (! err) {
      gutil.log('server running @ http://localhost:' + port + '/');
    }

    cb(err);
  });
});

gulp.task('package', 'Package for upload to build.rtc.io', function() {
  return gulp.src([
    './*',
    '!*.zip',
    '!*.ipa',
    'vendor/*',
    '!vendor/*.zip',
    'css/*',
    '!css/*.zip',
    'icons/*',
    '!icons/*.zip',
    '!gulpfile.js',
    '!package.json'
  ], { base: '.' })
  .pipe(zip('archive.zip'))
  .pipe(gulp.dest('.//'));
});

gulp.task('vendor', 'Rebuild vendor scripts from node package dependencies', [
  'vendor-rtc',
  'plugin-ios',
  'plugin-temasys'
]);

gulp.task('vendor-rtc', function() {
  return gulp
    .src('node_modules/rtc/dist/*')
    .pipe(gulp.dest('vendor/'));
});

gulp.task('plugin-ios', function() {
  return gulp
    .src('node_modules/rtc-plugin-nicta-ios/dist/*')
    .pipe(gulp.dest('vendor/'));
});

gulp.task('plugin-temasys', function() {
  return gulp
    .src('node_modules/rtc-plugin-temasys/dist/*')
    .pipe(gulp.dest('vendor/'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var connect = require('gulp-connect');
var open = require('gulp-open');
var minifyCss = require('gulp-minify-css');
var rimraf = require('gulp-rimraf');
var inline = require('gulp-inline');
var template = require('gulp-template');
var minifyHTML = require('gulp-minify-html');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');

var staticAssets = [
    "index.html",
    "./assets/**",
    "./php/!(cache)**",
    "*.ico",
    ".htaccess"
];

function compileJs(watch) {
    var bundler = watchify(browserify('./js/RegExr.js', {debug: true}));

    function rebundle() {
        bundler.bundle()
            .on('error', function (err) {
                console.error(err);
                this.emit('end');
            })
            .pipe(source('scripts.min.js'))
            .pipe(buffer())
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest('./build/js'))
            .pipe(browserSync.stream());
    }

    if (watch) {
        bundler.on('update', function () {
            rebundle();
        });
    }

    rebundle();
}

gulp.task('sass', function () {
    return gulp.src('./scss/regexr.scss')
        .pipe(sass({includePaths: ["scss/third-party/compass-mixins"]}).on('error', sass.logError))
        .pipe(gulp.dest('./build/css'))
        .pipe(browserSync.stream());
});

gulp.task('browser-sync', function () {
    return browserSync(
        {
            open: "local",
            server: {
                baseDir: "./build/"
            }
        });
});

gulp.task('watch-js-templates', function() {
	var assets = "js/*.template.js";
	return gulp.watch(assets).on('change', function () {
		gulp.src(assets, {base: './js'})
			.pipe(gulp.dest('build/js/'));
		browserSync.reload();
	});
});

gulp.task('watch-assets', function () {
    return gulp.src(staticAssets, {base: './'})
        .pipe(watch(staticAssets))
        .pipe(gulp.dest('build/'))
        .pipe(browserSync.stream());
});

gulp.task('watch-sass', function () {
    gulp.watch("./scss/**/*.scss", ['sass']);
});

gulp.task('copy-assets', function () {
    return gulp.src(staticAssets, {base: './'})
        .pipe(gulp.dest('build/'));
});

gulp.task('minify-js', function () {
    return gulp.src(['build/js/scripts.min.js', 'build/js/regExWorker.template.js'])
        .pipe(uglify({
            compress: {
                global_defs: {
                    DEBUG: false
                },
                dead_code: true
            },
            ASCIIOnly: true
        }))
        .pipe(gulp.dest('build/js'));
});

gulp.task('build-js', function () {
    return compileJs();
});

gulp.task('watch-js', function () {
    return compileJs(true);
});

gulp.task('server', function () {
    connect.server({
        root: 'build'
    });
});

gulp.task('minify-css', function () {
    return gulp.src('build/css/regexr.css')
        .pipe(minifyCss())
        .pipe(gulp.dest('build/css'));
});

gulp.task('open-build', function () {
    gulp.src(__filename)
        .pipe(open({uri: 'http://localhost:8080'}));
});

gulp.task('clean-pre-build', function () {
    return gulp.src(['./build/!(v1|.git|sitemap.txt|*.md)'], {read: false})
        .pipe(rimraf());
});

gulp.task('clean-post-build', function () {
    return gulp.src(['./build/js/index.template.js', './build/js/scripts.min.js.map'], {read: false})
        .pipe(rimraf());
});

gulp.task('inline', function() {
    return gulp.src('build/index.html')
        .pipe(inline({
                base: 'build/' ,js: uglify, css: minifyCss
            }
        ))
        .pipe(gulp.dest('build/'));
});

gulp.task('parse-index', function () {
    return gulp.src('build/index.html')
        .pipe(template({noCache: Date.now()}))
        .pipe(minifyHTML())
        .pipe(gulp.dest('build/'));
});

gulp.task('build', function (done) {
    runSequence(
        'clean-pre-build',
        ['build-js', 'copy-assets', 'sass'],
        ['minify-js', 'minify-css', 'inline'],
        ['parse-index', 'clean-post-build'],
        'server', 'open-build',
        done
    );
});

gulp.task('default', function (done) {
    runSequence(
        ['sass', 'watch-js', 'watch-sass'],
        'copy-assets',
        ['watch-assets', 'watch-js-templates', 'browser-sync'],
        done
    );
});
<commit_msg>- Fixed copying of *.template.js files - Changed to use browserSyncs built-in file watching for browser reloads. - Formatting<commit_after>var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var connect = require('gulp-connect');
var open = require('gulp-open');
var minifyCss = require('gulp-minify-css');
var rimraf = require('gulp-rimraf');
var inline = require('gulp-inline');
var template = require('gulp-template');
var minifyHTML = require('gulp-minify-html');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');

var staticAssets = [
	"index.html",
	"./assets/**",
	"./php/!(cache)**",
	"*.ico",
	".htaccess"
];

function compileJs(watch) {
	var bundler = watchify(browserify('./js/RegExr.js', {debug: true}));

	function rebundle() {
		bundler.bundle()
			.on('error', function (err) {
				console.error(err);
				this.emit('end');
			})
			.pipe(source('scripts.min.js'))
			.pipe(buffer())
			.pipe(sourcemaps.init({loadMaps: true}))
			.pipe(sourcemaps.write('./'))
			.pipe(gulp.dest('./build/js'));
	}

	if (watch) {
		bundler.on('update', function () {
			rebundle();
		});
	}

	rebundle();
}

gulp.task('sass', function () {
	return gulp.src('./scss/regexr.scss')
		.pipe(sass({includePaths: ["scss/third-party/compass-mixins"]}).on('error', sass.logError))
		.pipe(gulp.dest('./build/css'));
});

gulp.task('browser-sync', function () {
	return browserSync(
		{
			open: "local",
			server: {
				baseDir: "./build/"
			},
			files: "./build/**"
		});
});

gulp.task('watch-js-templates', function () {
	var assets = "js/*.template.js";
	return gulp.watch(assets, ['copy-js-templates']);
});

gulp.task('copy-js-templates', function () {
	var assets = "js/*.template.js";
	return gulp.src(assets, {base: './js'})
		.pipe(gulp.dest('build/js/'));
});

gulp.task('watch-assets', function () {
	return gulp.src(staticAssets, {base: './'})
		.pipe(watch(staticAssets))
		.pipe(gulp.dest('build/'));
});

gulp.task('watch-sass', function () {
	gulp.watch("./scss/**/*.scss", ['sass']);
});

gulp.task('copy-assets', function () {
	return gulp.src(staticAssets, {base: './'})
		.pipe(gulp.dest('build/'));
});

gulp.task('minify-js', function () {
	return gulp.src(['build/js/scripts.min.js', 'build/js/regExWorker.template.js'])
		.pipe(uglify({
			compress: {
				global_defs: {
					DEBUG: false
				},
				dead_code: true
			},
			ASCIIOnly: true
		}))
		.pipe(gulp.dest('build/js'));
});

gulp.task('build-js', function () {
	return compileJs();
});

gulp.task('watch-js', function () {
	return compileJs(true);
});

gulp.task('server', function () {
	connect.server({
		root: 'build'
	});
});

gulp.task('minify-css', function () {
	return gulp.src('build/css/regexr.css')
		.pipe(minifyCss())
		.pipe(gulp.dest('build/css'));
});

gulp.task('open-build', function () {
	gulp.src(__filename)
		.pipe(open({uri: 'http://localhost:8080'}));
});

gulp.task('clean-pre-build', function () {
	return gulp.src(['./build/!(v1|.git|sitemap.txt|*.md)'], {read: false})
		.pipe(rimraf());
});

gulp.task('clean-post-build', function () {
	return gulp.src(['./build/js/index.template.js', './build/js/scripts.min.js.map'], {read: false})
		.pipe(rimraf());
});

gulp.task('inline', function () {
	return gulp.src('build/index.html')
		.pipe(inline({
				base: 'build/', js: uglify, css: minifyCss
			}
		))
		.pipe(gulp.dest('build/'));
});

gulp.task('parse-index', function () {
	return gulp.src('build/index.html')
		.pipe(template({noCache: Date.now()}))
		.pipe(minifyHTML())
		.pipe(gulp.dest('build/'));
});

gulp.task('build', function (done) {
	runSequence(
		'clean-pre-build',
		['build-js', 'copy-assets', 'sass'],
		['minify-js', 'minify-css', 'inline'],
		['parse-index', 'clean-post-build'],
		'server', 'open-build',
		done
	);
});

gulp.task('default', function (done) {
	runSequence(
		['sass', 'watch-js', 'watch-sass', 'copy-js-templates'],
		'copy-assets',
		['watch-assets', 'watch-js-templates', 'browser-sync'],
		done
	);
});
<|endoftext|>


<commit_before>/*
 * gulpfile for compare-layouts
 *
 * (c) Uwe Gerdes, entwicklung@uwegerdes.de
 */
'use strict';

var exec = require('child_process').exec,
	del = require('del'),
	fs = require('fs'),
	glob = require('glob'),
	gulp = require('gulp'),
	autoprefixer = require('gulp-autoprefixer'),
	server = require('gulp-develop-server'),
	jshint = require('gulp-jshint'),
	lessChanged = require('gulp-less-changed'),
	less = require('gulp-less'),
	lesshint = require('gulp-lesshint'),
	gulpLivereload = require('gulp-livereload'),
	notify = require('gulp-notify'),
	postMortem = require('gulp-postmortem'),
	uglify = require('gulp-uglify'),
	gutil = require('gulp-util'),
	path = require('path'),
	os = require('os'),
	rename = require('rename'),
	runSequence = require('run-sequence')
	;

var baseDir = __dirname;
var testLogfile = path.join(baseDir, 'tests.log');
var testHtmlLogfile = path.join(baseDir, 'tests.html');
var logMode = 0;
var txtLog = [];
var htmlLog = [];
var watchFilesFor = {};
var lifereloadPort = process.env.GULP_LIVERELOAD || 5082;

/*
 * log only to console, not GUI
 */
var log = notify.withReporter(function (options, callback) {
	callback();
});

/*
 * less files lint and style check
 */
watchFilesFor['less-lint'] = [
	path.join(baseDir, 'less', '**', '*.less')
];
gulp.task('less-lint', function () {
	return gulp.src( watchFilesFor['less-lint'] )
		.pipe(lesshint())  // enforce style guide
		.on('error', function (err) {})
		.pipe(lesshint.reporter())
		;
});

watchFilesFor.less = [
	path.join(baseDir, 'less', '**', '*.less'),
	path.join(baseDir, 'less', 'app.less')
];
gulp.task('less', function () {
	var dest = function(filename) {
		return path.join(path.dirname(path.dirname(filename)), 'css');
	};
	var src = watchFilesFor.less.filter(function(el){return el.indexOf('/**/') == -1; });
	return gulp.src( src )
		.pipe(lessChanged({
			getOutputFileName: function(file) {
				return rename( file, { dirname: dest(file), extname: '.css' } );
			}
		}))
		.pipe(less())
		.on('error', log.onError({ message:  'Error: <%= error.message %>' , title: 'LESS Error'}))
		.pipe(autoprefixer('last 3 version', 'safari 5', 'ie 8', 'ie 9', 'ios 6', 'android 4'))
		.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
		.pipe(gulp.dest(function(file) { return dest(file.path); }))
		.pipe(log({ message: 'written: <%= file.path %>', title: 'Gulp less' }))
		;
});

/*
 * jshint javascript files
 */
watchFilesFor.jshint = [
	path.join(baseDir, 'package.json'),
	path.join(baseDir, '**', '*.js')
];
gulp.task('jshint', function(callback) {
	return gulp.src(watchFilesFor.jshint)
		.pipe(jshint())
		.pipe(jshint.reporter('default'))
		;
});

watchFilesFor['compare-layouts-default'] = [
	path.join(baseDir, 'config', 'default.js'),
	path.join(baseDir, 'index.js'),
	path.join(baseDir, 'bin', 'load-page-styles.js')
];
gulp.task('compare-layouts-default', function(callback) {
	del( [
			path.join(baseDir, 'results', 'default', '*.png'),
			path.join(baseDir, 'results', 'default', '*.css.json')
		], { force: true } );
	var loader = exec('node index.js config/default.js',
		{ cwd: baseDir },
		function (err, stdout, stderr) {
			logExecResults(err, stdout, stderr);
			callback();
		}
	);
	loader.stdout.on('data', function(data) { if(!data.match(/PASS/)) { console.log(data.trim()); } });
});

// helper functions
var logExecResults = function (err, stdout, stderr) {
	logTxt (stdout.replace(/\u001b\[[^m]+m/g, '').match(/[^\n]*FAIL [^\n]+/g));
	logHtml(stdout.replace(/\u001b\[[^m]+m/g, '').match(/[^\n]*FAIL [^0-9][^\n]+/g));
	if (err) {
		console.log('error: ' + err.toString());
	}
};

var logTxt = function (msg) {
	if (logMode === 1 && msg){
		var txtMsg = msg.join('\n');
		txtLog.push(txtMsg);
	}
};

var logHtml = function (msg) {
	if (logMode === 1 && msg){
		var htmlMsg = msg.join('
')
						.replace(/FAIL ([^ ]+) ([^ :]+)/, 'FAIL ./results/$1/$22.png')
						.replace(/([^ ]+\/[^ ]+\.png)/g, '$1');
		var errorClass = htmlMsg.indexOf('FAIL') > -1 ? ' class="fail"' : ' class="success"';
		htmlLog.push('\t
' + htmlMsg + '
');
	}
};

var writeTxtLog = function () {
	if (txtLog.length > 0) {
		fs.writeFileSync(testLogfile, txtLog.join('\n') + '\n');
	}
};

var writeHtmlLog = function () {
	if (htmlLog.length > 0) {
		var html = '<!DOCTYPE html>\n\n\n<meta charset="utf-8" />\n' +
				'<title>Testergebnisse</title>\n' +
				'<link href="compare-layouts/css/index.css" rel="stylesheet" />\n' +
				'\n
Testergebnisse
\n
\n';
		html += htmlLog.join('\n');
		html += '
\n\n';
		fs.writeFileSync(testHtmlLogfile, html);
	}
};

gulp.task('clearTestLog', function() {
	del([ testLogfile, testHtmlLogfile ], { force: true });
	logMode = 1;
});

gulp.task('logTestResults', function(callback) {
	if (txtLog.length > 0) {
		console.log('######################## TEST RESULTS ########################');
		console.log(txtLog.join('\n'));
	} else {
		console.log('######################## TEST SUCCESS ########################');
		logTxt (['SUCCESS gulp tests']);
	}
	writeTxtLog();
	writeHtmlLog();
	logMode = 0;
	callback();
});

// start responsive-check server
gulp.task('server:start', function() {
	server.listen({
			path: path.join(baseDir, 'server.js'),
			env: { GULP_LIVERELOAD: lifereloadPort, VERBOSE: false },
			cwd: baseDir
		}
	);
});
gulp.task('server:stop', function() {
    server.kill();
});
// restart server if server.js changed
watchFilesFor.server = [
	path.join(baseDir, 'server.js')
];
gulp.task('server', function() {
	server.changed(function(error) {
		if( error ) {
			console.log('responsive-check server.js restart error: ' + JSON.stringify(error, null, 4));
		} else {
			console.log('responsive-check server.js restarted');
			gulp.src(watchFilesFor.server)
				.pipe(gulpLivereload( { quiet: true } ));
		}
	});
});
/*
 * gulp postmortem task to stop server on termination of gulp
 */
gulp.task('server-postMortem', function() {
	return gulp.src( watchFilesFor.server )
		.pipe(postMortem({gulp: gulp, tasks: [ 'server:stop' ]}))
		;
});

/*
 * livereload server and task
 */
watchFilesFor.livereload = [
	path.join(baseDir, 'views', '*.ejs'),
	path.join(baseDir, 'css', '*.css'),
	path.join(baseDir, 'js', '*.js'),
	path.join(baseDir, 'results', '**', 'index.json')
];
gulp.task('livereload', function() {
	gulp.src(watchFilesFor.livereload)
		.pipe(gulpLivereload( { quiet: true } ));
});

/*
 * compare-layouts selftest task
 */
gulp.task('compare-layouts-selftest', function(callback) {
	runSequence('server:start',
		'build',
		'compare-layouts-default',
		'server:stop',
		'compare-layouts-selftest-success',
		callback);
});

/*
 * compare-layouts selftest check result task
 */
gulp.task('compare-layouts-selftest-success', function() {
	if (!fs.existsSync(path.join(baseDir, 'results', 'default', 'index.json'))) {
		throw 'no result summary created';
	} else {
		console.log('result summary successfully created (with compare differences)');
	}
});

/*
 * run all build tasks
 */
gulp.task('build', function(callback) {
	runSequence('less-lint',
		'less',
		'jshint',
		callback);
});

/*
 * watch task
 */
gulp.task('watch', function() {
	Object.keys(watchFilesFor).forEach(function(task) {
		watchFilesFor[task].forEach(function(filename) {
			glob(filename, function(err, files) {
				if (err) {
					console.log(filename + ' error: ' + JSON.stringify(err, null, 4));
				}
				if (files.length === 0) {
					console.log(filename + ' not found');
				}
			});
		});
		gulp.watch( watchFilesFor[task], [ task ] );
	});
	gulpLivereload.listen( { port: lifereloadPort, delay: 2000 } );
	console.log('gulp livereload listening on http://' + ipv4adresses()[0] + ':' + lifereloadPort);
});

/*
 * default task: run all build tasks and watch
 */
gulp.task('default', function(callback) {
	runSequence('build',
		'server:start',
		'watch',
		'server-postMortem',
		callback);
});

function ipv4adresses() {
	var addresses = [];
	var interfaces = os.networkInterfaces();
	for (var k in interfaces) {
		for (var k2 in interfaces[k]) {
			var address = interfaces[k][k2];
			if (address.family === 'IPv4' && !address.internal) {
				addresses.push(address.address);
			}
		}
	}
	return addresses;
}

module.exports = {
	gulp: gulp,
	watchFilesFor: watchFilesFor
};
<commit_msg>corrected some paths in gulpfile.js<commit_after>/*
 * gulpfile for compare-layouts
 *
 * (c) Uwe Gerdes, entwicklung@uwegerdes.de
 */
'use strict';

var exec = require('child_process').exec,
	del = require('del'),
	fs = require('fs'),
	glob = require('glob'),
	gulp = require('gulp'),
	autoprefixer = require('gulp-autoprefixer'),
	server = require('gulp-develop-server'),
	jshint = require('gulp-jshint'),
	lessChanged = require('gulp-less-changed'),
	less = require('gulp-less'),
	lesshint = require('gulp-lesshint'),
	gulpLivereload = require('gulp-livereload'),
	notify = require('gulp-notify'),
	postMortem = require('gulp-postmortem'),
	uglify = require('gulp-uglify'),
	gutil = require('gulp-util'),
	path = require('path'),
	os = require('os'),
	rename = require('rename'),
	runSequence = require('run-sequence')
	;

var baseDir = __dirname;
var testLogfile = path.join(baseDir, 'tests.log');
var testHtmlLogfile = path.join(baseDir, 'tests.html');
var logMode = 0;
var txtLog = [];
var htmlLog = [];
var watchFilesFor = {};
var lifereloadPort = process.env.GULP_LIVERELOAD || 5082;

/*
 * log only to console, not GUI
 */
var log = notify.withReporter(function (options, callback) {
	callback();
});

/*
 * less files lint and style check
 */
watchFilesFor['less-lint'] = [
	path.join(baseDir, 'less', '**', '*.less')
];
gulp.task('less-lint', function () {
	return gulp.src( watchFilesFor['less-lint'] )
		.pipe(lesshint())  // enforce style guide
		.on('error', function (err) {})
		.pipe(lesshint.reporter())
		;
});

watchFilesFor.less = [
	path.join(baseDir, 'less', '**', '*.less'),
	path.join(baseDir, 'less', 'app.less')
];
gulp.task('less', function () {
	var dest = function(filename) {
		return path.join(path.dirname(path.dirname(filename)), 'css');
	};
	var src = watchFilesFor.less.filter(function(el){return el.indexOf('/**/') == -1; });
	return gulp.src( src )
		.pipe(lessChanged({
			getOutputFileName: function(file) {
				return rename( file, { dirname: dest(file), extname: '.css' } );
			}
		}))
		.pipe(less())
		.on('error', log.onError({ message:  'Error: <%= error.message %>' , title: 'LESS Error'}))
		.pipe(autoprefixer('last 3 version', 'safari 5', 'ie 8', 'ie 9', 'ios 6', 'android 4'))
		.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
		.pipe(gulp.dest(function(file) { return dest(file.path); }))
		.pipe(log({ message: 'written: <%= file.path %>', title: 'Gulp less' }))
		;
});

/*
 * jshint javascript files
 */
watchFilesFor.jshint = [
	path.join(baseDir, 'package.json'),
	path.join(baseDir, '*.js'),
	path.join(baseDir, 'js', '*.js')
];
gulp.task('jshint', function(callback) {
	return gulp.src(watchFilesFor.jshint)
		.pipe(jshint())
		.pipe(jshint.reporter('default'))
		;
});

watchFilesFor['compare-layouts-default'] = [
	path.join(baseDir, 'config', 'default.js'),
	path.join(baseDir, 'index.js'),
	path.join(baseDir, 'bin', 'load-page-styles.js')
];
gulp.task('compare-layouts-default', function(callback) {
	del( [
			path.join(baseDir, 'results', 'default', '*.png'),
			path.join(baseDir, 'results', 'default', '**', 'index.json')
		], { force: true } );
	var loader = exec('node index.js config/default.js',
		{ cwd: baseDir },
		function (err, stdout, stderr) {
			logExecResults(err, stdout, stderr);
			callback();
		}
	);
	loader.stdout.on('data', function(data) { if(!data.match(/PASS/)) { console.log(data.trim()); } });
});

// helper functions
var logExecResults = function (err, stdout, stderr) {
	logTxt (stdout.replace(/\u001b\[[^m]+m/g, '').match(/[^\n]*FAIL [^\n]+/g));
	logHtml(stdout.replace(/\u001b\[[^m]+m/g, '').match(/[^\n]*FAIL [^0-9][^\n]+/g));
	if (err) {
		console.log('error: ' + err.toString());
	}
};

var logTxt = function (msg) {
	if (logMode === 1 && msg){
		var txtMsg = msg.join('\n');
		txtLog.push(txtMsg);
	}
};

var logHtml = function (msg) {
	if (logMode === 1 && msg){
		var htmlMsg = msg.join('
')
						.replace(/FAIL ([^ ]+) ([^ :]+)/, 'FAIL ./results/$1/$22.png')
						.replace(/([^ ]+\/[^ ]+\.png)/g, '$1');
		var errorClass = htmlMsg.indexOf('FAIL') > -1 ? ' class="fail"' : ' class="success"';
		htmlLog.push('\t
' + htmlMsg + '
');
	}
};

var writeTxtLog = function () {
	if (txtLog.length > 0) {
		fs.writeFileSync(testLogfile, txtLog.join('\n') + '\n');
	}
};

var writeHtmlLog = function () {
	if (htmlLog.length > 0) {
		var html = '<!DOCTYPE html>\n\n\n<meta charset="utf-8" />\n' +
				'<title>Testergebnisse</title>\n' +
				'<link href="compare-layouts/css/index.css" rel="stylesheet" />\n' +
				'\n
Testergebnisse
\n
\n';
		html += htmlLog.join('\n');
		html += '
\n\n';
		fs.writeFileSync(testHtmlLogfile, html);
	}
};

gulp.task('clearTestLog', function() {
	del([ testLogfile, testHtmlLogfile ], { force: true });
	logMode = 1;
});

gulp.task('logTestResults', function(callback) {
	if (txtLog.length > 0) {
		console.log('######################## TEST RESULTS ########################');
		console.log(txtLog.join('\n'));
	} else {
		console.log('######################## TEST SUCCESS ########################');
		logTxt (['SUCCESS gulp tests']);
	}
	writeTxtLog();
	writeHtmlLog();
	logMode = 0;
	callback();
});

// start responsive-check server
gulp.task('server:start', function() {
	server.listen({
			path: path.join(baseDir, 'server.js'),
			env: { GULP_LIVERELOAD: lifereloadPort, VERBOSE: false },
			cwd: baseDir
		}
	);
});
gulp.task('server:stop', function() {
    server.kill();
});
// restart server if server.js changed
watchFilesFor.server = [
	path.join(baseDir, 'server.js')
];
gulp.task('server', function() {
	server.changed(function(error) {
		if( error ) {
			console.log('responsive-check server.js restart error: ' + JSON.stringify(error, null, 4));
		} else {
			console.log('responsive-check server.js restarted');
			gulp.src(watchFilesFor.server)
				.pipe(gulpLivereload( { quiet: true } ));
		}
	});
});
/*
 * gulp postmortem task to stop server on termination of gulp
 */
gulp.task('server-postMortem', function() {
	return gulp.src( watchFilesFor.server )
		.pipe(postMortem({gulp: gulp, tasks: [ 'server:stop' ]}))
		;
});

/*
 * livereload server and task
 */
watchFilesFor.livereload = [
	path.join(baseDir, 'views', '*.ejs'),
	path.join(baseDir, 'css', '*.css'),
	path.join(baseDir, 'js', '*.js'),
	path.join(baseDir, 'results', '**', 'index.json')
];
gulp.task('livereload', function() {
	gulp.src(watchFilesFor.livereload)
		.pipe(gulpLivereload( { quiet: true } ));
});

/*
 * compare-layouts selftest task
 */
gulp.task('compare-layouts-selftest', function(callback) {
	runSequence('server:start',
		'build',
		'compare-layouts-default',
		'server:stop',
		'compare-layouts-selftest-success',
		callback);
});

/*
 * compare-layouts selftest check result task
 */
gulp.task('compare-layouts-selftest-success', function() {
	if (!fs.existsSync(path.join(baseDir, 'results', 'default', 'index.json'))) {
		throw 'no result summary created';
	} else {
		console.log('result summary successfully created (with compare differences)');
	}
});

/*
 * run all build tasks
 */
gulp.task('build', function(callback) {
	runSequence('less-lint',
		'less',
		'jshint',
		callback);
});

/*
 * watch task
 */
gulp.task('watch', function() {
	Object.keys(watchFilesFor).forEach(function(task) {
		watchFilesFor[task].forEach(function(filename) {
			glob(filename, function(err, files) {
				if (err) {
					console.log(filename + ' error: ' + JSON.stringify(err, null, 4));
				}
				if (files.length === 0) {
					console.log(filename + ' not found');
				}
			});
		});
		gulp.watch( watchFilesFor[task], [ task ] );
	});
	gulpLivereload.listen( { port: lifereloadPort, delay: 2000 } );
	console.log('gulp livereload listening on http://' + ipv4adresses()[0] + ':' + lifereloadPort);
});

/*
 * default task: run all build tasks and watch
 */
gulp.task('default', function(callback) {
	runSequence('build',
		'server:start',
		'watch',
		'server-postMortem',
		callback);
});

function ipv4adresses() {
	var addresses = [];
	var interfaces = os.networkInterfaces();
	for (var k in interfaces) {
		for (var k2 in interfaces[k]) {
			var address = interfaces[k][k2];
			if (address.family === 'IPv4' && !address.internal) {
				addresses.push(address.address);
			}
		}
	}
	return addresses;
}

module.exports = {
	gulp: gulp,
	watchFilesFor: watchFilesFor
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var path = require('path');
var rename = require('gulp-rename');
var react = require('gulp-react');
var flowtype = require('gulp-flowtype');
var source = require('vinyl-source-stream');
var jsxcs = require('gulp-jsxcs');
var gutil = require('gulp-util');
var jest = require('gulp-jest');
var browserify = require('browserify');
var reactify = require('reactify');
var es6defaultParams = require('es6-default-params');

// Lint Task
gulp.task('prelint', function() {
    return gulp.src('js/**/*.js')
        .pipe(jsxcs().on('error', function(err) {
            console.log(err.toString());
        }))
        .pipe(jshint.reporter('default'));
});

// Lint Task
gulp.task('postlint', function() {
    return gulp.src('build/**/*.js')
        .pipe(jshint({
            esnext: true
        }))
        .pipe(jshint.reporter('default'));
});

gulp.task('typecheck', function() {
    return gulp.src('js/**/*.js')
        .pipe(flowtype({
            declarations: './flowtypes',
            background: false,    // Watch/Server mode
            all: false,           // Check all files regardless
            lib: '',              // Library directory
            module: '',           // Module mode
            stripRoot: false,     // Relative vs Absolute paths
            weak: false,          // Force weak check
            showAllErrors: false, // Show more than 50 errors
            killFlow: false,
        }))
        .pipe(jshint.reporter('default'));
});

// Compile Our LESS
gulp.task('less', function() {
    return gulp.src('./style/**/*.less')
        .pipe(less({
            paths: [ path.join(__dirname, 'style') ]
        }))
        .pipe(gulp.dest('./build/css'));
});

gulp.task('react', function() {
    return browserify('./js/main.js')
        .transform({
            'strip-types': true,
            es6: true}, reactify)
        .transform(es6defaultParams)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./build'));
        /*
        .pipe(react({
            harmony: true,
            // Skip Flow type annotations!
            stripTypes: true
        }))
        */

});

// Concatenate & Minify JS
gulp.task('releasify', function() {
    return gulp.src('build/**/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

// Test
gulp.task('test', function() {
    return gulp.src('__tests__').pipe(jest({
        //testDirectoryName: "__test__",
        testPathIgnorePatterns: [
            "perseus",
            "bower_compoennts",
            "node_modules",
            "spec/support"
        ],
        moduleFileExtensions: [
            "js",
            "json",
            "react"
        ]
    }));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('js/**/*.js', ['prelint', 'typecheck', 'react']);
    gulp.watch('build/**/*.js', ['postlint']);
    gulp.watch('style/**/*.less', ['less']);
});

// Default Task
// Not including Flow typechecking by default because it takes so painfully long.
// Maybe because of my code layout or otheriwse, needto figure it out before enabling by default.
gulp.task('default', ['prelint', 'typecheck', 'react', 'less', 'postlint', 'watch']);
<commit_msg>Enable source maps for browserify<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var path = require('path');
var rename = require('gulp-rename');
var react = require('gulp-react');
var flowtype = require('gulp-flowtype');
var source = require('vinyl-source-stream');
var jsxcs = require('gulp-jsxcs');
var gutil = require('gulp-util');
var jest = require('gulp-jest');
var browserify = require('browserify');
var reactify = require('reactify');
var es6defaultParams = require('es6-default-params');

// Lint Task
gulp.task('prelint', function() {
    return gulp.src('js/**/*.js')
        .pipe(jsxcs().on('error', function(err) {
            console.log(err.toString());
        }))
        .pipe(jshint.reporter('default'));
});

// Lint Task
gulp.task('postlint', function() {
    return gulp.src('build/**/*.js')
        .pipe(jshint({
            esnext: true
        }))
        .pipe(jshint.reporter('default'));
});

gulp.task('typecheck', function() {
    return gulp.src('js/**/*.js')
        .pipe(flowtype({
            declarations: './flowtypes',
            background: false,    // Watch/Server mode
            all: false,           // Check all files regardless
            lib: '',              // Library directory
            module: '',           // Module mode
            stripRoot: false,     // Relative vs Absolute paths
            weak: false,          // Force weak check
            showAllErrors: false, // Show more than 50 errors
            killFlow: false,
        }))
        .pipe(jshint.reporter('default'));
});

// Compile Our LESS
gulp.task('less', function() {
    return gulp.src('./style/**/*.less')
        .pipe(less({
            paths: [ path.join(__dirname, 'style') ]
        }))
        .pipe(gulp.dest('./build/css'));
});

gulp.task('react', function() {
    return browserify('./js/main.js', {
            debug: true
        })
        .transform({
            'strip-types': true,
            es6: true}, reactify)
        .transform(es6defaultParams)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./build'));
        /*
        .pipe(react({
            harmony: true,
            // Skip Flow type annotations!
            stripTypes: true
        }))
        */

});

// Concatenate & Minify JS
gulp.task('releasify', function() {
    return gulp.src('build/**/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

// Test
gulp.task('test', function() {
    return gulp.src('__tests__').pipe(jest({
        //testDirectoryName: "__test__",
        testPathIgnorePatterns: [
            "perseus",
            "bower_compoennts",
            "node_modules",
            "spec/support"
        ],
        moduleFileExtensions: [
            "js",
            "json",
            "react"
        ]
    }));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('js/**/*.js', ['prelint', 'typecheck', 'react']);
    gulp.watch('build/**/*.js', ['postlint']);
    gulp.watch('style/**/*.less', ['less']);
});

// Default Task
// Not including Flow typechecking by default because it takes so painfully long.
// Maybe because of my code layout or otheriwse, needto figure it out before enabling by default.
gulp.task('default', ['prelint', 'typecheck', 'react', 'less', 'postlint', 'watch']);
<|endoftext|>