<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var install = require('gulp-install');
var zip = require('gulp-zip');
var AWS = require('aws-sdk');
var fs = require('fs');
var base64 = require('gulp-base64');
var runSequence = require('run-sequence');
var packageDefinition = require('./package.json');
var awsConfig = require('./aws.json');

// Clean out the dist folder and remove the compiled zip file.
gulp.task('clean', function(cb) {
    del('./dist',
        del('./dist.zip', cb)
    );
});

gulp.task('js', function() {
    return gulp.src(['index.js'],{'base':'.'})
        .pipe(gulp.dest('dist/'))
});

gulp.task('templates', function() {
    return gulp.src('templates/**')
        .pipe(gulp.dest('./dist/templates'));
});

// Install npm packages to dist, ignoring devDependencies.
gulp.task('npm', function() {
    return gulp.src('./package.json')
        .pipe(gulp.dest('./dist/'))
        .pipe(install({production: true}));
});

// Zip the dist directory
gulp.task('zip', function() {
    return gulp.src(['dist/**/*', '!dist/package.json', 'dist/.*'])
        .pipe(zip('dist.zip'))
        .pipe(gulp.dest('./'));
});

// Per the gulp guidelines, we do not need a plugin for something that can be
// done easily with an existing node module. #CodeOverConfig
//
// Note: This presumes that AWS.config already has credentials. This will be
// the case if you have installed and configured the AWS CLI.
//
// See http://aws.amazon.com/sdk-for-node-js/
gulp.task('upload', function() {

    AWS.config.loadFromPath('./aws.json');
    var lambda = new AWS.Lambda();
    var functionName = packageDefinition.lambda.name;
    var handler = packageDefinition.lambda.handler;
    var role = packageDefinition.lambda.role;

    lambda.getFunction({FunctionName: functionName}, function(err, data) {
        if (err) {
            console.log(err);
            if (err.statusCode === 404) {
                var warning = 'Unable to find lambda function ' + functionName + '. Attempting to create it..'
                gutil.log(warning);
                var params = {
                    Code: {
                        ZipFile: fs.readFileSync('./dist.zip')
                    },
                    FunctionName: functionName,
                    Handler: handler,
                    Role: 'arn:aws:iam::' + awsConfig.accountId + ':role/' + role,
                    Runtime: 'nodejs',
                    Description: packageDefinition.description,
                    MemorySize: 128,
                    Timeout: 300
                };
                lambda.createFunction(params, function(err, data) {
                    if (err) gutil.log(err, err.stack); // an error occurred
                    else     gutil.log(data);           // successful response
                });

            } else {
                var warning = 'AWS API request failed. ';
                warning += 'Check your AWS credentials and permissions.';
                gutil.log(warning);
            }
        } else {
            // This is a bit silly, simply because these five parameters are required.
            var current = data.Configuration;
            var params = {
                FunctionName: functionName,
                ZipFile: fs.readFileSync('./dist.zip')
            };

            lambda.updateFunctionCode(params, function(err, data) {
                if (err) {
                    var warning = 'Package upload failed. '
                    warning += 'Check your iam:PassRole permissions.'
                    gutil.log(warning);
                } else {
                    gutil.log(data);
                }
            });
        }
    });
});

// The key to deploying as a single command is to manage the sequence of events.
gulp.task('default', function(callback) {
    return runSequence(
        'clean',
        'npm',
        'templates',
        'js',
        'zip',
        'upload',
        callback
    );
});<commit_msg>Config.son for managing email addresses<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var install = require('gulp-install');
var zip = require('gulp-zip');
var AWS = require('aws-sdk');
var fs = require('fs');
var base64 = require('gulp-base64');
var runSequence = require('run-sequence');
var packageDefinition = require('./package.json');
var awsConfig = require('./aws.json');

// Clean out the dist folder and remove the compiled zip file.
gulp.task('clean', function(cb) {
    del('./dist',
        del('./dist.zip', cb)
    );
});

gulp.task('js', function() {
    return gulp.src(['index.js','config.json'],{'base':'.'})
        .pipe(gulp.dest('dist/'))
});

gulp.task('templates', function() {
    return gulp.src('templates/**')
        .pipe(gulp.dest('./dist/templates'));
});

// Install npm packages to dist, ignoring devDependencies.
gulp.task('npm', function() {
    return gulp.src('./package.json')
        .pipe(gulp.dest('./dist/'))
        .pipe(install({production: true}));
});

// Zip the dist directory
gulp.task('zip', function() {
    return gulp.src(['dist/**/*', '!dist/package.json', 'dist/.*'])
        .pipe(zip('dist.zip'))
        .pipe(gulp.dest('./'));
});

// Per the gulp guidelines, we do not need a plugin for something that can be
// done easily with an existing node module. #CodeOverConfig
//
// Note: This presumes that AWS.config already has credentials. This will be
// the case if you have installed and configured the AWS CLI.
//
// See http://aws.amazon.com/sdk-for-node-js/
gulp.task('upload', function() {

    AWS.config.loadFromPath('./aws.json');
    var lambda = new AWS.Lambda();
    var functionName = packageDefinition.lambda.name;
    var handler = packageDefinition.lambda.handler;
    var role = packageDefinition.lambda.role;

    lambda.getFunction({FunctionName: functionName}, function(err, data) {
        if (err) {
            console.log(err);
            if (err.statusCode === 404) {
                var warning = 'Unable to find lambda function ' + functionName + '. Attempting to create it..'
                gutil.log(warning);
                var params = {
                    Code: {
                        ZipFile: fs.readFileSync('./dist.zip')
                    },
                    FunctionName: functionName,
                    Handler: handler,
                    Role: 'arn:aws:iam::' + awsConfig.accountId + ':role/' + role,
                    Runtime: 'nodejs',
                    Description: packageDefinition.description,
                    MemorySize: 128,
                    Timeout: 300
                };
                lambda.createFunction(params, function(err, data) {
                    if (err) gutil.log(err, err.stack); // an error occurred
                    else     gutil.log(data);           // successful response
                });

            } else {
                var warning = 'AWS API request failed. ';
                warning += 'Check your AWS credentials and permissions.';
                gutil.log(warning);
            }
        } else {
            // This is a bit silly, simply because these five parameters are required.
            var current = data.Configuration;
            var params = {
                FunctionName: functionName,
                ZipFile: fs.readFileSync('./dist.zip')
            };

            lambda.updateFunctionCode(params, function(err, data) {
                if (err) {
                    var warning = 'Package upload failed. '
                    warning += 'Check your iam:PassRole permissions.'
                    gutil.log(warning);
                } else {
                    gutil.log(data);
                }
            });
        }
    });
});

// The key to deploying as a single command is to manage the sequence of events.
gulp.task('default', function(callback) {
    return runSequence(
        'clean',
        'npm',
        'templates',
        'js',
        'zip',
        'upload',
        callback
    );
});<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');

var babelify = require('babelify');
var browserify = require('browserify');
var watchify = require('watchify');
var uglify = require('gulp-uglify');
var beautify = require('gulp-beautify');

var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulpif = require('gulp-if');
var runSequence = require('run-sequence');
var clean = require('gulp-clean');

const babel = require('gulp-babel');

var argv = require('yargs').argv;

gulp.task('default', function() {
    gulp.start('build-all');
});

gulp.task('build-all', function() {
    runSequence(
        'clean-lib',
        'build-lib',
        'build-cljs-lib',
        'clean-web',
        ['browserify', 'copy-css', 'copy-html'],
        'deploy-web');
});

gulp.task('clean-lib', function () {
    return gulp.src('./lib', {read: false})
        .pipe(clean());
});

gulp.task('build-lib', function() {
    return gulp.src(['src/**/*.js',
                     '!./src/require.js',
                     '!./src/react-grid-gallery.bundle.js'])
        .pipe(babel({
            presets: ['es2015', 'react']
        }))
        .pipe(gulp.dest('lib'));
});

gulp.task('clean-web', function () {
    return gulp.src('./examples/dist', {read: false})
        .pipe(clean());
});

gulp.task('deploy-web', function() {
    return gulp.src('./examples/dist/**/*')
        .pipe(ghPages());
});

gulp.task('copy-css', function () {
    return gulp.src('./examples/**/*.css')
        .pipe(gulp.dest('./examples/dist/css'));
});

gulp.task('copy-html', function () {
    return gulp.src('./examples/index.html')
        .pipe(gulp.dest('./examples/dist/'));
});

//uncomment watchify + on update for continuous build
gulp.task('browserify', function() {
    var bundle =
            //watchify(
        browserify('./examples/app.js', {
        extensions: ['.js', '.jsx'],
        })
//)
    ;
    bundle.transform(babelify, {'presets': ['es2015', 'react']});

    //bundle.on('update', function() {
    //    rebundle(bundle);
    //});

    function rebundle(bundle) {
        return bundle.bundle()
            .on('error', function(error) {
                console.log(error.stack, error.message);
                this.emit('end');
            })
            .pipe(gulpif(argv.dev, source('bundle.js'), source('bundle.min.js')))
            .pipe(buffer())
            .pipe(gulpif(argv.dev, beautify(), uglify()))
            .pipe(gulp.dest('examples/dist/js'));
    }
    return rebundle(bundle);
});

gulp.task('build-cljs-lib', function() {
    var bundle = browserify('./src/require.js', {
        extensions: ['.js', '.jsx'],
    });
    bundle.transform(babelify, {'presets': ['es2015', 'react']});
    bundle.on('update', function() {
        rebundle(bundle);
    });

    function rebundle(bundle) {
        return bundle.bundle()
            .on('error', function(error) {
                console.log(error.stack, error.message);
                this.emit('end');
            })
            .pipe(gulpif(argv.dev,
                         source('react-grid-gallery.bundle.js'),
                         source('react-grid-gallery.bundle.min.js')))
            .pipe(buffer())
            //.pipe(gulpif(argv.dev, beautify(), uglify()))
            .pipe(gulp.dest('lib'));
    }
    return rebundle(bundle);
});
<commit_msg>added two demos to examples<commit_after>'use strict';

var gulp = require('gulp');
var ghPages = require('gulp-gh-pages');

var babelify = require('babelify');
var browserify = require('browserify');
var watchify = require('watchify');
var uglify = require('gulp-uglify');
var beautify = require('gulp-beautify');

var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulpif = require('gulp-if');
var runSequence = require('run-sequence');
var clean = require('gulp-clean');

const babel = require('gulp-babel');

var argv = require('yargs').argv;

gulp.task('default', function() {
    gulp.start('build-all');
});

gulp.task('build-all', function() {
    runSequence(
        'clean-lib',
        'build-lib',
        'build-cljs-lib',
        'clean-web',
        ['browserify', 'copy-css', 'copy-html'],
        'deploy-web');
});

gulp.task('clean-lib', function () {
    return gulp.src('./lib', {read: false})
        .pipe(clean());
});

gulp.task('build-lib', function() {
    return gulp.src(['src/**/*.js',
                     '!./src/require.js',
                     '!./src/react-grid-gallery.bundle.js'])
        .pipe(babel({
            presets: ['es2015', 'react']
        }))
        .pipe(gulp.dest('lib'));
});

gulp.task('clean-web', function () {
    return gulp.src('./examples/dist', {read: false})
        .pipe(clean());
});

gulp.task('deploy-web', function() {
    return gulp.src('./examples/dist/**/*')
        .pipe(ghPages());
});

gulp.task('copy-css', function () {
    return gulp.src('./examples/**/*.css')
        .pipe(gulp.dest('./examples/dist/css'));
});

gulp.task('copy-html', function () {
    return gulp.src('./examples/index.html')
        .pipe(gulp.dest('./examples/dist/'));
});

//uncomment watchify + on update for continuous build
gulp.task('browserify', function() {
    var bundle =
            //watchify(
            browserify(['./examples/app.js',
                        './examples/demo1.js',
                        './examples/demo2.js'], {
        extensions: ['.js', '.jsx']
        })
//)
    ;
    bundle.transform(babelify, {'presets': ['es2015', 'react']});

    //bundle.on('update', function() {
    //    rebundle(bundle);
    //});

    function rebundle(bundle) {
        return bundle.bundle()
            .on('error', function(error) {
                console.log(error.stack, error.message);
                this.emit('end');
            })
            .pipe(gulpif(argv.dev, source('bundle.js'), source('bundle.min.js')))
            .pipe(buffer())
            .pipe(gulpif(argv.dev, beautify(), uglify()))
            .pipe(gulp.dest('examples/dist/js'));
    }
    return rebundle(bundle);
});

gulp.task('build-cljs-lib', function() {
    var bundle = browserify('./src/require.js', {
        extensions: ['.js', '.jsx'],
    });
    bundle.transform(babelify, {'presets': ['es2015', 'react']});
    bundle.on('update', function() {
        rebundle(bundle);
    });

    function rebundle(bundle) {
        return bundle.bundle()
            .on('error', function(error) {
                console.log(error.stack, error.message);
                this.emit('end');
            })
            .pipe(gulpif(argv.dev,
                         source('react-grid-gallery.bundle.js'),
                         source('react-grid-gallery.bundle.min.js')))
            .pipe(buffer())
            //.pipe(gulpif(argv.dev, beautify(), uglify()))
            .pipe(gulp.dest('lib'));
    }
    return rebundle(bundle);
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var rename = require('gulp-rename');
var jshint = require('gulp-jshint');
var mocha = require('gulp-spawn-mocha');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var coveralls = require('gulp-coveralls');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var glob = require('glob');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var babel = require('babelify');

var DEBUG = process.env.NODE_ENV === 'debug',
    CI = process.env.CI === 'true';

var paths = {
    test: ['./test/**/*.js', '!test/{temp,temp/**}'],
    source: ['./lib/*.js', './bin/*']
};
paths.lint = paths.source.concat(paths.test);

var plumberConf = {};

if (CI) {
    plumberConf.errorHandler = function(err) {
        throw err;
  };
}

gulp.task('lint', function() {
  return gulp.src(paths.lint)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('istanbul', function () {
  return gulp.src(paths.test, {read: false})
    .pipe(mocha({
      debugBrk: DEBUG,
      R: 'spec',
      istanbul: !DEBUG
    }));
});

gulp.task('test-browser', ['dist'], function () {
    return gulp.src('test/runner.html')
        .pipe(mochaPhantomJS({reporter: 'min'}));
});

gulp.task('dist-lib', function() {
    return browserify('./index.js', { standalone: 'bridge'})
        .transform(babel, {presets: ['es2015']})
        .ignore('fs')
        .ignore('stream')
        .bundle()
        .pipe(source('table-master-parser.js'))
        .pipe(gulp.dest('./dist/'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./dist/'));
});

gulp.task('dist-test', function (cb) {
  glob('./test/**/*.js', {}, function (err, files) {
    var b = browserify({standalone: 'spec'});
    files.forEach(function (file) {
        b.add(file);
    });
    b
        .transform(babel, {presets: ['es2015']})
        .ignore('fs')
        .ignore('stream')
        .bundle()
        .pipe(source('table-master-parser.spec.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./dist/'))
        .on('end', function() { cb(); });
  });
});

gulp.task('coverage', function () {
  return gulp.src('./coverage/lcov.info')
    .pipe(coveralls());
});

gulp.task('test',    ['lint', 'istanbul']);
gulp.task('dist',    ['dist-lib', 'dist-test']);
gulp.task('ci',      ['test', 'test-browser', 'dist']);
gulp.task('default', ['test']);
<commit_msg>fix(dist): wrong global name for the package<commit_after>'use strict';

var gulp = require('gulp');
var rename = require('gulp-rename');
var jshint = require('gulp-jshint');
var mocha = require('gulp-spawn-mocha');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var coveralls = require('gulp-coveralls');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var glob = require('glob');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var babel = require('babelify');

var DEBUG = process.env.NODE_ENV === 'debug',
    CI = process.env.CI === 'true';

var paths = {
    test: ['./test/**/*.js', '!test/{temp,temp/**}'],
    source: ['./lib/*.js', './bin/*']
};
paths.lint = paths.source.concat(paths.test);

var plumberConf = {};

if (CI) {
    plumberConf.errorHandler = function(err) {
        throw err;
  };
}

gulp.task('lint', function() {
  return gulp.src(paths.lint)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('istanbul', function () {
  return gulp.src(paths.test, {read: false})
    .pipe(mocha({
      debugBrk: DEBUG,
      R: 'spec',
      istanbul: !DEBUG
    }));
});

gulp.task('test-browser', ['dist'], function () {
    return gulp.src('test/runner.html')
        .pipe(mochaPhantomJS({reporter: 'min'}));
});

gulp.task('dist-lib', function() {
    return browserify('./index.js', { standalone: 'tableMasterParser'})
        .transform(babel, {presets: ['es2015']})
        .ignore('fs')
        .ignore('stream')
        .bundle()
        .pipe(source('table-master-parser.js'))
        .pipe(gulp.dest('./dist/'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./dist/'));
});

gulp.task('dist-test', function (cb) {
  glob('./test/**/*.js', {}, function (err, files) {
    var b = browserify({standalone: 'spec'});
    files.forEach(function (file) {
        b.add(file);
    });
    b
        .transform(babel, {presets: ['es2015']})
        .ignore('fs')
        .ignore('stream')
        .bundle()
        .pipe(source('table-master-parser.spec.js'))
        .pipe(gulp.dest('./dist'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./dist/'))
        .on('end', function() { cb(); });
  });
});

gulp.task('coverage', function () {
  return gulp.src('./coverage/lcov.info')
    .pipe(coveralls());
});

gulp.task('test',    ['lint', 'istanbul']);
gulp.task('dist',    ['dist-lib', 'dist-test']);
gulp.task('ci',      ['test', 'test-browser', 'dist']);
gulp.task('default', ['test']);
<|endoftext|>


<commit_before>"use strict";

var gulp = require('gulp'),
    boilerplate = require('appium-gulp-plugins').boilerplate.use(gulp),
    DEFAULTS = require('appium-gulp-plugins').boilerplate.DEFAULTS,
    _ = require('lodash');

boilerplate({
  build: 'appium-base-driver',
  jscs: false,
  testReporter: process.env.TRAVIS ? 'spec' : 'nyan',
  coverage: _.defaults({verbose: true}, DEFAULTS.coverage)
});
<commit_msg>using defaults in gulpfile<commit_after>"use strict";

var gulp = require('gulp'),
    boilerplate = require('appium-gulp-plugins').boilerplate.use(gulp);

boilerplate({
  build: 'appium-base-driver',
  jscs: false
});
<|endoftext|>


<commit_before>var gulp = require('gulp')
var g = require('gulp-load-plugins')()
var series = require('run-sequence')
var del = require('del')

var package_config = require('./package.json')
var fs = require('fs')
var EOL = require('os').EOL

var small_header = '// Alchemist.js v<%= version %> | license: <%= license %>' + EOL
var large_header = [
  '/**',
  ' * Alchemist.js',
  ' * v<%= version %>',
  ' * License: <%= license %>',
  ' *',
  ' * Author: <%= author %>',
  ' * Website: <%= homepage %>',
  ' */',
  EOL
].join(EOL)

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

gulp.task('build:min', function () {
  return gulp.src('dist/alchemist-*.js')
  .pipe(g.uglify())
  .pipe(g.header(small_header, package_config))
  .pipe(g.rename({ suffix: '.min' }))
  .pipe(gulp.dest('dist'))
  .pipe(g.size({ showFiles: true }))
  .pipe(g.size({ showFiles: true, gzip: true }))
})

gulp.task('build:web', function () {
  return gulp.src('lib/alchemist.js')
  .pipe(g.webpack({
    output: {
      filename: 'alchemist.js',
      library: 'Alchemist',
      libraryTarget: 'umd',
      sourcePrefix: '' } }))
      .pipe(g.header(large_header, package_config))
      .pipe(g.rename({ suffix: '-' + package_config.version }))
      .pipe(gulp.dest('dist'))
})

gulp.task('build', function (cb) {
  series('clean', 'build:web', 'build:min', cb)
})

gulp.task('test:run', function () {
  return gulp.src('test/*.js')
  .pipe(g.mocha({ reporter: 'spec' }))
  .on('error', warn)
})

gulp.task('test', function (cb) {
  series('test:run', 'lint', cb)
})

gulp.task('lint', function () {
  return gulp.src(['gulpfile.js', 'test/*.js', 'alchemist.js'])
  .pipe(g.jscs())
  .on('error', warn)
})

gulp.task('watch:lint', ['lint'], function () {
  gulp.watch(['gulpfile.js', '.jscsrc', 'test/*.js', 'alchemist.js'], ['lint'])
})

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

gulp.task('default', ['build'])

function warn (err) {
  console.warn(err.message)
  this.emit('end')
}
<commit_msg>removed unecessary fs require from gulpfile<commit_after>var gulp = require('gulp')
var g = require('gulp-load-plugins')()
var series = require('run-sequence')
var del = require('del')

var package_config = require('./package.json')
var EOL = require('os').EOL

var small_header = '// Alchemist.js v<%= version %> | license: <%= license %>' + EOL
var large_header = [
  '/**',
  ' * Alchemist.js',
  ' * v<%= version %>',
  ' * License: <%= license %>',
  ' *',
  ' * Author: <%= author %>',
  ' * Website: <%= homepage %>',
  ' */',
  EOL
].join(EOL)

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

gulp.task('build:min', function () {
  return gulp.src('dist/alchemist-*.js')
  .pipe(g.uglify())
  .pipe(g.header(small_header, package_config))
  .pipe(g.rename({ suffix: '.min' }))
  .pipe(gulp.dest('dist'))
  .pipe(g.size({ showFiles: true }))
  .pipe(g.size({ showFiles: true, gzip: true }))
})

gulp.task('build:web', function () {
  return gulp.src('lib/alchemist.js')
  .pipe(g.webpack({
    output: {
      filename: 'alchemist.js',
      library: 'Alchemist',
      libraryTarget: 'umd',
      sourcePrefix: '' } }))
      .pipe(g.header(large_header, package_config))
      .pipe(g.rename({ suffix: '-' + package_config.version }))
      .pipe(gulp.dest('dist'))
})

gulp.task('build', function (cb) {
  series('clean', 'build:web', 'build:min', cb)
})

gulp.task('test:run', function () {
  return gulp.src('test/*.js')
  .pipe(g.mocha({ reporter: 'spec' }))
  .on('error', warn)
})

gulp.task('test', function (cb) {
  series('test:run', 'lint', cb)
})

gulp.task('lint', function () {
  return gulp.src(['gulpfile.js', 'test/*.js', 'alchemist.js'])
  .pipe(g.jscs())
  .on('error', warn)
})

gulp.task('watch:lint', ['lint'], function () {
  gulp.watch(['gulpfile.js', '.jscsrc', 'test/*.js', 'alchemist.js'], ['lint'])
})

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

gulp.task('default', ['build'])

function warn (err) {
  console.warn(err.message)
  this.emit('end')
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    config = require('./frontplate');
    $ = require('gulp-load-plugins')({
        pattern: ['gulp-*', 'gulp.*'],
        replaceString: /\bgulp[\-.]/
    });

$.browser = require('browser-sync');

var BASE_TYPE;
var BASE_PATH;
var MINIFY;

if (config.flatten) {
    BASE_TYPE = '';
    BASE_PATH = config.APP_PATH;
} else {
    BASE_TYPE = process.argv.indexOf('-sp') === -1 ? 'pc' : 'sp';
    BASE_PATH = config.APP_PATH + '/' + BASE_TYPE;
}
if (config.debug) {
    MINIFY = process.argv.indexOf('-min') === -1 ? false : true;
} else {
    MINIFY = true;
}

/**
 * パス生成関数
 * @param name
 * @param prop
 * @returns {string}
 */
function getPath(name,prop) {
    prop = prop || 'src';
    var path = config.path[name][prop];
    if (typeof path === 'object') {
        return path.map(function(val) {
            if (val.charAt(0) === '!') {
                return '!' + BASE_PATH + '/' + val.substring(1);
            }
            return BASE_PATH + '/' + val;
        })
    } else {
        path = path || '';
        return BASE_PATH + '/' + path;
    }
}

// globalに共通変数書き出し
global.frontplate = {
    plugins: $,
    config: config,
    getPath: getPath,
    BASE_TYPE: BASE_TYPE,
    BASE_PATH: BASE_PATH,
    MINIFY: MINIFY
};

gulp.task('watch', function() {
    gulp.watch(getPath('js'), ['jshint']);
    gulp.watch(getPath('ejs','watch'), ['ejs']);
    gulp.watch(getPath('iconfont'), ['iconfont','style']);
    gulp.watch(getPath('sass'), ['style']);
    gulp.watch(getPath('html'), ['htmllint']);
    gulp.watch(getPath('sprite','watch'), ['sprite']);
});

// gulpディレクトリのタスク読み込み
var tasks = require('./gulp/load');
gulp.task('default',['script','style','server','watch','watchScript'], function() {});
<commit_msg>監視子ディレクトリを配列から生成するように変更<commit_after>var gulp = require('gulp'),
    config = require('./config');
    $ = require('gulp-load-plugins')({
        pattern: ['gulp-*', 'gulp.*'],
        replaceString: /\bgulp[\-.]/
    });

$.browser = require('browser-sync');

var DIRECTORIES = ['pc','sp','admin'];
var BASE_TYPE = getBaseType();
var BASE_PATH = getBasePath();
var MINIFY = process.argv.indexOf('-min') === -1 ? false : true;

function getBasePath() {
    var path = config.APP_PATH;
    if (!config.flatten) {
        path += '/' + BASE_TYPE;
    }
    return path;
}

function getBaseType() {
    var type = '';
    if (!config.flatten) {
        for (var i = 0, len = DIRECTORIES.length; i < len; i++) {
            if (process.argv.indexOf('-' + DIRECTORIES[i]) !== -1) {
                type = DIRECTORIES[i];
                break;
            }
        }
        if (!type) {
            type = DIRECTORIES[0];
        }
    }
    return type;
}

/**
 * パス生成関数
 * @param name
 * @param prop
 * @returns {string}
 */
function getPath(name,prop) {
    prop = prop || 'src';
    var path = config.path[name][prop];
    if (typeof path === 'object') {
        return path.map(function(val) {
            if (val.charAt(0) === '!') {
                return '!' + BASE_PATH + '/' + val.substring(1);
            }
            return BASE_PATH + '/' + val;
        })
    } else {
        path = path || '';
        return BASE_PATH + '/' + path;
    }
}

// globalに共通変数書き出し
global.frontplate = {
    plugins: $,
    config: config,
    getPath: getPath,
    BASE_TYPE: BASE_TYPE,
    BASE_PATH: BASE_PATH,
    MINIFY: MINIFY
};

gulp.task('watch', function() {
    gulp.watch(getPath('js'), ['jshint']);
    gulp.watch(getPath('ejs','watch'), ['ejs']);
    gulp.watch(getPath('iconfont'), ['iconfont','style']);
    gulp.watch(getPath('sass'), ['style']);
    gulp.watch(getPath('html'), ['htmllint']);
    gulp.watch(getPath('sprite','watch'), ['sprite']);
});

// gulpディレクトリのタスク読み込み
var tasks = require('./gulp/load');
gulp.task('default',['script','style','server','watch','watchScript'], function() {});<|endoftext|>


<commit_before>var gulp = require('gulp');
var plumber = require('gulp-plumber');
var to5 = require('gulp-6to5');
var changed = require('gulp-changed');
var browserSync = require('browser-sync');
var jshint = require('gulp-jshint');
var runSequence = require('run-sequence');
var vinylPaths = require('vinyl-paths');
var del = require('del');
var stylish = require('jshint-stylish');
var assign = Object.assign || require('object.assign');
var sourcemaps = require("gulp-sourcemaps");
var ngHtml2Js = require("gulp-ng-html2js");
var htmlMin = require('gulp-minify-html');
var builder = require('systemjs-builder');
var RSVP = require('rsvp');
var less = require('gulp-less');
var karma = require('karma').server;
var insert = require('gulp-insert');
var ngAnnotate = require('gulp-ng-annotate');
var fs = require('fs');

var compilerOptions = {
  filename: '',
  filenameRelative: '',
  blacklist: [],
  whitelist: [],
  //modules: 'system',
  //sourceMap: true,
  //sourceMapName: '',
  //sourceFileName: '',
  sourceRoot: '',
  moduleRoot: '',
  moduleIds: false,
  runtime: false,
  experimental: false,
  format: {
    comments: false,
    compact: false,
    indent: {
      parentheses: true,
      adjustMultilineComment: true,
      style: "  ",
      base: 0
    }
  }
};

var path = {
  source:'src/**/*.js',
  html:'**/*.html',
  templates: 'src/**/*.html',
  less: 'src/**/*.less',
  output:'dist/'
};

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

gulp.task('clean', function() {
  return gulp.src([path.output])
    .pipe(vinylPaths(del));
});

gulp.task('html', function () {
  return gulp.src(path.templates)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.html'}))
    .pipe(htmlMin({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe(ngHtml2Js())

    // not entirely sure this is needed....
    .pipe(insert.prepend("import angular from 'angular';\n"))
    .pipe(to5(compilerOptions))

    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('less', function () {
  return gulp.src(path.less)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.less'}))
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('es6', function () {
  return gulp.src(path.source)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.js'}))
    .pipe(sourcemaps.init())
    .pipe(to5(compilerOptions))
    .pipe(ngAnnotate())
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('compile', function(callback) {
  return runSequence(
    'clean',
    ['less', 'html', 'es6', 'move'],
    callback
  );
});

gulp.task('lint', function() {
  return gulp.src(path.source)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('move', function(){
  return gulp.src('./src/**/*.json')
    .pipe(changed(path.output, {extension: '.json'}))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('serve', ['compile'], function(done) {
  browserSync({
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  }, done);
});

gulp.task('iis', ['compile'], function(done) {
  browserSync({
    proxy: "windows.local"
  }, done);
});

gulp.task('watch', ['serve'], function() {
  var watcher = gulp.watch([path.source, path.html], ['compile']);
  watcher.on('change', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  });
});

gulp.task('steal', ['compile'], function(){
  var steal = require('steal-tools');
  steal.build({
    main: 'app/app',
    config: 'system.config.js'
  }, {
    minify: false,
    bundleSteal: false,
    bundle: ['app/login/login',
      'app/admin/admin',
      'app/dashboard/dashboard',
      'app/forms/forms']
  })
});

gulp.task('builder' , function(){
  var builder = require('./build/build');
  var routes = require('./src/app/routes.json');

  // just get the source of our routes
  routes = routes.map(function(r){
    return r.src;
  });

  builder.build({
    main: 'app/app',
    config: './system.config.js',
    bundles: routes
  });
});

gulp.task('depBuilder', ['compile'], function(){
  var depBuilder = require('./build/dep-builder');
  var routes = require('./src/app/routes.json');

  // just get the source of our routes
  routes = routes.map(function(r){
    return r.src;
  });
  var appTree;
  var routeTrees = [];
  var promises = [];
  promises.push(new RSVP.Promise(function(resolve, reject) {
    depBuilder.build({
      main: 'app/app',
      config: './system.config.js'
    }).then(function(tree){
      appTree = tree;
      resolve();
    });
  }));

  routes.forEach(function(route){
    promises.push(new RSVP.Promise(function(resolve, reject) {
      depBuilder.build({
        main: route,
        config: './system.config.js'
      }).then(function(tree){
        routeTrees.push(tree);
        resolve();
      });
    }));
  })

  RSVP.all(promises).then(function() {
    console.log('got all trees');

    // Removing app tree dependencies from route trees;
    Object.keys(appTree).forEach(function(moduleName){
      console.log('removing ' + moduleName);

      routeTrees.forEach(function(treeIndex){
        if (treeIndex[moduleName]){
          // deleting the dep tree
          delete treeIndex[moduleName];
          // removing dep from the other trees
          Object.keys(treeIndex).forEach(function(depName){
            treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, appTree[moduleName].tree);
          });
        }
      });
    });

    // generating inverse index of dependencies
    var bundles = {};
    var inverseIndex = {};
    routeTrees.forEach(function(treeIndex, i){
      Object.keys(treeIndex).forEach(function(depName){
        if (inverseIndex[depName] === undefined){
          inverseIndex[depName] = [i];
        } else {
          inverseIndex[depName].push(i);
        }
      });
    });

    console.log('removed shared dependencies');
    // generating bundles
    Object.keys(inverseIndex).forEach(function(moduleName){
      console.log('---------------------------')
      console.log('processing ' + moduleName)
      // if it's included in only one route, leave it there
      if (inverseIndex[moduleName].length == 1){
        console.log('not a shared dependency - skipping')
        return;
      }

      var module = routeTrees[inverseIndex[moduleName][0]][moduleName];
      if (inverseIndex[moduleName].length / routeTrees.length >= 0.6){
        // if it's included in more than 60% of the routes, put it in app
        console.log('shared in more than 60% - including in app');
        appTree['app/app'].tree = builder.addTrees(appTree['app/app'].tree, module.tree);
        appTree[moduleName] = module;

      } else {
        // otherwise, put it in a bundle
        var bundleName = inverseIndex[moduleName].sort().join('-');
        console.log('creating bundle ' + bundleName);
        if (bundles[bundleName] === undefined){
          bundles[bundleName] = module;
        } else {
          bundles[bundleName].tree = builder.addTrees(bundles[bundleName].tree, module.tree);
        }
      }

      // remove from other trees;
      inverseIndex[moduleName].forEach(function(index){
        var treeIndex = routeTrees[index];
        delete treeIndex[moduleName];

        Object.keys(treeIndex).forEach(function(depName){
          treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, module.tree);
        });

      })
    });

    console.log('building...');
    // build bundles
    var bundlesConfig = {};
    Object.keys(bundles).forEach(function(bundleName) {
      buildTree(bundles[bundleName], "bundles/" + bundleName);
      bundlesConfig["bundles/" + bundleName] = Object.keys(bundles[bundleName].tree);
    });
    // build route trees
    routeTrees.forEach(function(treeIndex){
      Object.keys(treeIndex).forEach(function(moduleName) {
        buildTree(treeIndex[moduleName], moduleName);
      });
    });
    // build root app
    Object.keys(appTree).forEach(function(moduleName) {
      buildTree(appTree[moduleName], moduleName).then(function(){
        if (moduleName === 'app/app'){
          var bundlesString = "System.bundles = " + JSON.stringify(bundlesConfig) + ";";

          gulp.src('dist/app/app.js')
            .pipe(insert.prepend(bundlesString))
            .pipe(gulp.dest('dist/app'));
        }
      })
    });

    console.log('build successful!')
  });

  var buildTree = function(tree, destination){
    if (destination.indexOf('bower_components') != 0){
      return builder.buildTree(tree.tree, 'dist/' + destination + '.js', {
        sourceMaps: true
        //minify: true
      })
    }
  }

});
<commit_msg>fix for less<commit_after>var gulp = require('gulp');
var plumber = require('gulp-plumber');
var to5 = require('gulp-6to5');
var changed = require('gulp-changed');
var browserSync = require('browser-sync');
var jshint = require('gulp-jshint');
var runSequence = require('run-sequence');
var vinylPaths = require('vinyl-paths');
var del = require('del');
var stylish = require('jshint-stylish');
var assign = Object.assign || require('object.assign');
var sourcemaps = require("gulp-sourcemaps");
var ngHtml2Js = require("gulp-ng-html2js");
var htmlMin = require('gulp-minify-html');
var builder = require('systemjs-builder');
var RSVP = require('rsvp');
var less = require('gulp-less');
var karma = require('karma').server;
var insert = require('gulp-insert');
var ngAnnotate = require('gulp-ng-annotate');
var fs = require('fs');

var compilerOptions = {
  filename: '',
  filenameRelative: '',
  blacklist: [],
  whitelist: [],
  //modules: 'system',
  //sourceMap: true,
  //sourceMapName: '',
  //sourceFileName: '',
  sourceRoot: '',
  moduleRoot: '',
  moduleIds: false,
  runtime: false,
  experimental: false,
  format: {
    comments: false,
    compact: false,
    indent: {
      parentheses: true,
      adjustMultilineComment: true,
      style: "  ",
      base: 0
    }
  }
};

var path = {
  source:'src/**/*.js',
  html:'**/*.html',
  templates: 'src/**/*.html',
  less: 'src/**/*.less',
  output:'dist/'
};

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

gulp.task('clean', function() {
  return gulp.src([path.output])
    .pipe(vinylPaths(del));
});

gulp.task('html', function () {
  return gulp.src(path.templates)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.html'}))
    .pipe(htmlMin({
      empty: true,
      spare: true,
      quotes: true
    }))
    .pipe(ngHtml2Js())

    // not entirely sure this is needed....
    .pipe(insert.prepend("import angular from 'angular';\n"))
    .pipe(to5(compilerOptions))

    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('less', function () {
  return gulp.src(path.less)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.less'}))
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('move-json', function () {
    return gulp.src('./src/**/*.json')
      .pipe(changed(path.output, { extension: '.json' }))
      .pipe(gulp.dest(path.output))
      .pipe(browserSync.reload({ stream: true }));
});

// todo...
gulp.task('move-less', function () {
    return gulp.src('./src/**/*.less')
      .pipe(changed(path.output, { extension: '.less' }))
      .pipe(gulp.dest(path.output))
      .pipe(browserSync.reload({ stream: true }));
});

gulp.task('es6', function () {
  return gulp.src(path.source)
    .pipe(plumber())
    .pipe(changed(path.output, {extension: '.js'}))
    .pipe(sourcemaps.init())
    .pipe(to5(compilerOptions))
    .pipe(ngAnnotate())
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest(path.output))
    .pipe(browserSync.reload({ stream: true }));
});

gulp.task('compile', function(callback) {
  return runSequence(
    'clean',
    //['less', 'html', 'es6', 'move'],
    ['html', 'es6', 'move-json', 'move-less'],
    callback
  );
});

gulp.task('lint', function() {
  return gulp.src(path.source)
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('serve', ['compile'], function(done) {
  browserSync({
    open: false,
    port: 9000,
    server: {
      baseDir: ['.'],
      middleware: function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      }
    }
  }, done);
});

gulp.task('iis', ['compile'], function(done) {
  browserSync({
    proxy: "windows.local"
  }, done);
});

gulp.task('watch', ['serve'], function() {
  var watcher = gulp.watch([path.source, path.html], ['compile']);
  watcher.on('change', function(event) {
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
  });
});

gulp.task('steal', ['compile'], function(){
  var steal = require('steal-tools');
  steal.build({
    main: 'app/app',
    config: 'system.config.js'
  }, {
    minify: false,
    bundleSteal: false,
    bundle: ['app/login/login',
      'app/admin/admin',
      'app/dashboard/dashboard',
      'app/forms/forms']
  })
});

gulp.task('builder' , function(){
  var builder = require('./build/build');
  var routes = require('./src/app/routes.json');

  // just get the source of our routes
  routes = routes.map(function(r){
    return r.src;
  });

  builder.build({
    main: 'app/app',
    config: './system.config.js',
    bundles: routes
  });
});

gulp.task('depBuilder', ['compile'], function(){
  var depBuilder = require('./build/dep-builder');
  var routes = require('./src/app/routes.json');

  // just get the source of our routes
  routes = routes.map(function(r){
    return r.src;
  });
  var appTree;
  var routeTrees = [];
  var promises = [];
  promises.push(new RSVP.Promise(function(resolve, reject) {
    depBuilder.build({
      main: 'app/app',
      config: './system.config.js'
    }).then(function(tree){
      appTree = tree;
      resolve();
    });
  }));

  routes.forEach(function(route){
    promises.push(new RSVP.Promise(function(resolve, reject) {
      depBuilder.build({
        main: route,
        config: './system.config.js'
      }).then(function(tree){
        routeTrees.push(tree);
        resolve();
      });
    }));
  })

  RSVP.all(promises).then(function() {
    console.log('got all trees');

    // Removing app tree dependencies from route trees;
    Object.keys(appTree).forEach(function(moduleName){
      console.log('removing ' + moduleName);

      routeTrees.forEach(function(treeIndex){
        if (treeIndex[moduleName]){
          // deleting the dep tree
          delete treeIndex[moduleName];
          // removing dep from the other trees
          Object.keys(treeIndex).forEach(function(depName){
            treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, appTree[moduleName].tree);
          });
        }
      });
    });

    // generating inverse index of dependencies
    var bundles = {};
    var inverseIndex = {};
    routeTrees.forEach(function(treeIndex, i){
      Object.keys(treeIndex).forEach(function(depName){
        if (inverseIndex[depName] === undefined){
          inverseIndex[depName] = [i];
        } else {
          inverseIndex[depName].push(i);
        }
      });
    });

    console.log('removed shared dependencies');
    // generating bundles
    Object.keys(inverseIndex).forEach(function(moduleName){
      console.log('---------------------------')
      console.log('processing ' + moduleName)
      // if it's included in only one route, leave it there
      if (inverseIndex[moduleName].length == 1){
        console.log('not a shared dependency - skipping')
        return;
      }

      var module = routeTrees[inverseIndex[moduleName][0]][moduleName];
      if (inverseIndex[moduleName].length / routeTrees.length >= 0.6){
        // if it's included in more than 60% of the routes, put it in app
        console.log('shared in more than 60% - including in app');
        appTree['app/app'].tree = builder.addTrees(appTree['app/app'].tree, module.tree);
        appTree[moduleName] = module;

      } else {
        // otherwise, put it in a bundle
        var bundleName = inverseIndex[moduleName].sort().join('-');
        console.log('creating bundle ' + bundleName);
        if (bundles[bundleName] === undefined){
          bundles[bundleName] = module;
        } else {
          bundles[bundleName].tree = builder.addTrees(bundles[bundleName].tree, module.tree);
        }
      }

      // remove from other trees;
      inverseIndex[moduleName].forEach(function(index){
        var treeIndex = routeTrees[index];
        delete treeIndex[moduleName];

        Object.keys(treeIndex).forEach(function(depName){
          treeIndex[depName].tree = builder.subtractTrees(treeIndex[depName].tree, module.tree);
        });

      })
    });

    console.log('building...');
    // build bundles
    var bundlesConfig = {};
    Object.keys(bundles).forEach(function(bundleName) {
      buildTree(bundles[bundleName], "bundles/" + bundleName);
      bundlesConfig["bundles/" + bundleName] = Object.keys(bundles[bundleName].tree);
    });
    // build route trees
    routeTrees.forEach(function(treeIndex){
      Object.keys(treeIndex).forEach(function(moduleName) {
        buildTree(treeIndex[moduleName], moduleName);
      });
    });
    // build root app
    Object.keys(appTree).forEach(function(moduleName) {
      buildTree(appTree[moduleName], moduleName).then(function(){
        if (moduleName === 'app/app'){
          var bundlesString = "System.bundles = " + JSON.stringify(bundlesConfig) + ";";

          gulp.src('dist/app/app.js')
            .pipe(insert.prepend(bundlesString))
            .pipe(gulp.dest('dist/app'));
        }
      })
    });

    console.log('build successful!')
  });

  var buildTree = function(tree, destination){
    if (destination.indexOf('bower_components') != 0){
      return builder.buildTree(tree.tree, 'dist/' + destination + '.js', {
        sourceMaps: true
        //minify: true
      })
    }
  }

});
<|endoftext|>


<commit_before>(function () {
   'use strict';
   var gulp = require('gulp'),

   fs = require('fs'),

   awspublish = require('gulp-awspublish'),

   rename = require('gulp-rename'),

   concat = require('gulp-concat'),

   uglify = require('gulp-uglify'),

   color = require('cli-color'),

   rename = require('gulp-rename'),

   notify = require('gulp-notify'),

   jshint = require('gulp-jshint'),

   stripDebug = require('gulp-strip-debug'),

   sourcemaps = require('gulp-sourcemaps'),

   sass = require('gulp-ruby-sass'),

   cssnano = require('gulp-cssnano'),

   htmlReplace = require('gulp-html-replace'),

   del = require('del'),

   replace = require('gulp-replace'),

   install = require('gulp-install'),

   path = require('path'),

   gulpFile = require('gulp-file'),

   foreach = require('gulp-foreach'),

   json_merger = require('json_merger'),

   jsonminify = require('gulp-jsonminify'),

   merge_stream = require('merge-stream'),

   run_sequence = require('run-sequence'),

   babel = require('gulp-babel'),

   jscs = require('gulp-jscs'),

   buildTemp = '.buildTemp',

   compiledTemp = '.compiledTemp';

   var buildParameters = JSON.parse(fs.readFileSync('./buildparameters.json'));

   /**
    * Copies project configuration files from the build tools into the project
    * The files are: .gitignore, .jshintrc, .editorconfig, config.rb
    */
   gulp.task('copy-config-files', function () {
      // .gitignore has special handling because npm strips .gitignore files
      // when downloading dependencies
      return gulp.src([
            './node_modules/widget-build-tools/widget_config/gitignore',
            './node_modules/widget-build-tools/widget_config/.editorconfig',
            './node_modules/widget-build-tools/widget_config/.jshintrc',
            './node_modules/widget-build-tools/widget_config/.jscsrc',
            './node_modules/widget-build-tools/widget_config/config.rb'
         ])
         .pipe(rename(function (path) {
            if (path.basename === 'gitignore') {
               path.basename = '.gitignore';
            }
         }))
         .pipe(gulp.dest('./'));
   });

   /**
    * Cleans the project (deletes compiledTemp, /dist/ and buildTemp folders)
    */
   gulp.task('clean', function () {
      del.sync(compiledTemp);
      del.sync('.dist');
      return del.sync(buildTemp);
   });

   /**
    * Cleans then builds
    */
   gulp.task('default', ['clean'], function () {
      return gulp.start('build');
   });

   /**
    * Tasks used by 'build' to run everything in the right order
    */
   gulp.task('build2', ['copy-config-files'], function () {
      gulp.start('build3');
   });
   gulp.task('build3', ['compile'], function () {
      gulp.start('build4');
   });
   gulp.task('build4', ['html-replace', 'css-concat', 'js-concat']);

   /**
    * Full build cycle with compilling and minifying
    */
   gulp.task('build', ['build2']);

   /**
    * Replaces references inside index.html to reference the minified and concatanated
    * js and css files
    */
   gulp.task('html-replace', function () {
      var references = extendObj(
         {
            css: 'css/app.min.css',
            js: 'js/app.min.js'
         },
         buildParameters.htmlReplace
      );
      return gulp.src('./' + compiledTemp + '/index.html')
         .pipe(htmlReplace(references))
         .pipe(gulp.dest('./dist'));
   });

   gulp.task('publish', ['build'], function () {
      var publisher = awspublish.create({
         params: {
            Bucket: 'kambi-widgets'
         }
      });

      var headers = {};

      return gulp.src(['./dist/**/*'])
         .pipe(rename(function (path) {
            path.dirname = '/' + buildParameters.awsPublishPath + '/' + path.dirname;
         }))
         .pipe(publisher.publish(headers, {}))
         .pipe(publisher.cache())
         .pipe(awspublish.reporter());
   });

   /**
    * Compiles all scss files and places them in {compiledTemp}/css/ folder
    */
   gulp.task('compile-scss', [], function () {
      var scssStream = sass('./src/scss/app.scss', {
            compass: true,
            style: 'expanded',
            lineComments: false,
            sourcemap: true
         })
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: '../css/src/scss'
         }))
         .pipe(gulp.dest('./' + compiledTemp + '/css'));

      var sourceStream = gulp.src('./src/**/*.scss')
         .pipe(gulp.dest('./' + compiledTemp + '/css/src/'));

      return merge_stream(scssStream, sourceStream);
   });

   /**
    * Compiles all js files using Babel and places them in {compiledTemp} folder
    */
   gulp.task('compile-babel', [], function () {
      // TODO add babel compilation step once chrome sourcemap bug gets fixed
      // https://bugs.chromium.org/p/chromium/issues/detail?id=369797
      // var babelStream = gulp.src('./src/**/*.js')
      //    .pipe(jshint('.jshintrc'))
      //    .pipe(jshint.reporter('default'))
      //    .pipe(sourcemaps.init())
      //    .pipe(babel({
      //       presets: ['es2015'],
      //       sourceRoot: '../src/'
      //    }))
      //    .pipe(concat('app.js'))
      //    .pipe(sourcemaps.write('.'))
      //    .pipe(gulp.dest('./'+ compiledTemp +'/js/'));
      // var sourceStream = gulp.src('./src/**/*.js')
      //    .pipe(gulp.dest('./'+ compiledTemp +'/js/src/'));
      // return merge_stream(babelStream, sourceStream);

      return gulp.src('./src/**/*.js')
         .pipe(jshint('.jshintrc'))
         .pipe(jshint.reporter('default'))
         .pipe(jscs())
         .pipe(jscs.reporter())
         .pipe(gulp.dest('./' + compiledTemp));
   });

   /**
    * Copies all static files (.html, .json, images) to compiledTemp folder, i18n files are handled
    * by the translations task
    */
   gulp.task('compile-static', [], function () {
      return gulp
         .src([
            './src/**/*',
            '!./src/js/**',
            '!./src/js/',
            '!./src/scss/**',
            '!./src/scss/',
            '!./src/i18n/**',
            '!./src/i18n/'
         ])
         .pipe(gulp.dest('./' + compiledTemp));
   });

   /**
    * Merges the i18n files from ./src/i18n/ with kambi-sportsbook-widget-core-translate i18n files
    */
   gulp.task('compile-translations', function () {
      return gulp.src('./src/i18n/*.json')
         .pipe(foreach(function (stream, file) {
            var name = path.basename(file.path);
            var filePath = file.cwd + '/node_modules/kambi-sportsbook-widget-core-translate/dist/i18n/' + name;
            var srcJson = JSON.parse(file.contents.toString());
            var coreJson = json_merger.fromFile(filePath);
            var result = extendObj(srcJson, coreJson);
            gulpFile(name, JSON.stringify(result), { src: true })
               .pipe(gulp.dest(compiledTemp + '/i18n'))
               .pipe(jsonminify())
               .pipe(gulp.dest('./dist/i18n/'));
            return stream;
         }));
   });

   /**
    * Compiles all js, scss and i18n files and place them (alongside static files) in the dist
    * folder
    */
   gulp.task('compile', ['compile-babel', 'compile-scss', 'compile-static', 'compile-translations']);

   /**
    * Watches for any change in the files inside /src/ folder and recompiles them
    */
   gulp.task('watch', [], function () {
      gulp.watch('src/**/*.js', ['compile-babel']);
      gulp.watch('src/**/*.scss', ['compile-scss']);
      gulp.watch('src/i18n/*.json', ['compile-translations']);
      gulp.watch(['./src/**/*', '!./src/**/*.js', '!./src/**/*.scss', '!./src/i18n/**'], ['compile-static']);
   });

   /**
    * Minifies and concatenates all css files from {compiledTemp} and places them in the dist folder
    */
   gulp.task('css-concat', function () {
      return gulp.src('./' + compiledTemp + '/css/**/*.css')
         .pipe(concat('app.css'))
         .pipe(gulp.dest('./dist/css'))
         .pipe(cssnano())
         .pipe(rename('app.min.css'))
         .pipe(gulp.dest('./dist/css'));
   });

   /**
    * Concatanates all the js files in the compiledTemp folder into {buildTemp}/app.js
    */
   gulp.task('app-concat', function () {
      return gulp.src('./' + compiledTemp + '/**/*.js')
         .pipe(concat('app.js'))
         .pipe(gulp.dest('./' + buildTemp + '/js'));
   });

   /**
    * Concatanates and minifies all js files in {buildTemp} into /dist/js/app.min,js
    */
   gulp.task('js-concat', ['app-concat'], function () {
      return gulp.src('./' + buildTemp + '/**/*.js')
         .pipe(concat('app.js'))
         .pipe(stripDebug())
         .pipe(gulp.dest('./dist/js'))
         .pipe(uglify())
         .pipe(rename('app.min.js'))
         .pipe(gulp.dest('./dist/js'));
   });

   function extendObj (obj, src) {
      Object.keys(src).forEach(function (key) { obj[key] = src[key]; });
      return obj;
   }

}).call(this);
<commit_msg>Moved publish task to its own project (widget-aws-publish-tools, hosted on bitbucket)<commit_after>(function () {
   'use strict';
   var gulp = require('gulp'),

   fs = require('fs'),

   awspublish = require('gulp-awspublish'),

   rename = require('gulp-rename'),

   concat = require('gulp-concat'),

   uglify = require('gulp-uglify'),

   color = require('cli-color'),

   rename = require('gulp-rename'),

   notify = require('gulp-notify'),

   jshint = require('gulp-jshint'),

   stripDebug = require('gulp-strip-debug'),

   sourcemaps = require('gulp-sourcemaps'),

   sass = require('gulp-ruby-sass'),

   cssnano = require('gulp-cssnano'),

   htmlReplace = require('gulp-html-replace'),

   del = require('del'),

   replace = require('gulp-replace'),

   install = require('gulp-install'),

   path = require('path'),

   gulpFile = require('gulp-file'),

   foreach = require('gulp-foreach'),

   json_merger = require('json_merger'),

   jsonminify = require('gulp-jsonminify'),

   merge_stream = require('merge-stream'),

   run_sequence = require('run-sequence'),

   babel = require('gulp-babel'),

   jscs = require('gulp-jscs'),

   buildTemp = '.buildTemp',

   compiledTemp = '.compiledTemp';

   var buildParameters = JSON.parse(fs.readFileSync('./buildparameters.json'));

   /**
    * Copies project configuration files from the build tools into the project
    * The files are: .gitignore, .jshintrc, .editorconfig, config.rb
    */
   gulp.task('copy-config-files', function () {
      // .gitignore has special handling because npm strips .gitignore files
      // when downloading dependencies
      return gulp.src([
            './node_modules/widget-build-tools/widget_config/gitignore',
            './node_modules/widget-build-tools/widget_config/.editorconfig',
            './node_modules/widget-build-tools/widget_config/.jshintrc',
            './node_modules/widget-build-tools/widget_config/.jscsrc',
            './node_modules/widget-build-tools/widget_config/config.rb'
         ])
         .pipe(rename(function (path) {
            if (path.basename === 'gitignore') {
               path.basename = '.gitignore';
            }
         }))
         .pipe(gulp.dest('./'));
   });

   /**
    * Cleans the project (deletes compiledTemp, /dist/ and buildTemp folders)
    */
   gulp.task('clean', function () {
      del.sync(compiledTemp);
      del.sync('.dist');
      return del.sync(buildTemp);
   });

   /**
    * Cleans then builds
    */
   gulp.task('default', ['clean'], function () {
      return gulp.start('build');
   });

   /**
    * Tasks used by 'build' to run everything in the right order
    */
   gulp.task('build2', ['copy-config-files'], function () {
      gulp.start('build3');
   });
   gulp.task('build3', ['compile'], function () {
      gulp.start('build4');
   });
   gulp.task('build4', ['html-replace', 'css-concat', 'js-concat']);

   /**
    * Full build cycle with compilling and minifying
    */
   gulp.task('build', ['build2']);

   /**
    * Replaces references inside index.html to reference the minified and concatanated
    * js and css files
    */
   gulp.task('html-replace', function () {
      var references = extendObj(
         {
            css: 'css/app.min.css',
            js: 'js/app.min.js'
         },
         buildParameters.htmlReplace
      );
      return gulp.src('./' + compiledTemp + '/index.html')
         .pipe(htmlReplace(references))
         .pipe(gulp.dest('./dist'));
   });

   /**
    * Compiles all scss files and places them in {compiledTemp}/css/ folder
    */
   gulp.task('compile-scss', [], function () {
      var scssStream = sass('./src/scss/app.scss', {
            compass: true,
            style: 'expanded',
            lineComments: false,
            sourcemap: true
         })
         .pipe(sourcemaps.write('.', {
            includeContent: false,
            sourceRoot: '../css/src/scss'
         }))
         .pipe(gulp.dest('./' + compiledTemp + '/css'));

      var sourceStream = gulp.src('./src/**/*.scss')
         .pipe(gulp.dest('./' + compiledTemp + '/css/src/'));

      return merge_stream(scssStream, sourceStream);
   });

   /**
    * Compiles all js files using Babel and places them in {compiledTemp} folder
    */
   gulp.task('compile-babel', [], function () {
      // TODO add babel compilation step once chrome sourcemap bug gets fixed
      // https://bugs.chromium.org/p/chromium/issues/detail?id=369797
      // var babelStream = gulp.src('./src/**/*.js')
      //    .pipe(jshint('.jshintrc'))
      //    .pipe(jshint.reporter('default'))
      //    .pipe(sourcemaps.init())
      //    .pipe(babel({
      //       presets: ['es2015'],
      //       sourceRoot: '../src/'
      //    }))
      //    .pipe(concat('app.js'))
      //    .pipe(sourcemaps.write('.'))
      //    .pipe(gulp.dest('./'+ compiledTemp +'/js/'));
      // var sourceStream = gulp.src('./src/**/*.js')
      //    .pipe(gulp.dest('./'+ compiledTemp +'/js/src/'));
      // return merge_stream(babelStream, sourceStream);

      return gulp.src('./src/**/*.js')
         .pipe(jshint('.jshintrc'))
         .pipe(jshint.reporter('default'))
         .pipe(jscs())
         .pipe(jscs.reporter())
         .pipe(gulp.dest('./' + compiledTemp));
   });

   /**
    * Copies all static files (.html, .json, images) to compiledTemp folder, i18n files are handled
    * by the translations task
    */
   gulp.task('compile-static', [], function () {
      return gulp
         .src([
            './src/**/*',
            '!./src/js/**',
            '!./src/js/',
            '!./src/scss/**',
            '!./src/scss/',
            '!./src/i18n/**',
            '!./src/i18n/'
         ])
         .pipe(gulp.dest('./' + compiledTemp));
   });

   /**
    * Merges the i18n files from ./src/i18n/ with kambi-sportsbook-widget-core-translate i18n files
    */
   gulp.task('compile-translations', function () {
      return gulp.src('./src/i18n/*.json')
         .pipe(foreach(function (stream, file) {
            var name = path.basename(file.path);
            var filePath = file.cwd + '/node_modules/kambi-sportsbook-widget-core-translate/dist/i18n/' + name;
            var srcJson = JSON.parse(file.contents.toString());
            var coreJson = json_merger.fromFile(filePath);
            var result = extendObj(srcJson, coreJson);
            gulpFile(name, JSON.stringify(result), { src: true })
               .pipe(gulp.dest(compiledTemp + '/i18n'))
               .pipe(jsonminify())
               .pipe(gulp.dest('./dist/i18n/'));
            return stream;
         }));
   });

   /**
    * Compiles all js, scss and i18n files and place them (alongside static files) in the dist
    * folder
    */
   gulp.task('compile', ['compile-babel', 'compile-scss', 'compile-static', 'compile-translations']);

   /**
    * Watches for any change in the files inside /src/ folder and recompiles them
    */
   gulp.task('watch', [], function () {
      gulp.watch('src/**/*.js', ['compile-babel']);
      gulp.watch('src/**/*.scss', ['compile-scss']);
      gulp.watch('src/i18n/*.json', ['compile-translations']);
      gulp.watch(['./src/**/*', '!./src/**/*.js', '!./src/**/*.scss', '!./src/i18n/**'], ['compile-static']);
   });

   /**
    * Minifies and concatenates all css files from {compiledTemp} and places them in the dist folder
    */
   gulp.task('css-concat', function () {
      return gulp.src('./' + compiledTemp + '/css/**/*.css')
         .pipe(concat('app.css'))
         .pipe(gulp.dest('./dist/css'))
         .pipe(cssnano())
         .pipe(rename('app.min.css'))
         .pipe(gulp.dest('./dist/css'));
   });

   /**
    * Concatanates all the js files in the compiledTemp folder into {buildTemp}/app.js
    */
   gulp.task('app-concat', function () {
      return gulp.src('./' + compiledTemp + '/**/*.js')
         .pipe(concat('app.js'))
         .pipe(gulp.dest('./' + buildTemp + '/js'));
   });

   /**
    * Concatanates and minifies all js files in {buildTemp} into /dist/js/app.min,js
    */
   gulp.task('js-concat', ['app-concat'], function () {
      return gulp.src('./' + buildTemp + '/**/*.js')
         .pipe(concat('app.js'))
         .pipe(stripDebug())
         .pipe(gulp.dest('./dist/js'))
         .pipe(uglify())
         .pipe(rename('app.min.js'))
         .pipe(gulp.dest('./dist/js'));
   });

   function extendObj (obj, src) {
      Object.keys(src).forEach(function (key) { obj[key] = src[key]; });
      return obj;
   }

}).call(this);
<|endoftext|>


<commit_before>// Import modules:
var gulp = require('gulp')
,   pkg = require('./package.json')
,   less = require('gulp-less')
,   rename = require('gulp-rename')
,   concat = require('gulp-concat')
,   jshint = require('gulp-jshint')
,   header = require('gulp-header')
,   gutils = require('gulp-util')
,   replace = require('gulp-replace')
,   minifyCSS = require('gulp-minify-css')
,   uglify = require('gulp-uglify')
,   footer = require('gulp-footer');

//Add Trailing slash to projectPath if not exists.
if (pkg.projectPath !== "")
  pkg.projectPath = pkg.projectPath.replace(/\/?$/, '/');

var whichLib = pkg.jquery.url;
var pkgVersion = pkg.version;
if (gutils.env.chocolatechipjs) whichLib = "../chui/chocolatechip-" + pkgVersion + ".js";

// Define values for file headers:
var chui = ['ChUI-Android.css','ChUI-iOS.css','ChUI-Win.css','ChUI.js']
,   osNames = ['Android','iOS','Windows']
,   osTypes = ['android','ios','win'];

// Define header for ChUI files:
var chuiHeader = ['/*',
  '    pO\\',
  '   6  /\\',
  '     /OO\\',
  '    /OOOO\\',
  '   /OOOOOO\\',
  '  (OOOOOOOO)',
  '   \\:~==~:/',
  '',
  '<%= pkg.title %>',
  '<%= chuiName %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for minfied ChUI files:
var chuiHeaderMin = ['/*',
  '<%= pkg.title %>',
  '<%= chuiName %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for examples and demos:
var htmlHeader = ['<!DOCTYPE html>',
'<html lang="en"<%= langDir %>>',
'<head>',
'  <meta charset="utf-8">',
'  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">',
'  <meta name="apple-mobile-web-app-capable" content="yes">',
'  <meta name="mobile-web-app-capable" content="yes">',
'  <meta name="msapplication-tap-highlight" content="no">',
'  <title>ChocolateChip-UI <%= osName %></title>',
'  <link rel="stylesheet" href="../chui/chui-<%= osType %>-<%= pkg.version %>.css">',
'  <script src="<%= whichLib %>"></script>',
'  <script src="../chui/chui-<%= pkg.version %>.js"></script>'].join('\n') + '\n';

var less_for = function (os, idx) {
    gulp.src('src/themes/' + os + '/main.less')
      .pipe(less())
      .pipe(rename('chui-' + os + '-' + pkg.version + '.css'))
      .pipe(header(chuiHeader, { pkg : pkg, chuiName: chui[idx] }))
      .pipe(gulp.dest(pkg.projectPath + 'chui/')).pipe(minifyCSS({}))
      .pipe(gulp.dest(pkg.projectPath + 'dist/')).pipe(minifyCSS({}))
      .pipe(header(chuiHeaderMin, { pkg : pkg, chuiName: chui[idx] }))
      .pipe(rename('chui-' + os + '-' + pkg.version + '.min.css'))
      .pipe(gulp.dest(pkg.projectPath + './chui/'))
      .pipe(gulp.dest(pkg.projectPath + './dist/'));
}

// Process, minify and output LESS:
gulp.task('less', function () {
  osTypes.forEach(less_for);
});

// Concat, minify and output JavaScript:
gulp.task('js', function () {
  var chuijs_start = [
    'window.CHUIJSLIB;',
    'if(window.jQuery) {',
    '  window.CHUIJSLIB = window.jQuery;',
    '} else if (window.$chocolatechipjs) {',
    '  window.CHUIJSLIB = window.$chocolatechipjs;',
    '}',
    '(function($) {\n'
  ].join('\n');
  var chuijs_end = '\n\}\)\(window\.CHUIJSLIB\);';

  gulp.src([
    'src/chui/utils.js',
    'src/chui/events.js',
    'src/chui/detectors.js',
    'src/chui/browsers.js',
    'src/chui/gestures.js',
    'src/chui/desktop.js',
    'src/chui/layout.js',
    'src/chui/pubsub.js',
    'src/chui/navigation.js',
    'src/chui/buttons.js',
    'src/chui/blockui.js',
    'src/chui/center.js',
    'src/chui/busy.js',
    'src/chui/popup.js',
    'src/chui/popover.js',
    'src/chui/segmented.js',
    'src/chui/togglePanel.js',
    'src/chui/paging.js',
    'src/chui/deletableList.js',
    'src/chui/selectList.js',
    'src/chui/sheet.js',
    'src/chui/slideout.js',
    'src/chui/stepper.js',
    'src/chui/switch.js',
    'src/chui/scroll.js',
    'src/chui/tabbar.js',
    'src/chui/templates.js',
    'src/chui/search.js',
    'src/chui/carousel.js',
    'src/chui/range.js',
    'src/chui/select.js'
  ])

    .pipe(concat("chui-" + pkg.version + ".js"))
    .pipe(header(chuijs_start))
    .pipe(footer(chuijs_end))
    //.pipe(replace(/\}\)\(\);\n\}\)\(window.CHUIJSLIB\);/, '})(window.CHUIJSLIB);'))
    .pipe(header(chuiHeader, { pkg : pkg, chuiName: chui[3] }))
    .pipe(gulp.dest(pkg.projectPath + 'chui/'))
    .pipe(gulp.dest(pkg.projectPath + './dist/'))
    .pipe(uglify())
    .pipe(header(chuiHeaderMin, { pkg : pkg, chuiName: chui[3] }))
    .pipe(rename("chui-" + pkg.version + ".min.js"))
    .pipe(gulp.dest(pkg.projectPath + 'chui/'))
    .pipe(gulp.dest(pkg.projectPath + './dist/'));
});

// Copy out media:
gulp.task('copy', function() {
  gulp.src('src/images/**/*')
    .pipe(gulp.dest(pkg.projectPath + 'images/'));
  gulp.src('src/data/**/*')
    .pipe(gulp.dest(pkg.projectPath + 'data/'));

});

// JSHint:
gulp.task('jshint', function() {
  gulp.src("chui-" + pkg.version + ".js")
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

/*
   Define default task:
   To build, just enter gulp in terminal.
*/
gulp.task('default', ['less','js','jshint','examples']);

gulp.task('chui', ['less','js','jshint']);

// Generate only JavaScript
gulp.task('chuijs', ['js','jshint']);

// Generate all three themes - same as less following ChUI grunt conventions, easy docs
gulp.task('themes', ['less']);

// Generate only Android CSS
gulp.task('android', function () {
  less_for('android', osTypes.indexOf('android')); // 0 for position of element on chui var
});

// Generate only iOS CSS
gulp.task('ios', function () {
  less_for('ios', osTypes.indexOf('ios'));
});

// Generate only Windows CSS
gulp.task('win', function () {
  less_for('win', osTypes.indexOf('win'));
});

var generate_examples = function (os) {

  return (function() {

    var langDir = '';
    var rtl = gutils.env.dir === 'rtl';
    var dir = 'ltr';
    var prefix = '';

    var examples_for = function (os, idx) {

      gulp.src('src/' + prefix + 'examples/**/*')
        .pipe(header(htmlHeader, { pkg : pkg, osType : osTypes[idx], osName : osNames[idx], dir : prefix[dir], langDir : langDir, whichLib: whichLib }))
        .pipe(gulp.dest(pkg.projectPath + prefix + 'examples-' + os + '/'));
      gulp.src('src/' + prefix + 'demo/*.html')
        .pipe(header(htmlHeader, { pkg : pkg, osType : osTypes[idx], osName : osNames[idx], dir : prefix[dir], langDir : langDir, whichLib: whichLib }))
        .pipe(rename(prefix + 'demo-' + os + '.html'))
        .pipe(gulp.dest(pkg.projectPath + prefix + 'demo/'));

    };

    if (rtl) {
      prefix = 'rtl-';
      dir = 'rtl';
      langDir =  ' dir="rtl"';
      // Copy out rtl images:
      gulp.src('src/rtl-images/**/*')
        .pipe(gulp.dest(pkg.projectPath +'rtl-images/'));
      gulp.src('src/index.html')
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-android/'))
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-ios/'))
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-win/'));
    } else {
      gulp.src('src/index.html')
        .pipe(gulp.dest(pkg.projectPath + 'examples-android/'))
        .pipe(gulp.dest(pkg.projectPath + 'examples-ios/'))
        .pipe(gulp.dest(pkg.projectPath + 'examples-win/'));
    }

    if (os === undefined) {
      osTypes.forEach(examples_for);
    } else {
      examples_for(os, osTypes.indexOf(os));
    }

  });
};

/*
To build all examples for Android, iOS and Windows Phone,
just run gulp.

To build the right-to-left examples for Android, iOS
and Windows Phone, run:
  gulp --dir rtl

To create OS-specific builds, run the following commands.
To create their right-to-left version, run the command followed by --dir rtl.
*/
// Generate only android example & demo
gulp.task('android_examples', ['chuijs','android','copy'], generate_examples('android'));

// Generate only ios example & demo
gulp.task('ios_examples', ['chuijs','ios','copy'], generate_examples('ios'));

// Generate only windows example & demo
gulp.task('win_examples', ['chuijs','win','copy'], generate_examples('win'));

// Create examples & demos (ltr or rtl):
gulp.task('examples', ['copy'], generate_examples());

// Watch LESS files and generate CSS:
gulp.task('watch:less', function() {
  gulp.watch('src/themes/android/*.less', ['android']);
  gulp.watch('src/themes/ios/*.less', ['ios']);
  gulp.watch('src/themes/win/*.less', ['win']);
});

// Watch JS file and generate ChUI JS:
gulp.task('watch:scripts', function() {
  gulp.watch('src/chui/*.js', ['chuijs']);
});

// Watch html files and generate  examples & demo files
gulp.task('watch:html', function() {
  var rtl = gutils.env.dir === 'rtl';
  if (rtl) { // build rtl on --dir rtl
    gulp.watch(['src/rtl-examples/*.html', 'src/rtl-demo/*.html'], ['examples']);
  } else {
    gulp.watch(['src/examples/*.html', 'src/demo/*.html'], ['examples']);
  }
});

//Watch All - html js & less
gulp.task('watch', ['watch:less', 'watch:scripts', 'watch:html']);

var chocolatechipjs_start = '(function() {\n';
var chocolatechipjs_end = '\n})(window.CHUIJSLIB);';

gulp.task('chocolatechipjs', function() {
  gulp.src([
    "src/chocolatechipjs/chocolatechip-*.js"
  ])
  .pipe(gulp.dest(pkg.projectPath + 'chui/'))
});
<commit_msg>Now all references to target directories are "chui/" and "dist/".<commit_after>// Import modules:
var gulp = require('gulp')
,   pkg = require('./package.json')
,   less = require('gulp-less')
,   rename = require('gulp-rename')
,   concat = require('gulp-concat')
,   jshint = require('gulp-jshint')
,   header = require('gulp-header')
,   gutils = require('gulp-util')
,   replace = require('gulp-replace')
,   minifyCSS = require('gulp-minify-css')
,   uglify = require('gulp-uglify')
,   footer = require('gulp-footer');

//Add Trailing slash to projectPath if not exists.
if (pkg.projectPath !== "")
  pkg.projectPath = pkg.projectPath.replace(/\/?$/, '/');

var whichLib = pkg.jquery.url;
var pkgVersion = pkg.version;
if (gutils.env.chocolatechipjs) whichLib = "../chui/chocolatechip-" + pkgVersion + ".js";

// Define values for file headers:
var chui = ['ChUI-Android.css','ChUI-iOS.css','ChUI-Win.css','ChUI.js']
,   osNames = ['Android','iOS','Windows']
,   osTypes = ['android','ios','win'];

// Define header for ChUI files:
var chuiHeader = ['/*',
  '    pO\\',
  '   6  /\\',
  '     /OO\\',
  '    /OOOO\\',
  '   /OOOOOO\\',
  '  (OOOOOOOO)',
  '   \\:~==~:/',
  '',
  '<%= pkg.title %>',
  '<%= chuiName %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for minfied ChUI files:
var chuiHeaderMin = ['/*',
  '<%= pkg.title %>',
  '<%= chuiName %>',
  'Copyright ' + gutils.date("yyyy") + ' Sourcebits www.sourcebits.com',
  'License: <%= pkg.licences[0].type %>',
  'Version: <%= pkg.version %>',
  '*/\n'].join('\n');

// Define header for examples and demos:
var htmlHeader = ['<!DOCTYPE html>',
'<html lang="en"<%= langDir %>>',
'<head>',
'  <meta charset="utf-8">',
'  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">',
'  <meta name="apple-mobile-web-app-capable" content="yes">',
'  <meta name="mobile-web-app-capable" content="yes">',
'  <meta name="msapplication-tap-highlight" content="no">',
'  <title>ChocolateChip-UI <%= osName %></title>',
'  <link rel="stylesheet" href="../chui/chui-<%= osType %>-<%= pkg.version %>.css">',
'  <script src="<%= whichLib %>"></script>',
'  <script src="../chui/chui-<%= pkg.version %>.js"></script>'].join('\n') + '\n';

var less_for = function (os, idx) {
    gulp.src('src/themes/' + os + '/main.less')
      .pipe(less())
      .pipe(rename('chui-' + os + '-' + pkg.version + '.css'))
      .pipe(header(chuiHeader, { pkg : pkg, chuiName: chui[idx] }))
      .pipe(gulp.dest(pkg.projectPath + 'chui/')).pipe(minifyCSS({}))
      .pipe(gulp.dest(pkg.projectPath + 'dist/')).pipe(minifyCSS({}))
      .pipe(header(chuiHeaderMin, { pkg : pkg, chuiName: chui[idx] }))
      .pipe(rename('chui-' + os + '-' + pkg.version + '.min.css'))
      .pipe(gulp.dest(pkg.projectPath + 'chui/'))
      .pipe(gulp.dest(pkg.projectPath + 'dist/'));
}

// Process, minify and output LESS:
gulp.task('less', function () {
  osTypes.forEach(less_for);
});

// Concat, minify and output JavaScript:
gulp.task('js', function () {
  var chuijs_start = [
    'window.CHUIJSLIB;',
    'if(window.jQuery) {',
    '  window.CHUIJSLIB = window.jQuery;',
    '} else if (window.$chocolatechipjs) {',
    '  window.CHUIJSLIB = window.$chocolatechipjs;',
    '}',
    '(function($) {\n'
  ].join('\n');
  var chuijs_end = '\n\}\)\(window\.CHUIJSLIB\);';

  gulp.src([
    'src/chui/utils.js',
    'src/chui/events.js',
    'src/chui/detectors.js',
    'src/chui/browsers.js',
    'src/chui/gestures.js',
    'src/chui/desktop.js',
    'src/chui/layout.js',
    'src/chui/pubsub.js',
    'src/chui/navigation.js',
    'src/chui/buttons.js',
    'src/chui/blockui.js',
    'src/chui/center.js',
    'src/chui/busy.js',
    'src/chui/popup.js',
    'src/chui/popover.js',
    'src/chui/segmented.js',
    'src/chui/togglePanel.js',
    'src/chui/paging.js',
    'src/chui/deletableList.js',
    'src/chui/selectList.js',
    'src/chui/sheet.js',
    'src/chui/slideout.js',
    'src/chui/stepper.js',
    'src/chui/switch.js',
    'src/chui/scroll.js',
    'src/chui/tabbar.js',
    'src/chui/templates.js',
    'src/chui/search.js',
    'src/chui/carousel.js',
    'src/chui/range.js',
    'src/chui/select.js'
  ])

    .pipe(concat("chui-" + pkg.version + ".js"))
    .pipe(header(chuijs_start))
    .pipe(footer(chuijs_end))
    //.pipe(replace(/\}\)\(\);\n\}\)\(window.CHUIJSLIB\);/, '})(window.CHUIJSLIB);'))
    .pipe(header(chuiHeader, { pkg : pkg, chuiName: chui[3] }))
    .pipe(gulp.dest(pkg.projectPath + 'chui/'))
    .pipe(gulp.dest(pkg.projectPath + 'dist/'))
    .pipe(uglify())
    .pipe(header(chuiHeaderMin, { pkg : pkg, chuiName: chui[3] }))
    .pipe(rename("chui-" + pkg.version + ".min.js"))
    .pipe(gulp.dest(pkg.projectPath + 'chui/'))
    .pipe(gulp.dest(pkg.projectPath + 'dist/'));
});

// Copy out media:
gulp.task('copy', function() {
  gulp.src('src/images/**/*')
    .pipe(gulp.dest(pkg.projectPath + 'images/'));
  gulp.src('src/data/**/*')
    .pipe(gulp.dest(pkg.projectPath + 'data/'));

});

// JSHint:
gulp.task('jshint', function() {
  gulp.src("chui-" + pkg.version + ".js")
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

/*
   Define default task:
   To build, just enter gulp in terminal.
*/
gulp.task('default', ['less','js','jshint','examples']);

gulp.task('chui', ['less','js','jshint']);

// Generate only JavaScript
gulp.task('chuijs', ['js','jshint']);

// Generate all three themes - same as less following ChUI grunt conventions, easy docs
gulp.task('themes', ['less']);

// Generate only Android CSS
gulp.task('android', function () {
  less_for('android', osTypes.indexOf('android')); // 0 for position of element on chui var
});

// Generate only iOS CSS
gulp.task('ios', function () {
  less_for('ios', osTypes.indexOf('ios'));
});

// Generate only Windows CSS
gulp.task('win', function () {
  less_for('win', osTypes.indexOf('win'));
});

var generate_examples = function (os) {

  return (function() {

    var langDir = '';
    var rtl = gutils.env.dir === 'rtl';
    var dir = 'ltr';
    var prefix = '';

    var examples_for = function (os, idx) {

      gulp.src('src/' + prefix + 'examples/**/*')
        .pipe(header(htmlHeader, { pkg : pkg, osType : osTypes[idx], osName : osNames[idx], dir : prefix[dir], langDir : langDir, whichLib: whichLib }))
        .pipe(gulp.dest(pkg.projectPath + prefix + 'examples-' + os + '/'));
      gulp.src('src/' + prefix + 'demo/*.html')
        .pipe(header(htmlHeader, { pkg : pkg, osType : osTypes[idx], osName : osNames[idx], dir : prefix[dir], langDir : langDir, whichLib: whichLib }))
        .pipe(rename(prefix + 'demo-' + os + '.html'))
        .pipe(gulp.dest(pkg.projectPath + prefix + 'demo/'));

    };

    if (rtl) {
      prefix = 'rtl-';
      dir = 'rtl';
      langDir =  ' dir="rtl"';
      // Copy out rtl images:
      gulp.src('src/rtl-images/**/*')
        .pipe(gulp.dest(pkg.projectPath +'rtl-images/'));
      gulp.src('src/index.html')
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-android/'))
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-ios/'))
        .pipe(gulp.dest(pkg.projectPath + 'rtl-examples-win/'));
    } else {
      gulp.src('src/index.html')
        .pipe(gulp.dest(pkg.projectPath + 'examples-android/'))
        .pipe(gulp.dest(pkg.projectPath + 'examples-ios/'))
        .pipe(gulp.dest(pkg.projectPath + 'examples-win/'));
    }

    if (os === undefined) {
      osTypes.forEach(examples_for);
    } else {
      examples_for(os, osTypes.indexOf(os));
    }

  });
};

/*
To build all examples for Android, iOS and Windows Phone,
just run gulp.

To build the right-to-left examples for Android, iOS
and Windows Phone, run:
  gulp --dir rtl

To create OS-specific builds, run the following commands.
To create their right-to-left version, run the command followed by --dir rtl.
*/
// Generate only android example & demo
gulp.task('android_examples', ['chuijs','android','copy'], generate_examples('android'));

// Generate only ios example & demo
gulp.task('ios_examples', ['chuijs','ios','copy'], generate_examples('ios'));

// Generate only windows example & demo
gulp.task('win_examples', ['chuijs','win','copy'], generate_examples('win'));

// Create examples & demos (ltr or rtl):
gulp.task('examples', ['copy'], generate_examples());

// Watch LESS files and generate CSS:
gulp.task('watch:less', function() {
  gulp.watch('src/themes/android/*.less', ['android']);
  gulp.watch('src/themes/ios/*.less', ['ios']);
  gulp.watch('src/themes/win/*.less', ['win']);
});

// Watch JS file and generate ChUI JS:
gulp.task('watch:scripts', function() {
  gulp.watch('src/chui/*.js', ['chuijs']);
});

// Watch html files and generate  examples & demo files
gulp.task('watch:html', function() {
  var rtl = gutils.env.dir === 'rtl';
  if (rtl) { // build rtl on --dir rtl
    gulp.watch(['src/rtl-examples/*.html', 'src/rtl-demo/*.html'], ['examples']);
  } else {
    gulp.watch(['src/examples/*.html', 'src/demo/*.html'], ['examples']);
  }
});

//Watch All - html js & less
gulp.task('watch', ['watch:less', 'watch:scripts', 'watch:html']);

var chocolatechipjs_start = '(function() {\n';
var chocolatechipjs_end = '\n})(window.CHUIJSLIB);';

gulp.task('chocolatechipjs', function() {
  gulp.src([
    "src/chocolatechipjs/chocolatechip-*.js"
  ])
  .pipe(gulp.dest(pkg.projectPath + 'chui/'))
});
<|endoftext|>


<commit_before>'use strict';

var gulp        = require('gulp');
var isparta     = require('isparta');
var plugins     = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var server      = require('gulp-develop-server' );
var webpack     = require("webpack");
var exec        = require('child_process').exec;
var fs          = require("fs");

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

gulp.task('lint:src', function() {
  return gulp.src(['src/**/*.js'])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

// Lint our test code
gulp.task('lint:test', function() {
  return gulp.src(['test/unit/**/*.js'])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('build', function(done) {
  runSequence('clean', 'build:node', 'build:browser', done);
});

gulp.task('test', function(done) {
  runSequence('clean', 'test:unit', 'test:browser', function (err) {
    server.kill();
    done();
  });
});

gulp.task('hooks:precommit', ['build'], function() {
  return gulp.src(['dist/*', 'lib/*'])
    .pipe(plugins.git.add());
});

gulp.task('build:node', ['lint:src'], function() {
    return gulp.src('src/**/*.js')
        .pipe(plugins.babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('build:browser', ['lint:src'], function() {
  return gulp.src('src/browser.js')
    .pipe(plugins.webpack({
      output: { library: 'StellarSdk' },
      module: {
        loaders: [
          { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
        ],
      },
      plugins: [
        // Ignore native modules (ed25519)
        new webpack.IgnorePlugin(/ed25519/)
      ]
    }))
    // Add EventSource polyfill for IE11
    .pipe(plugins.insert.prepend(fs.readFileSync('./node_modules/event-source-polyfill/eventsource.js')))
    .pipe(plugins.rename('stellar-sdk.js'))
    .pipe(gulp.dest('dist'))
    .pipe(plugins.uglify({
      output: {
        ascii_only: true
      }
    }))
    .pipe(plugins.rename('stellar-sdk.min.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('test:init-istanbul', ['clean-coverage'], function () {
  return gulp.src(['src/**/*.js'])
    .pipe(plugins.istanbul({
      instrumenter: isparta.Instrumenter
    }))
    .pipe(plugins.istanbul.hookRequire());
});

gulp.task('test:integration', ['build:node', 'test:init-istanbul'], function() {
  return gulp.src(["test/test-helper.js", "test/unit/**/*.js", "test/integration/**/*.js"])
    .pipe(plugins.mocha({
      reporter: ['spec']
    }))
    .pipe(plugins.istanbul.writeReports());
});

gulp.task('test:unit', ['build:node'], function() {
  return gulp.src(["test/test-helper.js", "test/unit/**/*.js"])
    .pipe(plugins.mocha({
      reporter: ['spec']
    }));
});

gulp.task('test:browser', ["build:browser"], function (done) {
  var Server = require('karma').Server;
  var server = new Server({ configFile: __dirname + '/karma.conf.js' });
  server.start(function() {
    done();
  });
});

gulp.task('test:sauce', ["build:browser"], function (done) {
  var Server = require('karma').Server;
  var server = new Server({ configFile: __dirname + '/karma-sauce.conf.js' });
  server.start(function() {
    done();
  });
});

gulp.task('clean', function () {
  return gulp.src('dist', { read: false })
      .pipe(plugins.rimraf());
});

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

gulp.task('clean-coverage', function() {
  return gulp.src(['coverage'], { read: false })
    .pipe(plugins.rimraf());
});

gulp.task('submit-coverage', function() {
  return gulp
    .src("./coverage/**/lcov.info")
    .pipe(plugins.coveralls());
});
<commit_msg>Fix event-source-polyfill path<commit_after>'use strict';

var gulp        = require('gulp');
var isparta     = require('isparta');
var plugins     = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var server      = require('gulp-develop-server' );
var webpack     = require("webpack");
var exec        = require('child_process').exec;
var fs          = require("fs");

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

gulp.task('lint:src', function() {
  return gulp.src(['src/**/*.js'])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

// Lint our test code
gulp.task('lint:test', function() {
  return gulp.src(['test/unit/**/*.js'])
    .pipe(plugins.plumber())
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('build', function(done) {
  runSequence('clean', 'build:node', 'build:browser', done);
});

gulp.task('test', function(done) {
  runSequence('clean', 'test:unit', 'test:browser', function (err) {
    server.kill();
    done();
  });
});

gulp.task('hooks:precommit', ['build'], function() {
  return gulp.src(['dist/*', 'lib/*'])
    .pipe(plugins.git.add());
});

gulp.task('build:node', ['lint:src'], function() {
    return gulp.src('src/**/*.js')
        .pipe(plugins.babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('build:browser', ['lint:src'], function() {
  return gulp.src('src/browser.js')
    .pipe(plugins.webpack({
      output: { library: 'StellarSdk' },
      module: {
        loaders: [
          { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
        ],
      },
      plugins: [
        // Ignore native modules (ed25519)
        new webpack.IgnorePlugin(/ed25519/)
      ]
    }))
    // Add EventSource polyfill for IE11
    .pipe(plugins.insert.prepend(fs.readFileSync('./node_modules/event-source-polyfill/src/eventsource.min.js')))
    .pipe(plugins.rename('stellar-sdk.js'))
    .pipe(gulp.dest('dist'))
    .pipe(plugins.uglify({
      output: {
        ascii_only: true
      }
    }))
    .pipe(plugins.rename('stellar-sdk.min.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('test:init-istanbul', ['clean-coverage'], function () {
  return gulp.src(['src/**/*.js'])
    .pipe(plugins.istanbul({
      instrumenter: isparta.Instrumenter
    }))
    .pipe(plugins.istanbul.hookRequire());
});

gulp.task('test:integration', ['build:node', 'test:init-istanbul'], function() {
  return gulp.src(["test/test-helper.js", "test/unit/**/*.js", "test/integration/**/*.js"])
    .pipe(plugins.mocha({
      reporter: ['spec']
    }))
    .pipe(plugins.istanbul.writeReports());
});

gulp.task('test:unit', ['build:node'], function() {
  return gulp.src(["test/test-helper.js", "test/unit/**/*.js"])
    .pipe(plugins.mocha({
      reporter: ['spec']
    }));
});

gulp.task('test:browser', ["build:browser"], function (done) {
  var Server = require('karma').Server;
  var server = new Server({ configFile: __dirname + '/karma.conf.js' });
  server.start(function() {
    done();
  });
});

gulp.task('test:sauce', ["build:browser"], function (done) {
  var Server = require('karma').Server;
  var server = new Server({ configFile: __dirname + '/karma-sauce.conf.js' });
  server.start(function() {
    done();
  });
});

gulp.task('clean', function () {
  return gulp.src('dist', { read: false })
      .pipe(plugins.rimraf());
});

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

gulp.task('clean-coverage', function() {
  return gulp.src(['coverage'], { read: false })
    .pipe(plugins.rimraf());
});

gulp.task('submit-coverage', function() {
  return gulp
    .src("./coverage/**/lcov.info")
    .pipe(plugins.coveralls());
});
<|endoftext|>