<commit_before>var co = require('co');
var gulp = require('gulp');
var karma = require('karma').server;
var rename = require('gulp-rename');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var util = require('util');
var wrap = require('gulp-wrap');

// Defines
var FILENAME_DEV = 'src/browser-cookies.js';
var FILENAME_MIN = 'browser-cookies.min.js';
var FILENAME_TST = 'browser-cookies.test.js';

// Browsers to run on Sauce Labs (https://saucelabs.com/platforms/)
var customLaunchers = {
  // Mobile
  /*Android_40: {browserName: 'android',           version: '4.0'},
  Android_50: {browserName: 'android',           version: '5'},
  iPhone_4:   {browserName: 'iphone',            version: '4'},
  iPhone_6:   {browserName: 'iphone',            version: '6'},
  iPhone_8:   {browserName: 'iphone',            version: '8'},*/

  // Desktop
  Chrome_26:  {browserName: 'chrome',            version: '26'},
  Chrome_48:  {browserName: 'chrome',            version: '48'},
  Edge_20:    {browserName: 'MicrosoftEdge',     version: '20'},
  IE_07:      {browserName: 'internet explorer', version:  '7'},
  IE_08:      {browserName: 'internet explorer', version:  '8'},
  IE_09:      {browserName: 'internet explorer', version:  '9'},
  IE_10:      {browserName: 'internet explorer', version: '10'},
  IE_11:      {browserName: 'internet explorer', version: '11'},
  Firefox_04: {browserName: 'firefox',           version:  '4'},
  Firefox_44: {browserName: 'firefox',           version: '44'},
  Opera_11:   {browserName: 'opera',             version: '11'},
  Safari_5:   {browserName: 'safari',            version:  '5'},
  Safari_9:   {browserName: 'safari',            version:  '8'}
};

// Base Karma configuration, contains everything needed for a local teste run
// The config is extended by gulp tasks below to add coverage/sauselabs/etc
var karmaConfig = {
  basePath: '',
  frameworks: ['jasmine'],
  files: ['dist/' + FILENAME_TST, 'test/spec.js'],
  reporters: ['progress', 'spec'],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true,
  preprocessors: {},
  browsers: ['PhantomJS'],
  //logLevel: 'DEBUG',
};

// Function to run Karma on Sauce Labs in batches
// so start 3 jobs -> wait for these to finish -> start another 3 jobs -> etc...
// Using a 'co' function, so asyncronous functions can by yielded synchronous
var runInSeries = function *(config, browsers, done) {
  var parallelJobs = 1;

  var batchTotal = Math.ceil(browsers.length / parallelJobs);
  var batchCurrent = 0;

  while(browsers.length > 0) {
    // Determine the browsers to test in this batch
    config.browsers = [];
    while(browsers.length > 0 && config.browsers.length < parallelJobs) {
      config.browsers.push(browsers.pop());
    }

    console.log(Date.now(), 'Starting batch ' + (batchCurrent + 1) + '/' + batchTotal + ': ', config.browsers.join(', '));

    // Run Karma batch
    yield new Promise(function (resolve, reject) {
      karma.start(config, function () {
        // Resolve using a timeout to allow existing karma session to exit before starting a new session
        setTimeout(function() {resolve();}, 0);
      });
    });

    console.log(Date.now(), 'Finished batch ' + (batchCurrent + 1) + '/' + batchTotal + ': ', config.browsers.join(', '));
    batchCurrent += 1;

    // Increase port number, to prevent conflict with previous Karma session that may still be shutting down
    config = util._extend({}, config);
    config.port += 10;
  }

  done();
};

gulp.task('build', function (done) {
  return gulp.src(FILENAME_DEV)
  .pipe(size({gzip: false, title: FILENAME_DEV + ' size:'}))
  .pipe(uglify())
  .pipe(rename(FILENAME_MIN))
  .pipe(size({gzip: false, title: FILENAME_MIN + ' size:'}))
  .pipe(size({gzip: true,  title: FILENAME_MIN + ' size:'}))
  .pipe(gulp.dest('dist'));
});

gulp.task('test:_build', function (done) {
  return gulp.src(FILENAME_DEV)
    .pipe(rename(FILENAME_TST))
    .pipe(wrap('function requireCookies(document, Date, exports) { <%= contents %> }'))
    .pipe(gulp.dest("dist"));
});

// Test run including code coverage and Sauce Labs
// May be run locally or using travis CI
gulp.task('test:_full', function (done) {
  // Check whether Sause Labs credentials are configured
  if (!process.env.SAUCE_USERNAME) {
    console.log('SAUCE_USERNAME and SAUSE_ACCESS_KEY must be configured as ENV vars');
    process.exit(1);
  }

  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true;

  // Enable code coverage
  config.reporters.push('coverage');
  config.preprocessors['dist/' + FILENAME_TST] = ['coverage'];
  config.coverageReporter = {
    dir: 'coverage/',
    reporters: [
      {type: 'lcov', subdir: '.' },
      {type: 'cobertura', subdir: '.', file: 'cobertura.xml'}
    ]
  };

  // Determine starttime of the test (used in test title and build numbee).
  var date = new Date();
  var startDate = date.toISOString().slice(0,10).replace(/-/g,"");
  function pad(integer) {return ('0' + integer).slice(-2);}
  var startTime = pad(date.getHours()) +pad(date.getMinutes()) + pad(date.getSeconds());
  var start = startDate + '_' + startTime;

  // Configure Sauce Labs browsers
  for (var launcher in customLaunchers) {
    customLaunchers[launcher].base = 'SauceLabs'; // Use SauceLabs
    customLaunchers[launcher].public = 'public'; // Make results public
    customLaunchers[launcher].tags = [launcher]; // Add browser key as tag

    // If running on TRAVIS use the job number as tunnel-identifier for Sauce Labs
    if (process.env.TRAVIS_JOB_NUMBER !== undefined) {
      customLaunchers[launcher]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
      customLaunchers[launcher].build                = process.env.TRAVIS_BUILD_NUMBER + '_' + start;
    } else {
      customLaunchers[launcher]['tunnel-identifier'] = start;
    }
  }

  // Enable Sauce Labs
  config.reporters.push('saucelabs');
  config.sauceLabs = {
    testName: start,
    };
  config.customLaunchers = customLaunchers;
  config.captureTimeout = 60 * 1000;
  config.browserNoActivityTimeout = 300 * 1000;
  config.browserDisconnectTimeout = 15 * 1000;
  config.browserDisconnectTolerance = 1;
  config.background = true;

  //config.browsers = Object.keys(customLaunchers);
  //karma.start(config, done)

  // Run Karma (on Sauce Labs) in batches
  console.log('Starting karma session:', config.sauceLabs.testName);
  co(runInSeries(config, Object.keys(customLaunchers).sort(), done));
});

// Execute tests on local system
gulp.task('test:_local', function (done) {
  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true; // Run only once

  // Run Karma
  karma.start(config, done);
});

gulp.task('test:full',  gulp.series(['test:_build', 'test:_full' ])); // Various browsers using Sauce Labs
gulp.task('test:local', gulp.series(['test:_build', 'test:_local'])); // Local run using PhantomJS
<commit_msg>Updated browser to test using Sauce Labs<commit_after>var co = require('co');
var gulp = require('gulp');
var karma = require('karma').server;
var rename = require('gulp-rename');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var util = require('util');
var wrap = require('gulp-wrap');

// Defines
var FILENAME_DEV = 'src/browser-cookies.js';
var FILENAME_MIN = 'browser-cookies.min.js';
var FILENAME_TST = 'browser-cookies.test.js';

// Browsers to run on Sauce Labs (https://saucelabs.com/platforms/)
var customLaunchers = {
  // Mobile
  /*Android_40: {browserName: 'android',           version: '4.0'},
  Android_50: {browserName: 'android',           version: '5'},
  iPhone_4:   {browserName: 'iphone',            version: '4'},
  iPhone_6:   {browserName: 'iphone',            version: '6'},
  iPhone_8:   {browserName: 'iphone',            version: '8'},*/

  // Desktop
  Chrome_26:  {browserName: 'chrome',            version: '26'},
  Chrome_48:  {browserName: 'chrome',            version: '48'},
  Edge_20:    {browserName: 'MicrosoftEdge',     version: '20'},
  IE_07:      {browserName: 'internet explorer', version:  '7'},
  IE_08:      {browserName: 'internet explorer', version:  '8'},
  IE_09:      {browserName: 'internet explorer', version:  '9'},
  IE_10:      {browserName: 'internet explorer', version: '10'},
  IE_11:      {browserName: 'internet explorer', version: '11'},
  Firefox_04: {browserName: 'firefox',           version:  '4'},
  Firefox_44: {browserName: 'firefox',           version: '44'},
  Opera_11:   {browserName: 'opera',             version: '11'},
  Safari_5:   {browserName: 'safari',            version:  '5'},
  Safari_8:   {browserName: 'safari',            version:  '8'}
};

// Base Karma configuration, contains everything needed for a local teste run
// The config is extended by gulp tasks below to add coverage/sauselabs/etc
var karmaConfig = {
  basePath: '',
  frameworks: ['jasmine'],
  files: ['dist/' + FILENAME_TST, 'test/spec.js'],
  reporters: ['progress', 'spec'],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true,
  preprocessors: {},
  browsers: ['PhantomJS'],
  //logLevel: 'DEBUG',
};

// Function to run Karma on Sauce Labs in batches
// so start 3 jobs -> wait for these to finish -> start another 3 jobs -> etc...
// Using a 'co' function, so asyncronous functions can by yielded synchronous
var runInSeries = function *(config, browsers, done) {
  var parallelJobs = 1;

  var batchTotal = Math.ceil(browsers.length / parallelJobs);
  var batchCurrent = 0;

  while(browsers.length > 0) {
    // Determine the browsers to test in this batch
    config.browsers = [];
    while(browsers.length > 0 && config.browsers.length < parallelJobs) {
      config.browsers.push(browsers.pop());
    }

    console.log(Date.now(), 'Starting batch ' + (batchCurrent + 1) + '/' + batchTotal + ': ', config.browsers.join(', '));

    // Run Karma batch
    yield new Promise(function (resolve, reject) {
      karma.start(config, function () {
        // Resolve using a timeout to allow existing karma session to exit before starting a new session
        setTimeout(function() {resolve();}, 0);
      });
    });

    console.log(Date.now(), 'Finished batch ' + (batchCurrent + 1) + '/' + batchTotal + ': ', config.browsers.join(', '));
    batchCurrent += 1;

    // Increase port number, to prevent conflict with previous Karma session that may still be shutting down
    config = util._extend({}, config);
    config.port += 10;
  }

  done();
};

gulp.task('build', function (done) {
  return gulp.src(FILENAME_DEV)
  .pipe(size({gzip: false, title: FILENAME_DEV + ' size:'}))
  .pipe(uglify())
  .pipe(rename(FILENAME_MIN))
  .pipe(size({gzip: false, title: FILENAME_MIN + ' size:'}))
  .pipe(size({gzip: true,  title: FILENAME_MIN + ' size:'}))
  .pipe(gulp.dest('dist'));
});

gulp.task('test:_build', function (done) {
  return gulp.src(FILENAME_DEV)
    .pipe(rename(FILENAME_TST))
    .pipe(wrap('function requireCookies(document, Date, exports) { <%= contents %> }'))
    .pipe(gulp.dest("dist"));
});

// Test run including code coverage and Sauce Labs
// May be run locally or using travis CI
gulp.task('test:_full', function (done) {
  // Check whether Sause Labs credentials are configured
  if (!process.env.SAUCE_USERNAME) {
    console.log('SAUCE_USERNAME and SAUSE_ACCESS_KEY must be configured as ENV vars');
    process.exit(1);
  }

  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true;

  // Enable code coverage
  config.reporters.push('coverage');
  config.preprocessors['dist/' + FILENAME_TST] = ['coverage'];
  config.coverageReporter = {
    dir: 'coverage/',
    reporters: [
      {type: 'lcov', subdir: '.' },
      {type: 'cobertura', subdir: '.', file: 'cobertura.xml'}
    ]
  };

  // Determine starttime of the test (used in test title and build numbee).
  var date = new Date();
  var startDate = date.toISOString().slice(0,10).replace(/-/g,"");
  function pad(integer) {return ('0' + integer).slice(-2);}
  var startTime = pad(date.getHours()) +pad(date.getMinutes()) + pad(date.getSeconds());
  var start = startDate + '_' + startTime;

  // Configure Sauce Labs browsers
  for (var launcher in customLaunchers) {
    customLaunchers[launcher].base = 'SauceLabs'; // Use SauceLabs
    customLaunchers[launcher].public = 'public'; // Make results public
    customLaunchers[launcher].tags = [launcher]; // Add browser key as tag

    // If running on TRAVIS use the job number as tunnel-identifier for Sauce Labs
    if (process.env.TRAVIS_JOB_NUMBER !== undefined) {
      customLaunchers[launcher]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
      customLaunchers[launcher].build                = process.env.TRAVIS_BUILD_NUMBER + '_' + start;
    } else {
      customLaunchers[launcher]['tunnel-identifier'] = start;
    }
  }

  // Enable Sauce Labs
  config.reporters.push('saucelabs');
  config.sauceLabs = {
    testName: start,
    };
  config.customLaunchers = customLaunchers;
  config.captureTimeout = 60 * 1000;
  config.browserNoActivityTimeout = 300 * 1000;
  config.browserDisconnectTimeout = 15 * 1000;
  config.browserDisconnectTolerance = 1;
  config.background = true;

  //config.browsers = Object.keys(customLaunchers);
  //karma.start(config, done)

  // Run Karma (on Sauce Labs) in batches
  console.log('Starting karma session:', config.sauceLabs.testName);
  co(runInSeries(config, Object.keys(customLaunchers).sort(), done));
});

// Execute tests on local system
gulp.task('test:_local', function (done) {
  // Copy the Karma config
  var config = util._extend({}, karmaConfig);

  // Stop after the test run has finishsed
  config.singleRun = true; // Run only once

  // Run Karma
  karma.start(config, done);
});

gulp.task('test:full',  gulp.series(['test:_build', 'test:_full' ])); // Various browsers using Sauce Labs
gulp.task('test:local', gulp.series(['test:_build', 'test:_local'])); // Local run using PhantomJS
<|endoftext|>


<commit_before>// load everything
var gulp = require('gulp');

var browserSync = require('browser-sync').create();
var del = require('del');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var csso = require('gulp-csso');
var twig = require('gulp-twig');
var fs = require('fs');
var surge = require('gulp-surge');

// Now define some tasks

// a task to delete all css files in dist folder
gulp.task('css:clean', function(){
    return del([
        'dist/*.css',
        'dist/*.map'
    ], { force: true });
});

// CSS compilation (also deletes css files first using previously defined task)
gulp.task('css:compile', ['css:clean'], function(){
    return gulp
        .src('src/scss/index.scss') // this is the source of for compilation
        .pipe(sass().on('error', sass.logError)) // compile sass to css and also tell us about a problem if happens
        .pipe(sourcemaps.init()) // initalizes a sourcemap
        .pipe(postcss([autoprefixer( // supported browsers (from Bootstrap 4 beta: https://github.com/twbs/bootstrap/blob/v4-dev/build/postcss.config.js)
            //
            // Official browser support policy:
            // https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers
            //
            'Chrome >= 45', // Exact version number here is kinda arbitrary
            'Firefox ESR',
            // Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version,
            // NOT the Edge app version shown in Edge's "About" screen.
            // For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12.
            // See also https://github.com/Fyrd/caniuse/issues/1928
            'Edge >= 12',
            'Explorer >= 10',
            // Out of leniency, we prefix these 1 version further back than the official policy.
            'iOS >= 9',
            'Safari >= 9',
            // The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them.
            'Android >= 4.4',
            'Opera >= 30'
        ), require('postcss-flexbugs-fixes')]))
        .pipe(csso()) // compresses CSS
        .pipe(sourcemaps.write('.')) // writes the sourcemap
        .pipe(gulp.dest('./dist')) // destination of the resulting css
        .pipe(browserSync.stream()); // tell browsersync to reload CSS (injects compiled CSS)
});

// delete all html files in dist folder
gulp.task('html:clean', function(){
    return del('dist/**/*.html', { force: true });
});

// HTML compilation from templates
gulp.task('html:compile', ['html:clean'], function(){
    return gulp.src('src/templates/**/[^_]*.twig')
    // compile twig templates to html files
        .pipe(twig({ data: JSON.parse(fs.readFileSync('src/templates/data.json')) })) // import from data.json
        .pipe(gulp.dest('./dist/')) // where to put compiled html
        .on('end', function(){ // after compilation finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

gulp.task('static:clean', function(){
    return del([
        'dist/**/*', // delete all files from src
        '!dist/**/*.html', // except css
        '!dist/**/*.css', // (and it's sourcemap)
        '!dist/**/*.map' // and html files
    ], { force: true });
});

// copy everything static folder
gulp.task('static:copy', ['static:clean'], function(){
    return gulp.src('src/static/**/*')
        .pipe(gulp.dest('dist'))
        .on('end', function(){ // after copying finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

// build everything
gulp.task('build', ['css:compile', 'html:compile', 'static:copy']);

// development with automatic refreshing
gulp.task('develop', ['build'], function(){
    browserSync.init({ // initalize Browsersync
        // set what files be served
        server: {
            baseDir: 'dist', // serve from this folder
            serveStaticOptions: {
                // trying a extension when one isn't specified:
                // effectively means that http://localhost:3000/another-page shows another-page.html
                extensions: ['html']
            }
        }
    });
    gulp.watch('src/scss/**/*', ['css:compile']); // watch for changes in scss
    gulp.watch('src/templates/**/*', ['html:compile']); // watch for changes in templates
    gulp.watch('src/static/**/*', ['static:copy']); // watch for changes in static files
});

// deployment to surge.sh
gulp.task('deploy', ['build'], function(){
    return surge({
        project: 'dist',
        domain: 'https://my-first-website.surge.sh'
    })
});

// set develop as a default task (gulp runs this when you don't specify a task)
gulp.task('default', ['develop']);
<commit_msg>FIX: comments<commit_after>// load everything
var gulp = require('gulp');

var browserSync = require('browser-sync').create();
var del = require('del');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var csso = require('gulp-csso');
var twig = require('gulp-twig');
var fs = require('fs');
var surge = require('gulp-surge');

// Now define some tasks

// a task to delete all css files in dist folder
gulp.task('css:clean', function(){
    return del([
        'dist/*.css',
        'dist/*.map'
    ], { force: true });
});

// CSS compilation (also deletes css files first using previously defined task)
gulp.task('css:compile', ['css:clean'], function(){
    return gulp
        .src('src/scss/index.scss') // this is the source of for compilation
        .pipe(sass().on('error', sass.logError)) // compile sass to css and also tell us about a problem if happens
        .pipe(sourcemaps.init()) // initalizes a sourcemap
        .pipe(postcss([autoprefixer( // supported browsers (from Bootstrap 4 beta: https://github.com/twbs/bootstrap/blob/v4-dev/build/postcss.config.js)
            //
            // Official browser support policy:
            // https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers
            //
            'Chrome >= 45', // Exact version number here is kinda arbitrary
            'Firefox ESR',
            // Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version,
            // NOT the Edge app version shown in Edge's "About" screen.
            // For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12.
            // See also https://github.com/Fyrd/caniuse/issues/1928
            'Edge >= 12',
            'Explorer >= 10',
            // Out of leniency, we prefix these 1 version further back than the official policy.
            'iOS >= 9',
            'Safari >= 9',
            // The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them.
            'Android >= 4.4',
            'Opera >= 30'
        ), require('postcss-flexbugs-fixes')]))
        .pipe(csso()) // compresses CSS
        .pipe(sourcemaps.write('.')) // writes the sourcemap
        .pipe(gulp.dest('./dist')) // destination of the resulting css
        .pipe(browserSync.stream()); // tell browsersync to reload CSS (injects compiled CSS)
});

// delete all html files in dist folder
gulp.task('html:clean', function(){
    return del('dist/**/*.html', { force: true });
});

// HTML compilation from templates
gulp.task('html:compile', ['html:clean'], function(){
    return gulp.src('src/templates/**/[^_]*.twig')
    // compile twig templates to html files
        .pipe(twig({ data: JSON.parse(fs.readFileSync('src/templates/data.json')) })) // import from data.json
        .pipe(gulp.dest('./dist/')) // where to put compiled html
        .on('end', function(){ // after compilation finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

gulp.task('static:clean', function(){
    return del([
        'dist/**/*', // delete all files from src
        '!dist/**/*.html', // except html files
        '!dist/**/*.css', // css and
        '!dist/**/*.map' // and sourcemaps
    ], { force: true });
});

// copy everything static folder
gulp.task('static:copy', ['static:clean'], function(){
    return gulp.src('src/static/**/*')
        .pipe(gulp.dest('dist'))
        .on('end', function(){ // after copying finishes…
            browserSync.reload() // … tell Browsersync to reload
        });
});

// build everything
gulp.task('build', ['css:compile', 'html:compile', 'static:copy']);

// development with automatic refreshing
gulp.task('develop', ['build'], function(){
    browserSync.init({ // initalize Browsersync
        // set what files be served
        server: {
            baseDir: 'dist', // serve from this folder
            serveStaticOptions: {
                // trying a extension when one isn't specified:
                // effectively means that http://localhost:3000/another-page shows another-page.html
                extensions: ['html']
            }
        }
    });
    gulp.watch('src/scss/**/*', ['css:compile']); // watch for changes in scss
    gulp.watch('src/templates/**/*', ['html:compile']); // watch for changes in templates
    gulp.watch('src/static/**/*', ['static:copy']); // watch for changes in static files
});

// deployment to surge.sh
gulp.task('deploy', ['build'], function(){
    return surge({
        project: 'dist',
        domain: 'https://my-first-website.surge.sh'
    })
});

// set develop as a default task (gulp runs this when you don't specify a task)
gulp.task('default', ['develop']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jasmine = require('gulp-jasmine');
var babel = require('gulp-babel');

//Babel transpile
//cmd: gulp babel
gulp.task('babel', function () {
    return gulp.src('src/chartium-es6.js')
        .pipe(babel())
        .pipe(gulp.dest('dist'));
});

//Jasmine tests
//cmd: grunt test
gulp.task('test', function () {
    return gulp.src('spec/test.js')
        .pipe(jasmine());
});<commit_msg>turning off gulp babel for now<commit_after>var gulp = require('gulp');
var jasmine = require('gulp-jasmine');
/*var babel = require('gulp-babel');

//Babel transpile
//cmd: gulp babel
gulp.task('babel', function () {
    return gulp.src('src/chartium-es6.js')
        .pipe(babel())
        .pipe(gulp.dest('dist'));
});
*/
//Jasmine tests
//cmd: grunt test
gulp.task('test', function () {
    return gulp.src('spec/test.js')
        .pipe(jasmine());
});<|endoftext|>


<commit_before>#! /usr/bin/env node

// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

(function () {
    'use strict';

    var define = require('amdefine')(module);

    /**
     * Array of modules this one depends on.
     * @type {Array}
     */
    var deps = [
        'gulp',
        'gulp-bower',
        'gulp-debug',
        'gulp-clean',
        'gulp-concat',
        'gulp-cssshrink',
        'gulp-handlebars',
        'gulp-jshint',
        'gulp-rename',
        'gulp-require-convert',
        'gulp-sass',
        'gulp-sourcemaps',
        'gulp-uglify',
        'gulp-watch',
        'gulp-wrap',
        'gulp-wrap-amd'
    ];

    var sources = {
        sass: [
            './data/public/css/*.scss'
        ],

        scripts: {
            app: [
                './data/public/app/**/*.js'
            ]
        },

        templates: [
            './data/public/app/**/*.hbs'
        ]
    };

    var destDir = './data/public/assets';

    define(deps, function (gulp,
                           bower,
                           debug,
                           clean,
                           concat,
                           cssshrink,
                           handlebars,
                           jshint,
                           rename,
                           requireConvert,
                           sass,
                           sourcemaps,
                           uglify,
                           watch,
                           wrap,
                           wrapAmd) {
        // Lint Task
        gulp.task('lint', ['bower'], function () {
            var src = sources.scripts.app;
            return gulp.src(src)
                .pipe(jshint())
                .pipe(jshint.reporter('default'));
        });

        // Bower Task
        gulp.task('bower', function () {
            return bower({
                cwd: './',
                debugging: true
            });
        });

        // Clean Task
        gulp.task('clean', function() {
            var src = ['./data/public/assets/*.*'];
            return gulp.src(src)
                .pipe(clean());
        });

        // Sass Task
        gulp.task('sass', ['clean'], function () {
            var src = sources.sass;
            return gulp.src(src)
                .pipe(sourcemaps.init())
                .pipe(sass())
                .pipe(cssshrink())
                .pipe(sourcemaps.write())
                .pipe(rename('bundle.css'))
                .pipe(gulp.dest(destDir));
        });

        // Scripts (Application) Task
        gulp.task('scripts.app', ['clean'], function () {
            var src = sources.scripts.app;
            return gulp.src(src)
                .pipe(requireConvert())
                .pipe(rename('bundle.js'))
                .pipe(gulp.dest(destDir));
        });

        // Ember Templates Task
        gulp.task('templates', ['bower', 'clean'], function () {
            var src = sources.templates;
            return gulp.src(src)
                //.pipe(debug())
                .pipe(handlebars({
                    handlebars: require('ember-handlebars')
                }))
                .pipe(wrap({
                        src: './data/public/handlebars/template.hbs'
                    },
                    // Passed variables
                    {},
                    {
                        variable: 'data'
                    }
                ))
                .pipe(concat('templates.js'))
                .pipe(wrapAmd({
                    deps: [
                        'ember'
                    ],
                    exports: 'Ember.TEMPLATES'
                }))
                //.pipe(uglify())
                .pipe(gulp.dest(destDir));
        });

        // Build Task
        gulp.task('build', [
            'clean',
            'sass',
            'scripts.app',
            'lint',
            'templates'
        ]);

        // Default Task
        gulp.task('default', [
            'bower',
            'build'
        ]);
    });
}());<commit_msg>More modular gulpfile<commit_after>#! /usr/bin/env node

// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

(function () {
    'use strict';

    var define = require('amdefine')(module);

    /**
     * Array of modules this one depends on.
     * @type {Array}
     */
    var deps = [
        'gulp',
        'gulp-bower',
        'gulp-debug',
        'gulp-clean',
        'gulp-concat',
        'gulp-cssshrink',
        'gulp-handlebars',
        'gulp-jshint',
        'gulp-rename',
        'gulp-require-convert',
        'gulp-sass',
        'gulp-sourcemaps',
        'gulp-uglify',
        'gulp-watch',
        'gulp-wrap',
        'gulp-wrap-amd'
    ];

    var dirs = [

    ];

    var files = {
        assets: [
            './data/public/assets/*.*'
        ],
        sass: [
            './data/public/css/*.scss'
        ],

        scripts: {
            app: [
                './data/public/app/**/*.js'
            ]
        },

        templates: [
            './data/public/app/**/*.hbs'
        ]
    };

    var destDir = './data/public/assets';

    define(deps, function (gulp,
                           bower,
                           debug,
                           clean,
                           concat,
                           cssshrink,
                           handlebars,
                           jshint,
                           rename,
                           requireConvert,
                           sass,
                           sourcemaps,
                           uglify,
                           watch,
                           wrap,
                           wrapAmd) {

        // Variable used for specifying module dependencies
        var deps = [];

        // Lint Task
        deps = [
            'bower'
        ];
        gulp.task('lint', deps, function () {
            var src = files.scripts.app;
            return gulp.src(src)
                .pipe(jshint())
                .pipe(jshint.reporter('default'));
        });

        // Bower Task
        gulp.task('bower', function () {
            return bower({
                cwd: './',
                debugging: true
            });
        });

        // Clean Task
        gulp.task('clean', function() {
            var src = files.assets;
            return gulp.src(src)
                .pipe(clean());
        });

        // Sass Task
        deps = [
            'bower',
            'clean'
        ];
        gulp.task('sass', deps, function () {
            var src = files.sass;
            return gulp.src(src)
                .pipe(sourcemaps.init())
                .pipe(sass())
                .pipe(cssshrink())
                .pipe(sourcemaps.write())
                .pipe(rename('bundle.css'))
                .pipe(gulp.dest(destDir));
        });

        // Scripts (Application) Task
        deps = [
            'scripts.core'
        ];
        gulp.task('scripts.app', deps, function () {
            var src = files.scripts.app;
            return gulp.src(src)
                .pipe(requireConvert())
                .pipe(rename('bundle.js'))
                .pipe(gulp.dest(destDir));
        });

        // Scripts (Bundle) Task
        deps = [
            'scripts.app'
        ];
        gulp.task('scripts.bundle', deps, function () {
            var src = [];
            return gulp.src(src);
        });

        // Script (Core) Task
        deps = [
            'bower',
            'clean'
        ];
        gulp.task('scripts.core', deps, function () {
            var src = [];
            return gulp.src(src);
        });

        // Ember Templates Task
        deps = [
            'bower',
            'clean'
        ];
        gulp.task('templates', deps, function () {
            var src = files.templates;
            return gulp.src(src)
                //.pipe(debug())
                .pipe(handlebars({
                    handlebars: require('ember-handlebars') // Ember <= 1.8.1 && Handlebars <= 1.3.0
                    // handlebars: require('handlebars') // Ember >= 1.9 && Handlebars >= 2.0
                }))
                .pipe(wrap({
                        src: './data/public/handlebars/template.hbs'
                    },
                    // Passed variables
                    {},
                    {
                        variable: 'data'
                    }
                ))
                .pipe(concat('templates.js'))
                .pipe(wrapAmd({
                    deps: [
                        'ember'
                    ],
                    exports: 'Ember.TEMPLATES'
                }))
                //.pipe(uglify())
                .pipe(gulp.dest(destDir));
        });

        // Build Task
        gulp.task('build', [
            'clean',
            'sass',
            'scripts.bundle',
            'lint',
            'templates'
        ]);

        // Default Task
        gulp.task('default', [
            'bower',
            'build'
        ]);
    });
}());<|endoftext|>


<commit_before>var gulp = require('gulp');
var pump = require('pump');
var changed = require('gulp-changed');
var order = require("gulp-order");
var concat = require('gulp-concat');
var babel = require('gulp-babel')
var uglify = require('gulp-uglify');

gulp.task("fs", function(cb) {
  pump([
    gulp.src("src/kernel/fs/*.js"),
    order([
      "pathname.js",
      "disk.js",
      "vfs.js",
      "*"
    ]),
    concat("fs.js"),
    gulp.dest("build/.kernel/")
  ], cb);
});

gulp.task("proc", function(cb) {
  pump([
    gulp.src("src/kernel/proc/*.js"),
    order([
      "*"
    ]),
    concat("proc.js"),
    gulp.dest("build/.kernel/")
  ], cb);
});

gulp.task("kernel", ["fs", "proc"], function(cb) {
  pump([
    gulp.src("build/.kernel/*.js"),
    order([
      "fs.js",
      "proc.js",
      "*"
    ]),
    concat("kernel.js"),
    gulp.dest("build/")
  ], cb);
});

gulp.task("default", ["kernel"], function(cb) {
  pump([
    gulp.src( ["src/misc.js", "build/*.js", "src/computer.js"] ),
    order([
      "misc.js",
      "kernel.js",
      "*",
      "computer.js"
    ]),
    concat("fauxOS.js"),
    babel({
      presets: ["es2015"]
    }),
    uglify( {mangle: false} ),
    gulp.dest("./"),
  ], cb);
});<commit_msg>order kernel/proc files<commit_after>var gulp = require('gulp');
var pump = require('pump');
var changed = require('gulp-changed');
var order = require("gulp-order");
var concat = require('gulp-concat');
var babel = require('gulp-babel')
var uglify = require('gulp-uglify');

gulp.task("fs", function(cb) {
  pump([
    gulp.src("src/kernel/fs/*.js"),
    order([
      "pathname.js",
      "disk.js",
      "vfs.js",
      "*"
    ]),
    concat("fs.js"),
    gulp.dest("build/.kernel/")
  ], cb);
});

gulp.task("proc", function(cb) {
  pump([
    gulp.src("src/kernel/proc/*.js"),
    order([
      "filedesc.js",
      "process.js",
      "*"
    ]),
    concat("proc.js"),
    gulp.dest("build/.kernel/")
  ], cb);
});

gulp.task("kernel", ["fs", "proc"], function(cb) {
  pump([
    gulp.src("build/.kernel/*.js"),
    order([
      "fs.js",
      "proc.js",
      "*"
    ]),
    concat("kernel.js"),
    gulp.dest("build/")
  ], cb);
});

gulp.task("default", ["kernel"], function(cb) {
  pump([
    gulp.src( ["src/misc.js", "build/*.js", "src/computer.js"] ),
    order([
      "misc.js",
      "kernel.js",
      "*",
      "computer.js"
    ]),
    concat("fauxOS.js"),
    babel({
      presets: ["es2015"]
    }),
    uglify( {mangle: false} ),
    gulp.dest("./"),
  ], cb);
});
<|endoftext|>


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

var gulp = require('gulp');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var concatCss = require('gulp-concat-css');

var cssify = require('cssify');
var watchify = require('watchify');
var browserify = require('browserify');

var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

gulp.task('clean', function() {
  del(['static/css', 'static/js']);
});

gulp.task('css', function(){
    gulp.src('./node_modules/bootstrap/dist/css/*.min.css')
    .pipe(concatCss("site.min.css"))
    .pipe(gulp.dest('./static/css/'));

    gulp.src('./node_modules/bootstrap/dist/fonts/*')
    .pipe(gulp.dest('./static/fonts/'));
});

gulp.task('build', ['clean', 'css'], function() {
  var bundler = browserify({
      entries: 'dinosaurs/index.js',
    });

    bundler.bundle()
    .pipe(source('site.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./static/js'));
});

gulp.task('develop', function() {
  var bundler = watchify(browserify({
      cache: {}, packageCache: {}, fullPaths: true,
      entries: 'dinosaurs/index.js',
      debug: true
    }));
    // bundler.transform('cssify');
  bundler.on('update', rebundle);

  function rebundle() {
    return bundler.bundle()
      // log errors if they happen
      .on('error', gutil.log.bind(gutil, 'Browserify Error'))
      .pipe(source('site.min.js'))
      .pipe(gulp.dest('./static/js'));
  }

  return rebundle();
});

gulp.task('default', ['clean', 'css', 'develop']);
<commit_msg>Minify our css<commit_after>var del = require('del');

var gulp = require('gulp');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');
var concatCss = require('gulp-concat-css');

var watchify = require('watchify');
var browserify = require('browserify');

var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

gulp.task('clean', function() {
  del(['static/css', 'static/js']);
});

gulp.task('css', function(){
    gulp.src('./node_modules/bootstrap/dist/css/*.min.css')
    .pipe(concatCss("site.min.css"))
    .pipe(minifyCSS())
    .pipe(gulp.dest('./static/css/'));

    gulp.src('./node_modules/bootstrap/dist/fonts/*')
    .pipe(gulp.dest('./static/fonts/'));
});

gulp.task('build', ['clean', 'css'], function() {
  var bundler = browserify({
      entries: 'dinosaurs/index.js',
    });

    bundler.bundle()
    .pipe(source('site.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest('./static/js'));
});

gulp.task('develop', function() {
  var bundler = watchify(browserify({
      cache: {}, packageCache: {}, fullPaths: true,
      entries: 'dinosaurs/index.js',
      debug: true
    }));
    // bundler.transform('cssify');
  bundler.on('update', rebundle);

  function rebundle() {
    return bundler.bundle()
      // log errors if they happen
      .on('error', gutil.log.bind(gutil, 'Browserify Error'))
      .pipe(source('site.min.js'))
      .pipe(gulp.dest('./static/js'));
  }

  return rebundle();
});

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


<commit_before>/* eslint-env node */
/* eslint-disable no-console, no-shadow, no-param-reassign */
const fs = require('fs');
const chalk = require('chalk');
const path = require('path');
const rmdir = require('rmdir');
const gulp = require('gulp');
const Server = require('karma').Server;
const $ = require('gulp-load-plugins')();
const babelConfig = require('./build/babel.config');

// use only relative paths
const TEST_FILES = ['./src/**/*_test.js'];
const SRC_FILES = ['./src/**/*.js', '!./src/**/*_test.js'];
const TEMPLATE = {
  src:
'export default function {{name}}({{args}}) {\n}\n',

  test:
`/* eslint-env mocha */
import A from 'assert';
import {{name}} from './{{name}}';
import util from '../../build/util';

describe('{{name}}({{args}})', () => {
  it('passes', () => {
    A.equal({{name}}, {{name}});
  });
});\n`,

  bench:
`require('../../build/babel.register');
const Benchmark = require('Benchmark');
const suite = new Benchmark.Suite('{{pack}}.{{name}}()');
const util = require('../../build/util');

const {{name}} = require('../../src/{{pack}}/{{name}}');

suite
  .add('{{pack}}.{{name}}', () => {
  });

module.exports = suite;\n`,
};

//------------------------------------------------------------------------------
// HELPERS
//------------------------------------------------------------------------------
const readFiles = (fullPath, includeTests) => (dir) => {
  let result = fs.readdirSync(dir)
    .filter(f => f !== 'index.js' && f[0] !== '_');

  if (!includeTests)
    result = result.filter(f => f.slice(-8) !== '_test.js');

  if (fullPath)
    result = result.map(f => path.join(dir, f));

  return result;
};

const PACKAGES = readFiles(false, false)('./src');
const packExists = (name) => {
  return PACKAGES.indexOf(name) >= 0;
};

const fileExists = (dir, file) => {
  const files = readFiles(false, true)(dir);
  return files.indexOf(file) >= 0;
};

const message = (color, bg) => (msg) => {
  if (bg == null) {
    console.error(chalk.red(msg));
  } else {
    const bgColor = `bg${bg[0].toUpperCase()}${bg.slice(1)}`;
    console.error(chalk[color](chalk[bgColor](msg)));
  }
};

const error = message('white', 'red');
const failure = done => (msg) => {
  error(msg);
  done();
};

const pathFromRoot = (relative) => {
  return path.join(__dirname, relative);
};
const pathFromSrc = (relative) => {
  return path.join(__dirname, 'src', relative);
};

const fileInfo = (name, suffix) => {
  if (typeof name !== 'string' || name.indexOf('.') < 0)
    return error(`"${name}" is not a valid name`);

  const [pack, fn] = name.split('.');
  const fname = suffix !== '_bench' ? `${fn}${suffix}.js` : `${fn}.js`;
  const dir = suffix !== '_bench' ? pathFromSrc(pack) :
    path.join(pathFromRoot('benchmark'), pack);

  return [pack, fn, dir, fname];
};

const writeIndex = dir => function writeIndex(done) {
  const write = (folder) => {
    if (path.basename(folder)[0] === '_')
      return;

    const files = readFiles(false, false)(folder);
    const contents = files.reduce((a, f) => {
      const n = f.slice(0, -3);

      if (f !== 'index.js' && f[0] !== '_')
        a += `export { default as ${n} } from './${n}';\n`;

      return a;
    }, '');

    fs.writeFileSync(path.join(folder, 'index.js'), contents);
  };

  if (dir !== 'all') {
    write(dir);
  } else {
    fs.readdirSync('./src')
      .map(pathFromSrc)
      .forEach(write);
  }

  if (done) done();
};

//------------------------------------------------------------------------------
// TASKS
//------------------------------------------------------------------------------
const bundle = name => function bundle() {
  return gulp.src(SRC_FILES)
    .pipe($.babel(babelConfig[name]))
    .pipe(gulp.dest(name === 'next' ? './next' : '.'));
};

const eslint = (file, fail) => function eslint() {
  const src = file === 'all' ? './**/*.js' : file;
  let stream = gulp.src(src)
    .pipe($.eslint())
    .pipe($.eslint.format());

  if (fail)
    stream = stream.pipe($.eslint.failAfterError());

  return stream;
};

const mocha = (file, fail) => function mocha() {
  const src = file === 'all' ? TEST_FILES : file;
  const stream = gulp.src(src)
    .pipe($.mocha({
      reporter: 'progress',
      bail: true,
      require: ['./build/babel.register.js'],
    }));

  if (fail === false) {
    stream.on('error', (err) => {
      return $.util.log(err.message);
    });
  }

  return stream;
};

const karma = () => function karma(done) {
  const single = $.util.env.s !== undefined;
  const server = new Server({
    configFile: path.join(__dirname, 'build/karma.config.js'),
    singleRun: single,
  }, done);

  server.start();
};

const benchmark = () => function benchmark() {
  let file = ['./benchmark/**/*.js', '!./benchmark/_**/*.js'];

  const name = $.util.env.f;
  if (name) {
    const [,, dir, fname] = fileInfo(name, '_bench');
    file = path.join(dir, fname.replace('.js', '*.js'));
  }

  return gulp.src(file, { read: false })
    .pipe($.benchmark());
};

const clean = () => function clean(done) {
  fs.readdirSync('./')
    .filter(p => !p.match(/^\..+|.+\.js[on]?|build|src|benchmark|node_modules|README|LICENSE/))
    .map(pathFromRoot)
    .forEach(p => rmdir(p));
  done();
};

const watchBuild = () => function watching(done) {
  const old = fs.readdirSync('./src')
    .map(pathFromSrc)
    .map(readFiles(true, true))
    .reduce((a, f) => a.concat(f), []);

  return gulp.watch(SRC_FILES)
    .on('change', (name) => {
      const file = pathFromRoot(name);
      const dir = path.dirname(file);
      const basename = path.basename(file);

      if (basename === 'index.js')
        return;

      // run the tests for this file
      const testFile = basename.slice(-8) === '_test.js' ? file :
        file.replace(basename.slice(-3), '_test.js');

      if (fs.existsSync(testFile)) {
        console.log('Running tests in', testFile);
        mocha(testFile, false)();
      }

      // lint this file
      eslint(file, false)();

      // New file. Add it to the index of the package.
      if (old.indexOf(file) < 0) {
        writeIndex(dir)(done);
        old.push(file);
      }
    })
    .on('unlink', (name) => {
      const file = pathFromRoot(name);
      const dir = path.dirname(file);
      const oldi = old.indexOf(file);

      if (path.basename(file) === 'index.js')
        return;

      if (oldi >= 0) {
        writeIndex(dir)(done);
        old.splice(oldi, 1);
      }
    });
};

const create = () => function create(done) {
  const file = $.util.env.f;
  const test = $.util.env.t !== undefined ? $.util.env.t : file ? 'true' : 'false';
  const bench = $.util.env.b !== undefined ? $.util.env.b : 'false';
  const args = $.util.env.a !== undefined ? $.util.env.a.replace(/,/g, ', ') : undefined;
  const fail = failure(done);

  if ((file !== undefined || test !== 'false') && args === undefined)
    return fail('no argument list defined');

  if (!file && test === true && !bench)
    return fail('nothing to do');

  const write = (what, file, name, pack, args) => {
    const contents = TEMPLATE[what]
      .replace(/{{name}}/g, name)
      .replace(/{{pack}}/g, pack)
      .replace(/{{args}}/g, args);

    fs.writeFileSync(file, contents);
  };

  if (file) {
    const [pack, fn, dir, fname] = fileInfo(file, '');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);
    if (fileExists(dir, fname))
      return fail(`file "${fname}" already exists`);

    write('src', path.join(dir, fname), fn, pack, args);
    writeIndex(dir)();
  }

  if (test !== 'false') {
    const name = file || test;
    const [pack, fn, dir, fname] = fileInfo(name, '_test');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);
    if (!fileExists(dir, `${fn}.js`))
      return fail(`source file of "${name}" not found`);
    if (fileExists(dir, fname))
      return fail(`file ${fname} already exists`);

    write('test', path.join(dir, fname), fn, pack, args);
  }

  if (bench !== 'false') {
    const name = file || bench;
    const [pack, fn, dir, fname] = fileInfo(name, '_bench');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);

    if (!fileExists(path.dirname(dir), pack))
      fs.mkdirSync(dir);

    if (fileExists(dir, fname))
      return fail(`file "${fname}" already exists`);

    write('bench', path.join(dir, fname), fn, pack, args);
  }

  done();
};

gulp.task('new', create());
gulp.task('mocha', mocha('all', false));
gulp.task('karma', karma());
gulp.task('eslint', eslint('all', false));
gulp.task('test', gulp.parallel(eslint('all', true), mocha('all', true)));
gulp.task('test-bundle', mocha('./build/bundle_test.js', true));
gulp.task('bundle-node', bundle('node', false));
gulp.task('bundle-next', bundle('next', false));
gulp.task('bundle', gulp.parallel('bundle-node', 'bundle-next'));
gulp.task('build', gulp.series(writeIndex('all'), 'test', 'bundle'));
gulp.task('benchmark', benchmark());
gulp.task('clean', clean());
gulp.task('dev', gulp.series(
  gulp.parallel(writeIndex('all'), 'eslint', 'mocha'),
  watchBuild()
));
<commit_msg>(- chore) Makes error messages more readable<commit_after>/* eslint-env node */
/* eslint-disable no-console, no-shadow, no-param-reassign */
const fs = require('fs');
const chalk = require('chalk');
const path = require('path');
const rmdir = require('rmdir');
const gulp = require('gulp');
const Server = require('karma').Server;
const $ = require('gulp-load-plugins')();
const babelConfig = require('./build/babel.config');

// use only relative paths
const TEST_FILES = ['./src/**/*_test.js'];
const SRC_FILES = ['./src/**/*.js', '!./src/**/*_test.js'];
const TEMPLATE = {
  src:
'export default function {{name}}({{args}}) {\n}\n',

  test:
`/* eslint-env mocha */
import A from 'assert';
import {{name}} from './{{name}}';
import util from '../../build/util';

describe('{{name}}({{args}})', () => {
  it('passes', () => {
    A.equal({{name}}, {{name}});
  });
});\n`,

  bench:
`require('../../build/babel.register');
const Benchmark = require('Benchmark');
const suite = new Benchmark.Suite('{{pack}}.{{name}}()');
const util = require('../../build/util');

const {{name}} = require('../../src/{{pack}}/{{name}}');

suite
  .add('{{pack}}.{{name}}', () => {
  });

module.exports = suite;\n`,
};

// -----------------------------------------------------------------------------
// HELPERS
// -----------------------------------------------------------------------------
const readFiles = (fullPath, includeTests) => (dir) => {
  let result = fs.readdirSync(dir)
    .filter(f => f !== 'index.js' && f[0] !== '_');

  if (!includeTests)
    result = result.filter(f => f.slice(-8) !== '_test.js');

  if (fullPath)
    result = result.map(f => path.join(dir, f));

  return result;
};

const PACKAGES = readFiles(false, false)('./src');
const packExists = (name) => {
  return PACKAGES.indexOf(name) >= 0;
};

const fileExists = (dir, file) => {
  const files = readFiles(false, true)(dir);
  return files.indexOf(file) >= 0;
};

const log = {
  error(msg) {
    console.log(chalk.bold('\nError:'), chalk.yellow(msg), '\n');
  },
};

const pathFromRoot = (relative) => {
  return path.join(__dirname, relative);
};
const pathFromSrc = (relative) => {
  return path.join(__dirname, 'src', relative);
};

const fileInfo = (name, suffix) => {
  if (typeof name !== 'string' || name.indexOf('.') < 0)
    return log.error(`"${name}" is not a valid name`);

  const [pack, fn] = name.split('.');
  const fname = suffix !== '_bench' ? `${fn}${suffix}.js` : `${fn}.js`;
  const dir = suffix !== '_bench' ? pathFromSrc(pack) :
    path.join(pathFromRoot('benchmark'), pack);

  return [pack, fn, dir, fname];
};

const writeIndex = dir => function writeIndex(done) {
  const write = (folder) => {
    if (path.basename(folder)[0] === '_')
      return;

    const files = readFiles(false, false)(folder);
    const contents = files.reduce((a, f) => {
      const n = f.slice(0, -3);

      if (f !== 'index.js' && f[0] !== '_')
        a += `export { default as ${n} } from './${n}';\n`;

      return a;
    }, '');

    fs.writeFileSync(path.join(folder, 'index.js'), contents);
  };

  if (dir !== 'all') {
    write(dir);
  } else {
    fs.readdirSync('./src')
      .map(pathFromSrc)
      .forEach(write);
  }

  if (done) done();
};

// -----------------------------------------------------------------------------
// TASKS
// -----------------------------------------------------------------------------
const bundle = name => function bundle() {
  return gulp.src(SRC_FILES)
    .pipe($.babel(babelConfig[name]))
    .pipe(gulp.dest(name === 'next' ? './next' : '.'));
};

const eslint = (file, fail) => function eslint() {
  const src = file === 'all' ? './**/*.js' : file;
  let stream = gulp.src(src)
    .pipe($.eslint())
    .pipe($.eslint.format());

  if (fail)
    stream = stream.pipe($.eslint.failAfterError());

  return stream;
};

const mocha = (file, fail) => function mocha() {
  const src = file === 'all' ? TEST_FILES : file;
  const stream = gulp.src(src)
    .pipe($.mocha({
      reporter: 'progress',
      bail: true,
      require: ['./build/babel.register.js'],
    }));

  if (fail === false) {
    stream.on('error', (err) => {
      return $.util.log(err.message);
    });
  }

  return stream;
};

const karma = () => function karma(done) {
  const single = $.util.env.s !== undefined;
  const server = new Server({
    configFile: path.join(__dirname, 'build/karma.config.js'),
    singleRun: single,
  }, done);

  server.start();
};

const benchmark = () => function benchmark() {
  let file = ['./benchmark/**/*.js', '!./benchmark/_**/*.js'];

  const name = $.util.env.f;
  if (name) {
    const [,, dir, fname] = fileInfo(name, '_bench');
    file = path.join(dir, fname.replace('.js', '*.js'));
  }

  return gulp.src(file, { read: false })
    .pipe($.benchmark());
};

const clean = () => function clean(done) {
  fs.readdirSync('./')
    .filter(p => !p.match(/^\..+|.+\.js[on]?|build|src|benchmark|node_modules|README|LICENSE/))
    .map(pathFromRoot)
    .forEach(p => rmdir(p));
  done();
};

const watchBuild = () => function watching(done) {
  const old = fs.readdirSync('./src')
    .map(pathFromSrc)
    .map(readFiles(true, true))
    .reduce((a, f) => a.concat(f), []);

  return gulp.watch(SRC_FILES)
    .on('change', (name) => {
      const file = pathFromRoot(name);
      const dir = path.dirname(file);
      const basename = path.basename(file);

      if (basename === 'index.js')
        return;

      // run the tests for this file
      const testFile = basename.slice(-8) === '_test.js' ? file :
        file.replace(basename.slice(-3), '_test.js');

      if (fs.existsSync(testFile)) {
        console.log('Running tests in', testFile);
        mocha(testFile, false)();
      }

      // lint this file
      eslint(file, false)();

      // New file. Add it to the index of the package.
      if (old.indexOf(file) < 0) {
        writeIndex(dir)(done);
        old.push(file);
      }
    })
    .on('unlink', (name) => {
      const file = pathFromRoot(name);
      const dir = path.dirname(file);
      const oldi = old.indexOf(file);

      if (path.basename(file) === 'index.js')
        return;

      if (oldi >= 0) {
        writeIndex(dir)(done);
        old.splice(oldi, 1);
      }
    });
};

const create = () => function create(done) {
  const file = $.util.env.f;
  const test = $.util.env.t !== undefined ? $.util.env.t : file ? 'true' : 'false';
  const bench = $.util.env.b !== undefined ? $.util.env.b : 'false';
  const args = $.util.env.a !== undefined ? $.util.env.a.replace(/,/g, ', ') : undefined;
  const fail = (msg) => {
    log.error(msg);
    done();
  };
  const write = (what, file, name, pack, args) => {
    const contents = TEMPLATE[what]
      .replace(/{{name}}/g, name)
      .replace(/{{pack}}/g, pack)
      .replace(/{{args}}/g, args);

    fs.writeFileSync(file, contents);
  };

  if ((file !== undefined || test !== 'false') && args === undefined)
    return fail('no argument list defined');

  if (!file && test === true && !bench)
    return fail('nothing to do');

  if (file) {
    const [pack, fn, dir, fname] = fileInfo(file, '');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);
    if (fileExists(dir, fname))
      return fail(`file "${fname}" already exists`);

    write('src', path.join(dir, fname), fn, pack, args);
    writeIndex(dir)();
  }

  if (test !== 'false') {
    const name = file || test;
    const [pack, fn, dir, fname] = fileInfo(name, '_test');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);
    if (!fileExists(dir, `${fn}.js`))
      return fail(`source file of "${name}" not found`);
    if (fileExists(dir, fname))
      return fail(`file ${fname} already exists`);

    write('test', path.join(dir, fname), fn, pack, args);
  }

  if (bench !== 'false') {
    const name = file || bench;
    const [pack, fn, dir, fname] = fileInfo(name, '_bench');

    if (!packExists(pack))
      return fail(`package "${pack}" not found`);

    if (!fileExists(path.dirname(dir), pack))
      fs.mkdirSync(dir);

    if (fileExists(dir, fname))
      return fail(`file "${fname}" already exists`);

    write('bench', path.join(dir, fname), fn, pack, args);
  }

  done();
};

gulp.task('new', create());
gulp.task('mocha', mocha('all', false));
gulp.task('karma', karma());
gulp.task('eslint', eslint('all', false));
gulp.task('test', gulp.parallel(eslint('all', true), mocha('all', true)));
gulp.task('test-bundle', mocha('./build/bundle_test.js', true));
gulp.task('bundle-node', bundle('node', false));
gulp.task('bundle-next', bundle('next', false));
gulp.task('bundle', gulp.parallel('bundle-node', 'bundle-next'));
gulp.task('build', gulp.series(writeIndex('all'), 'test', 'bundle'));
gulp.task('benchmark', benchmark());
gulp.task('clean', clean());
gulp.task('dev', gulp.series(
  gulp.parallel(writeIndex('all'), 'eslint', 'mocha'),
  watchBuild()
));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var envify = require('envify');
var minifyCss = require('gulp-minify-css');
var gulpHtmlVersion = require('gulp-html-version');
var runSequence = require('run-sequence');

gulp.task('env-dev', function() {
    process.env.NODE_ENV = 'development';
});

gulp.task('env-prod', function() {
    process.env.NODE_ENV = 'production';
});

gulp.task('copy', function() {
    return gulp.src('src/*.html')
        .pipe(gulpHtmlVersion())
        .pipe(gulp.dest('www/'));
});

gulp.task('fonts', function() {
    return gulp.src('src/scss/fonts/*')
        .pipe(gulp.dest('www/fonts/'));
});

gulp.task('assets', function() {
    return gulp.src(['src/*.ico', 'src/*.png', 'src/manifest.json', 'src/google-services.json', 'src/GoogleService-Info.plist', 'src/*.svg', './node_modules/framework7/dist/js/framework7.min.js.map'])
        .pipe(gulp.dest('www/'));
});

gulp.task('images', function() {
    return gulp.src(['src/img/*', 'src/scss/img/*', 'src/scss/img/**/*'])
        .pipe(gulp.dest('www/img/'));
});

gulp.task('sass', function() {
    var paths = [
        './node_modules/framework7/dist/css/framework7.ios.css',
        './node_modules/Framework7-3D-Panels/dist/framework7.3dpanels.css',
        './node_modules/slick-carousel/slick/slick.css',
        './node_modules/react-image-crop/dist/ReactCrop.css',
        './node_modules/react-joyride/lib/styles/react-joyride-compiled.css',
        './node_modules/react-infinite-calendar/styles.css',
        './node_modules/rc-slider/assets/index.css',
        './src/scss/pages/*.scss',
        './src/scss/*.scss'
    ];

    return gulp.src(paths)
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest('./www/'))
        .pipe(connect.reload());
});

gulp.task('build-hello-js', function() {
    return gulp.src('./node_modules/hellojs/dist/hello.js')
        .pipe(gulp.dest('www/'));
});

gulp.task('build-js', function() {
    return browserify('./src/js/index.js')
        .transform(babelify)
        .transform(envify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./www'))
        .pipe(connect.reload());
});

gulp.task('build-service-worker', function() {
    return browserify('./src/js/firebase-messaging-sw.js')
        .transform(babelify)
        .bundle()
        .pipe(source('firebase-messaging-sw.js'))
        .pipe(gulp.dest('./www'))
        .pipe(connect.reload());
});

gulp.task('minify-js', ['build'], function() {
    return gulp.src('www/bundle.js')
        .pipe(uglify())
        .pipe(gulp.dest('./www'));
});

gulp.task('minify-css', ['sass'], function() {
    return gulp.src('www/bundle.css')
        .pipe(minifyCss())
        .pipe(gulp.dest('./www'));
});

// Rerun tasks whenever a file changes.
gulp.task('watch', ['build'], function() {
    gulp.watch('./src/scss/**/*', ['sass']);
    gulp.watch('./src/js/**/*', ['build-js']);
});

// Development
gulp.task('serve', function() {
    connect.server({
        root      : 'www',
        host      : '*',
        port      : 80,
        livereload: true
    });
});

gulp.task('build', ['copy', 'fonts', 'assets', 'images', 'sass', 'build-js', 'build-service-worker', 'build-hello-js']);
gulp.task('minify', ['minify-js', 'minify-css']);
gulp.task('release', ['env-prod'], function() {
    runSequence('minify');
});
gulp.task('build-dev', ['build', 'serve', 'watch']);
gulp.task('dev', ['env-dev'], function() {
    runSequence('build-dev');
});
<commit_msg>Fix react-joyride css file<commit_after>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var envify = require('envify');
var minifyCss = require('gulp-minify-css');
var gulpHtmlVersion = require('gulp-html-version');
var runSequence = require('run-sequence');

gulp.task('env-dev', function() {
    process.env.NODE_ENV = 'development';
});

gulp.task('env-prod', function() {
    process.env.NODE_ENV = 'production';
});

gulp.task('copy', function() {
    return gulp.src('src/*.html')
        .pipe(gulpHtmlVersion())
        .pipe(gulp.dest('www/'));
});

gulp.task('fonts', function() {
    return gulp.src('src/scss/fonts/*')
        .pipe(gulp.dest('www/fonts/'));
});

gulp.task('assets', function() {
    return gulp.src(['src/*.ico', 'src/*.png', 'src/manifest.json', 'src/google-services.json', 'src/GoogleService-Info.plist', 'src/*.svg', './node_modules/framework7/dist/js/framework7.min.js.map'])
        .pipe(gulp.dest('www/'));
});

gulp.task('images', function() {
    return gulp.src(['src/img/*', 'src/scss/img/*', 'src/scss/img/**/*'])
        .pipe(gulp.dest('www/img/'));
});

gulp.task('sass', function() {
    var paths = [
        './node_modules/framework7/dist/css/framework7.ios.css',
        './node_modules/Framework7-3D-Panels/dist/framework7.3dpanels.css',
        './node_modules/slick-carousel/slick/slick.css',
        './node_modules/react-image-crop/dist/ReactCrop.css',
        './node_modules/react-joyride/lib/react-joyride-compiled.css',
        './node_modules/react-infinite-calendar/styles.css',
        './node_modules/rc-slider/assets/index.css',
        './src/scss/pages/*.scss',
        './src/scss/*.scss'
    ];

    return gulp.src(paths)
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest('./www/'))
        .pipe(connect.reload());
});

gulp.task('build-hello-js', function() {
    return gulp.src('./node_modules/hellojs/dist/hello.js')
        .pipe(gulp.dest('www/'));
});

gulp.task('build-js', function() {
    return browserify('./src/js/index.js')
        .transform(babelify)
        .transform(envify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./www'))
        .pipe(connect.reload());
});

gulp.task('build-service-worker', function() {
    return browserify('./src/js/firebase-messaging-sw.js')
        .transform(babelify)
        .bundle()
        .pipe(source('firebase-messaging-sw.js'))
        .pipe(gulp.dest('./www'))
        .pipe(connect.reload());
});

gulp.task('minify-js', ['build'], function() {
    return gulp.src('www/bundle.js')
        .pipe(uglify())
        .pipe(gulp.dest('./www'));
});

gulp.task('minify-css', ['sass'], function() {
    return gulp.src('www/bundle.css')
        .pipe(minifyCss())
        .pipe(gulp.dest('./www'));
});

// Rerun tasks whenever a file changes.
gulp.task('watch', ['build'], function() {
    gulp.watch('./src/scss/**/*', ['sass']);
    gulp.watch('./src/js/**/*', ['build-js']);
});

// Development
gulp.task('serve', function() {
    connect.server({
        root      : 'www',
        host      : '*',
        port      : 80,
        livereload: true
    });
});

gulp.task('build', ['copy', 'fonts', 'assets', 'images', 'sass', 'build-js', 'build-service-worker', 'build-hello-js']);
gulp.task('minify', ['minify-js', 'minify-css']);
gulp.task('release', ['env-prod'], function() {
    runSequence('minify');
});
gulp.task('build-dev', ['build', 'serve', 'watch']);
gulp.task('dev', ['env-dev'], function() {
    runSequence('build-dev');
});
<|endoftext|>


<commit_before>var gulp = require("gulp"),
  connect = require("gulp-connect"),
  babel = require("gulp-babel"),
  react = require("gulp-react");

gulp.task("webserver", function () {
  connect.server({
    livereload: true,
  });
});

gulp.task("babel", function () {
  gulp.src("src/js/*.js")
  .pipe(babel())
  .pipe(gulp.dest("dist/"));
});

gulp.task("react", function () {
  gulp.src("src/jsx/*.jsx")
  .pipe(react())
  .pipe(gulp.dest("dist/"));
});

gulp.task("watch", function () {
  gulp.watch("src/js/*.js", ["babel"]);
  gulp.watch("src/jsx/*.jsx", ["react"]);
});

gulp.task("default", ["babel", "react", "webserver", "watch"]);
<commit_msg>Add sass support<commit_after>var gulp = require("gulp"),
  connect = require("gulp-connect"),
  babel = require("gulp-babel"),
  react = require("gulp-react"),
  sass = require("gulp-sass");

gulp.task("webserver", function () {
  connect.server({
    livereload: true,
  });
});

gulp.task("babel", function () {
  gulp.src("src/js/*.js")
  .pipe(babel())
  .pipe(gulp.dest("dist/"));
});

gulp.task("react", function () {
  gulp.src("src/jsx/*.jsx")
  .pipe(react())
  .pipe(gulp.dest("dist/"));
});

gulp.task("sass", function () {
  gulp.src("src/css/*.scss")
  .pipe(sass().on("error", sass.logError))
  .pipe(gulp.dest("dist/"));
});

gulp.task("watch", function () {
  gulp.watch("src/js/*.js", ["babel"]);
  gulp.watch("src/jsx/*.jsx", ["react"]);
  gulp.watch("src/css/*.scss", ["sass"]);
});

gulp.task("default", ["babel", "react", "sass", "webserver", "watch"]);
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Netflix, Inc.
 *
 * 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';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    karma = require('karma'),
    del = require('del'),
    bowerFiles = require('main-bower-files'),
    run = require('run-sequence'),

    dist = 'dist',
    app = 'app',
    styles = 'styles',
    scripts = 'scripts',
    views = 'views',
    images = 'images',
    fonts = 'fonts',

    development = process.env.NODE_ENV === 'dev',
    release = process.env.NODE_ENV === 'release',

    min = $.htmlmin({
      collapseWhitespace: true,
      conservativeCollapse: true,
      collapseBooleanAttributes: true,
      removeCommentsFromCDATA: true,
      removeOptionalTags: true
    });

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

gulp.task('test:ci', function(done) {
  karma.server.start({
    configFile: __dirname+'/karma.conf.js',
    browsers: ['Chrome'],
    singleRun: false,
  }, done);
});

gulp.task('test', ['test:karma']);

gulp.task('clean:fonts', function(done) {
  del([dist, fonts].join('/'), done);
});

// clean individual files by naming convention
['vendor', 'application'].forEach(function(item) {
  gulp.task('clean:'+styles+':'+item, function(done) {
    del([dist, styles, item+'*.css'].join('/'), done);
  });
});
['application', 'vendor', 'templates', 'settings'].forEach(function(item) {
  gulp.task('clean:'+scripts+':'+item, function(done) {
    del([
      [dist, scripts, item+'*.js'].join('/'),
      [dist, scripts, item+'*.js.map'].join('/'),
    ], done);
  });
});

gulp.task('clean', function(done) {
  del(dist, done);
});

// clean index.html
gulp.task('clean:html', function(done) {
  del([dist, 'index.html'].join('/'), done);
});

gulp.task('clean:static:bower', function(done) {
  del('dist/bower_components', done);
});

gulp.task('clean:static', function(done) {
  del([
    [dist, images].join('/'),
    [dist, '!(*.html)'].join('/'),
  ], done);
});

gulp.task('fonts', ['clean:fonts'], function() {
  return gulp.src([
    [app, fonts, '*/**'].join('/'),
    'bower_components/boostrap/dist/fonts/*.*',
  ]).pipe(gulp.dest([dist, fonts].join('/')));
});

gulp.task('static:bower', ['clean:static:bower'], function() {
  return gulp.src('bower_components/**/*').pipe(gulp.dest(dist+'/bower_components'));
});

gulp.task('static', ['clean:static', 'static:bower'], function() {
  return gulp.src([
    [app, images, '*/**'].join('/'),
    [app, '!(*.html)'].join('/'),
    'bower_components/**/*',
  ]).pipe(gulp.dest(dist));
});

gulp.task('html', ['clean:html'], function() {
  return gulp.src([app, 'index.html'].join('/'))
    .pipe($.inject(gulp.src([
      [dist, styles, 'vendor*.css'].join('/'),
      [dist, styles, '**/*.css'].join('/'),
      [dist, fonts, '**/*.css'].join('/'),
    ], {read: false}), {ignorePath: dist}))
    .pipe($.inject(gulp.src([
      [dist, scripts, 'vendor*.js'].join('/'),
      [dist, scripts, 'templates*.js'].join('/'),
      [dist, scripts, 'application*.js'].join('/'),
      [dist, scripts, 'settings*.js'].join('/'),
    ], {read: false}), {ignorePath: dist}))
    .pipe(gulp.dest(dist));
});

var prepareCss = function(src, out) {
  return src //.pipe($.sourcemaps.init({loadMaps: true}))
    .pipe($.less())
    .pipe($.concatCss(out))
    .pipe($.rev())
    .pipe($.if(release, $.cssmin()))
    // https://github.com/wearefractal/gulp-concat/issues/66
    //.pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest([dist, styles].join('/')));
};
gulp.task('css:vendor', ['clean:styles:vendor'], function() {
  return prepareCss(gulp.src([
    './bower_components/bootstrap/dist/css/bootstrap.css',
    './bower_components/select2-bootstrap-css/select2-bootstrap.css',
    './bower_components/select2/select2.css',
    './bower_components/angular-wizard/dist/angular-wizard.css'
  ], {base: 'styles/'}), 'vendor.css');
});
gulp.task('css:application', ['clean:styles:application'], function() {
  return prepareCss(gulp.src([app, styles, '**/*.less'].join('/')), 'application.css');
});
gulp.task('css', ['css:application', 'css:vendor']);

gulp.task('jshint', function() {
  return gulp.src([app, scripts, '**/*.js'].join('/'))
    .pipe($.if(!development, $.jshint()))
    .pipe($.if(!development, $.jshint.reporter('jshint-stylish')))
    .pipe($.if(!development, $.jshint.reporter('fail')));
});

var prepareJs = function(src, out) {
  return src.pipe($.if(!release, $.sourcemaps.init({loadMaps: true})))
    .pipe($.concat(out))
    .pipe($.if(!release, $.rev()))
    .pipe($.if(release, $.ngAnnotate()))
    .pipe($.if(release, $.uglify()))
    .pipe($.if(!release, $.sourcemaps.write('.')))
    .pipe(gulp.dest([dist, scripts].join('/')));
};
gulp.task('scripts:settings', ['clean:scripts:settings'], function() {
  return prepareJs(
    gulp.src([app, 'scripts', 'settings', 'settings.js'].join('/')), 'settings.js');
});
gulp.task('scripts:application', ['jshint', 'clean:scripts:application'], function() {
  return prepareJs(gulp.src([
    [app, scripts, 'app.js'].join('/'),
    [app, scripts, 'providers/*.js'].join('/'),
    [app, scripts, '**/!(settings).js'].join('/'),
  ]), 'application.js');
});
gulp.task('scripts:vendor', ['clean:scripts:vendor'], function() {
  return prepareJs(gulp.src(['bower_components/jquery/dist/jquery.js'].concat(bowerFiles({filter: /.*\.js/i}))), 'vendor.js');
});

gulp.task('scripts:templates', ['clean:scripts:templates'], function() {
  return gulp.src([app, views, '**/*.html'].join('/'))
    .pipe($.if(release, min))
    .pipe($.html2js({
      outputModuleName: 'deckApp.templates',
      useStrict: true,
      base: app,
    }))
    .pipe($.concat('templates.js'))
    .pipe($.if(!release, $.rev()))
    .pipe(gulp.dest([dist, scripts].join('/')));
});

gulp.task('scripts', ['scripts:application', 'scripts:vendor', 'scripts:templates', 'scripts:settings']);

gulp.task('connect', function() {
  $.connect.server({
    root: [dist],
    port: 9000,
    livereload: true,
    host: '0.0.0.0',
  });
});

gulp.task('build:prepare', ['scripts', 'css', 'fonts', 'static']);
gulp.task('build', ['clean'], function(done) {
  run('build:prepare', 'test:karma', 'html', done);
});

gulp.task('serve:prepare', ['build']);
gulp.task('serve', ['serve:prepare', 'connect', 'watch']);

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

gulp.task('watch', function() {
  gulp.watch('./app/views/**/*.html', function() {
    run('scripts:templates', 'html');
  });
  gulp.watch('./app/styles/**/*.less', function() {
    run('css:application', 'html');
  });
  gulp.watch('./app/scripts/**/*.js', function() {
    run('scripts:application', 'html', 'test:karma');
  });
  gulp.watch('./bower_components/**/*.js', function() {
    run('scripts:vendor', 'html');
  });
  gulp.watch('./bower_components/**/*.css', function() {
    run('css:vendor', 'html');
  });
  gulp.watch('./test/**/*', function() {
    run('test:karma');
  });
  $.watch([
    dist+'/scripts/**/*',
    dist+'/styles/**/*',
  ]).pipe($.connect.reload());
});

<commit_msg>clean/prepare build before starting test:ci<commit_after>/*
 * Copyright 2014 Netflix, Inc.
 *
 * 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';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    karma = require('karma'),
    del = require('del'),
    bowerFiles = require('main-bower-files'),
    run = require('run-sequence'),

    dist = 'dist',
    app = 'app',
    styles = 'styles',
    scripts = 'scripts',
    views = 'views',
    images = 'images',
    fonts = 'fonts',

    development = process.env.NODE_ENV === 'dev',
    release = process.env.NODE_ENV === 'release',

    min = $.htmlmin({
      collapseWhitespace: true,
      conservativeCollapse: true,
      collapseBooleanAttributes: true,
      removeCommentsFromCDATA: true,
      removeOptionalTags: true
    });

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

gulp.task('test:ci', function(done) {
  run(
    'clean',
    'build:prepare',
    function() {
      karma.server.start({
        configFile: __dirname+'/karma.conf.js',
        browsers: ['Chrome'],
        singleRun: false,
      }, done)
    }
  );
});

gulp.task('test', ['test:karma']);

gulp.task('clean:fonts', function(done) {
  del([dist, fonts].join('/'), done);
});

// clean individual files by naming convention
['vendor', 'application'].forEach(function(item) {
  gulp.task('clean:'+styles+':'+item, function(done) {
    del([dist, styles, item+'*.css'].join('/'), done);
  });
});
['application', 'vendor', 'templates', 'settings'].forEach(function(item) {
  gulp.task('clean:'+scripts+':'+item, function(done) {
    del([
      [dist, scripts, item+'*.js'].join('/'),
      [dist, scripts, item+'*.js.map'].join('/'),
    ], done);
  });
});

gulp.task('clean', function(done) {
  del(dist, done);
});

// clean index.html
gulp.task('clean:html', function(done) {
  del([dist, 'index.html'].join('/'), done);
});

gulp.task('clean:static:bower', function(done) {
  del('dist/bower_components', done);
});

gulp.task('clean:static', function(done) {
  del([
    [dist, images].join('/'),
    [dist, '!(*.html)'].join('/'),
  ], done);
});

gulp.task('fonts', ['clean:fonts'], function() {
  return gulp.src([
    [app, fonts, '*/**'].join('/'),
    'bower_components/boostrap/dist/fonts/*.*',
  ]).pipe(gulp.dest([dist, fonts].join('/')));
});

gulp.task('static:bower', ['clean:static:bower'], function() {
  return gulp.src('bower_components/**/*').pipe(gulp.dest(dist+'/bower_components'));
});

gulp.task('static', ['clean:static', 'static:bower'], function() {
  return gulp.src([
    [app, images, '*/**'].join('/'),
    [app, '!(*.html)'].join('/'),
    'bower_components/**/*',
  ]).pipe(gulp.dest(dist));
});

gulp.task('html', ['clean:html'], function() {
  return gulp.src([app, 'index.html'].join('/'))
    .pipe($.inject(gulp.src([
      [dist, styles, 'vendor*.css'].join('/'),
      [dist, styles, '**/*.css'].join('/'),
      [dist, fonts, '**/*.css'].join('/'),
    ], {read: false}), {ignorePath: dist}))
    .pipe($.inject(gulp.src([
      [dist, scripts, 'vendor*.js'].join('/'),
      [dist, scripts, 'templates*.js'].join('/'),
      [dist, scripts, 'application*.js'].join('/'),
      [dist, scripts, 'settings*.js'].join('/'),
    ], {read: false}), {ignorePath: dist}))
    .pipe(gulp.dest(dist));
});

var prepareCss = function(src, out) {
  return src //.pipe($.sourcemaps.init({loadMaps: true}))
    .pipe($.less())
    .pipe($.concatCss(out))
    .pipe($.rev())
    .pipe($.if(release, $.cssmin()))
    // https://github.com/wearefractal/gulp-concat/issues/66
    //.pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest([dist, styles].join('/')));
};
gulp.task('css:vendor', ['clean:styles:vendor'], function() {
  return prepareCss(gulp.src([
    './bower_components/bootstrap/dist/css/bootstrap.css',
    './bower_components/select2-bootstrap-css/select2-bootstrap.css',
    './bower_components/select2/select2.css',
    './bower_components/angular-wizard/dist/angular-wizard.css'
  ], {base: 'styles/'}), 'vendor.css');
});
gulp.task('css:application', ['clean:styles:application'], function() {
  return prepareCss(gulp.src([app, styles, '**/*.less'].join('/')), 'application.css');
});
gulp.task('css', ['css:application', 'css:vendor']);

gulp.task('jshint', function() {
  return gulp.src([app, scripts, '**/*.js'].join('/'))
    .pipe($.if(!development, $.jshint()))
    .pipe($.if(!development, $.jshint.reporter('jshint-stylish')))
    .pipe($.if(!development, $.jshint.reporter('fail')));
});

var prepareJs = function(src, out) {
  return src.pipe($.if(!release, $.sourcemaps.init({loadMaps: true})))
    .pipe($.concat(out))
    .pipe($.if(!release, $.rev()))
    .pipe($.if(release, $.ngAnnotate()))
    .pipe($.if(release, $.uglify()))
    .pipe($.if(!release, $.sourcemaps.write('.')))
    .pipe(gulp.dest([dist, scripts].join('/')));
};
gulp.task('scripts:settings', ['clean:scripts:settings'], function() {
  return prepareJs(
    gulp.src([app, 'scripts', 'settings', 'settings.js'].join('/')), 'settings.js');
});
gulp.task('scripts:application', ['jshint', 'clean:scripts:application'], function() {
  return prepareJs(gulp.src([
    [app, scripts, 'app.js'].join('/'),
    [app, scripts, 'providers/*.js'].join('/'),
    [app, scripts, '**/!(settings).js'].join('/'),
  ]), 'application.js');
});
gulp.task('scripts:vendor', ['clean:scripts:vendor'], function() {
  return prepareJs(gulp.src(['bower_components/jquery/dist/jquery.js'].concat(bowerFiles({filter: /.*\.js/i}))), 'vendor.js');
});

gulp.task('scripts:templates', ['clean:scripts:templates'], function() {
  return gulp.src([app, views, '**/*.html'].join('/'))
    .pipe($.if(release, min))
    .pipe($.html2js({
      outputModuleName: 'deckApp.templates',
      useStrict: true,
      base: app,
    }))
    .pipe($.concat('templates.js'))
    .pipe($.if(!release, $.rev()))
    .pipe(gulp.dest([dist, scripts].join('/')));
});

gulp.task('scripts', ['scripts:application', 'scripts:vendor', 'scripts:templates', 'scripts:settings']);

gulp.task('connect', function() {
  $.connect.server({
    root: [dist],
    port: 9000,
    livereload: true,
    host: '0.0.0.0',
  });
});

gulp.task('build:prepare', ['scripts', 'css', 'fonts', 'static']);
gulp.task('build', ['clean'], function(done) {
  run('build:prepare', 'test:karma', 'html', done);
});

gulp.task('serve:prepare', ['build']);
gulp.task('serve', ['serve:prepare', 'connect', 'watch']);

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

gulp.task('watch', function() {
  gulp.watch('./app/views/**/*.html', function() {
    run('scripts:templates', 'html');
  });
  gulp.watch('./app/styles/**/*.less', function() {
    run('css:application', 'html');
  });
  gulp.watch('./app/scripts/**/*.js', function() {
    run('scripts:application', 'html', 'test:karma');
  });
  gulp.watch('./bower_components/**/*.js', function() {
    run('scripts:vendor', 'html');
  });
  gulp.watch('./bower_components/**/*.css', function() {
    run('css:vendor', 'html');
  });
  gulp.watch('./test/**/*', function() {
    run('test:karma');
  });
  $.watch([
    dist+'/scripts/**/*',
    dist+'/styles/**/*',
  ]).pipe($.connect.reload());
});

<|endoftext|>


<commit_before>var elixir = require('laravel-elixir');

/* --------------------------------------------------------------------------
 *  Elixir Asset Management
 * --------------------------------------------------------------------------
 */
elixir(function(mix) {
    mix.less('app.less');
});
<commit_msg>Updating gulp file<commit_after>var gulp   = require('gulp'),
    elixir = require('laravel-elixir');

/* --------------------------------------------------------------------------
 *  General Configs
 * --------------------------------------------------------------------------
 */
var bowerDirectory        = './vendor/bower_components/',
    publicDirectory       = './www/assets/';

/* --------------------------------------------------------------------------
 *  Elixir Configs
 * --------------------------------------------------------------------------
 */
elixir.config.assetsDir   = 'resources/assets/';
elixir.config.cssOutput   = publicDirectory + 'css';
elixir.config.jsOutput    = publicDirectory + 'js';
elixir.config.bowerDir    = bowerDirectory;
elixir.config.sourcemaps  = false;
//elixir.config.production  = !! util.env.production;
//elixir.config.srcDir      = 'app';
//elixir.config.tasks       = [];
//elixir.config.watchers    = { default: {} };
//elixir.config.duplicate   = [];
//elixir.config.concatenate = {
//    css: [],
//    js: []
//};

/* --------------------------------------------------------------------------
 *  Elixir Asset Management
 * --------------------------------------------------------------------------
 */
elixir(function(mix) {
    // Publishing the fonts
    mix.copy([
        bowerDirectory + 'bootstrap/fonts',
        bowerDirectory + 'font-awesome/fonts'
    ], publicDirectory + 'fonts');

    // Compiling app scripts
    mix.scripts([
        bowerDirectory + 'jquery/dist/jquery.js',
        bowerDirectory + 'vue/dist/vue.js',
        bowerDirectory + 'bootstrap/dist/js/bootstrap.js'
    ], publicDirectory + 'js/vendors.js');

    mix.scripts('app.js', publicDirectory + 'js/app.js');

    // Compiling app styles
    mix.less('style.less', publicDirectory + 'css/style.css');
});
<|endoftext|>