<commit_before>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');

var log = function( head, msg ) {
    gutil.log( '[' + gutil.colors.blue( head ) + ']', msg );
};
var logger = function( head ) {
    return function( msg ) {
        log( head, msg );
    };
};

// === IMAGES ===

var images = {
    src: 'resources/assets/images/*/**.{svg,png,jpg}',
    dest: 'public/assets/images',

    build: function() {
        var files = gulp.src( images.src );
        return images.handle( files );
    },
    watch: function() {
        var watch = require( 'gulp-watch' );
        var plumber = require('gulp-plumber');

        var files = watch( images.src ).pipe( plumber() );
        return images.handle( files );
    },
    handle: function( source ) {
        var imagemin = require('gulp-imagemin');
        var changed = require('gulp-changed');

        var imageminConfig = {
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }]
        };

        return source
            .pipe( changed( images.dest ))
            .pipe( imagemin( imageminConfig ))
            .pipe( gulp.dest( images.dest ));
    }
};

// === STYLES ===

var styles = {
    paths: {
        src: 'resources/assets/css/*.{scss,sass,css}',
        watch: 'resources/assets/css/**/*.{scss,sass,css}',
        dest: 'public/assets/css'
    },

    build: function() {
        var merge = require('merge-stream');

        return merge(
            styles.buildCss(),
            styles.normalizeCss()
        );
    },
    buildCss: function() {
        var sass = require('gulp-sass');
        var postcss = require('gulp-postcss');
        var autoprefixer = require('autoprefixer-core');
        var minify = require('gulp-minify-css');
        var sourcemaps = require('gulp-sourcemaps');

        log('css', 'build');

        return gulp.src( styles.paths.src )
            .pipe( sourcemaps.init() )
            .pipe( sass() )
            .pipe( postcss([autoprefixer]) )
            .pipe( minify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( styles.paths.dest ))
    },
    normalizeCss: function () {
        var minify = require('gulp-minify-css');
        var changed = require('gulp-changed');
        return gulp.src('node_modules/normalize.css/normalize.css')
            .pipe( changed( styles.paths.dest ))
            .pipe( minify() )
            .pipe( gulp.dest( styles.paths.dest ));
    },
    watch: function() {
        var watch = require('gulp-watch');
        return watch( styles.paths.watch, styles.buildCss );
    }
};

// === JS ===

var js = {
    src: './resources/assets/js/*',
    dest: './public/assets/js',
    entry: './resources/assets/js/gw2heroes.js',

    config: {
        entries: './resources/assets/js/gw2heroes.js',
        dest: './public/assets/js',
        outputName: 'gw2heroes.js',
        paths: [ './node_modules', './resources/assets/js/' ],
        fullPaths: false,
        debug: true
    },

    build: function() {
        var browserify = require('browserify');
        var babelify = require('babelify');

        var bundle = browserify( js.config )
            .transform( babelify );

        return js.handle( bundle, js.config );
    },
    watch: function() {
        var browserify = require('browserify');
        var watchify = require('watchify');
        var babelify = require('babelify');
        var extend = require('lodash/object/extend');

        var config = extend( js.config, watchify.args );
        var bundle = watchify( browserify( config ))
            .transform( babelify );

        bundle.on('update', function() {
            js.handle( bundle, config );
        });
        bundle.on( 'log', logger('js') );

        return js.handle( bundle, config )
    },
    handle: function( bundle, config ) {
        var sourcemaps = require('gulp-sourcemaps');
        var uglify = require('gulp-uglify');
        var source = require('vinyl-source-stream');
        var buffer = require('gulp-buffer');

        return bundle
            .bundle()
            .on( 'error', function( err ) {
                log( 'js', gutil.colors.red('Error: ') + err );
            })
            .pipe( source( config.outputName ))
            .pipe( buffer() )
            .pipe( sourcemaps.init({ loadMaps: true }) )
            .pipe( uglify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( config.dest ));
    }
};

// === GENERAL ===

var general = {
    src: 'resources/assets',
    dest: 'public/assets',

    build: function() {
        var merge = require('merge-stream');

        return merge(
            images.build(),
            styles.build(),
            js.build()
        );
    },
    clean: function( cb ) {
        var del = require('del');
        del( general.dest, cb );
    },
    watch: function() {
        styles.build();
        styles.watch();

        images.build();
        images.watch();

        js.watch();
    }
};

gulp.task( 'watch', general.watch );
gulp.task( 'clean', general.clean );
gulp.task( 'build', general.build );
gulp.task( 'build:js', js.build );
gulp.task( 'build:css', styles.build );
gulp.task( 'build:images', images.build );
gulp.task( 'build-clean', ['clean'], general.build );
// alias default = build
gulp.task( 'default', ['build'] );
<commit_msg>fix gulp file not minifying images anymore<commit_after>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');

var log = function( head, msg ) {
    gutil.log( '[' + gutil.colors.blue( head ) + ']', msg );
};
var logger = function( head ) {
    return function( msg ) {
        log( head, msg );
    };
};

// === IMAGES ===

var images = {
    src: 'resources/assets/images/**/*.{svg,png,jpg}',
    dest: 'public/assets/images',

    build: function() {
        var files = gulp.src( images.src );
        return images.handle( files );
    },
    watch: function() {
        var watch = require( 'gulp-watch' );
        var plumber = require('gulp-plumber');

        var files = watch( images.src ).pipe( plumber() );
        return images.handle( files );
    },
    handle: function( source ) {
        var imagemin = require('gulp-imagemin');
        var changed = require('gulp-changed');

        var imageminConfig = {
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }]
        };

        return source
            .pipe( changed( images.dest ))
            .pipe( imagemin( imageminConfig ))
            .pipe( gulp.dest( images.dest ));
    }
};

// === STYLES ===

var styles = {
    paths: {
        src: 'resources/assets/css/*.{scss,sass,css}',
        watch: 'resources/assets/css/**/*.{scss,sass,css}',
        dest: 'public/assets/css'
    },

    build: function() {
        var merge = require('merge-stream');

        return merge(
            styles.buildCss(),
            styles.normalizeCss()
        );
    },
    buildCss: function() {
        var sass = require('gulp-sass');
        var postcss = require('gulp-postcss');
        var autoprefixer = require('autoprefixer-core');
        var minify = require('gulp-minify-css');
        var sourcemaps = require('gulp-sourcemaps');

        log('css', 'build');

        return gulp.src( styles.paths.src )
            .pipe( sourcemaps.init() )
            .pipe( sass() )
            .pipe( postcss([autoprefixer]) )
            .pipe( minify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( styles.paths.dest ))
    },
    normalizeCss: function () {
        var minify = require('gulp-minify-css');
        var changed = require('gulp-changed');
        return gulp.src('node_modules/normalize.css/normalize.css')
            .pipe( changed( styles.paths.dest ))
            .pipe( minify() )
            .pipe( gulp.dest( styles.paths.dest ));
    },
    watch: function() {
        var watch = require('gulp-watch');
        return watch( styles.paths.watch, styles.buildCss );
    }
};

// === JS ===

var js = {
    src: './resources/assets/js/*',
    dest: './public/assets/js',
    entry: './resources/assets/js/gw2heroes.js',

    config: {
        entries: './resources/assets/js/gw2heroes.js',
        dest: './public/assets/js',
        outputName: 'gw2heroes.js',
        paths: [ './node_modules', './resources/assets/js/' ],
        fullPaths: false,
        debug: true
    },

    build: function() {
        var browserify = require('browserify');
        var babelify = require('babelify');

        var bundle = browserify( js.config )
            .transform( babelify );

        return js.handle( bundle, js.config );
    },
    watch: function() {
        var browserify = require('browserify');
        var watchify = require('watchify');
        var babelify = require('babelify');
        var extend = require('lodash/object/extend');

        var config = extend( js.config, watchify.args );
        var bundle = watchify( browserify( config ))
            .transform( babelify );

        bundle.on('update', function() {
            js.handle( bundle, config );
        });
        bundle.on( 'log', logger('js') );

        return js.handle( bundle, config )
    },
    handle: function( bundle, config ) {
        var sourcemaps = require('gulp-sourcemaps');
        var uglify = require('gulp-uglify');
        var source = require('vinyl-source-stream');
        var buffer = require('gulp-buffer');

        return bundle
            .bundle()
            .on( 'error', function( err ) {
                log( 'js', gutil.colors.red('Error: ') + err );
            })
            .pipe( source( config.outputName ))
            .pipe( buffer() )
            .pipe( sourcemaps.init({ loadMaps: true }) )
            .pipe( uglify() )
            .pipe( sourcemaps.write( '.' ))
            .pipe( gulp.dest( config.dest ));
    }
};

// === GENERAL ===

var general = {
    src: 'resources/assets',
    dest: 'public/assets',

    build: function() {
        var merge = require('merge-stream');

        return merge(
            images.build(),
            styles.build(),
            js.build()
        );
    },
    clean: function( cb ) {
        var del = require('del');
        del( general.dest, cb );
    },
    watch: function() {
        styles.build();
        styles.watch();

        images.build();
        images.watch();

        js.watch();
    }
};

gulp.task( 'watch', general.watch );
gulp.task( 'clean', general.clean );
gulp.task( 'build', general.build );
gulp.task( 'build:js', js.build );
gulp.task( 'build:css', styles.build );
gulp.task( 'build:images', images.build );
gulp.task( 'build-clean', ['clean'], general.build );
// alias default = build
gulp.task( 'default', ['build'] );
<|endoftext|>


<commit_before>const gulp = require('gulp')
const eslint = require('gulp-eslint')
const ava = require('gulp-ava')

gulp.task('lint', () =>
    gulp.src(['chance.js', 'gulpfile.js', 'test/**/*.js'])
        .pipe(eslint({
            parser: 'babel-eslint',
            rules: {
                // quotes: ['error', 'single'],
                'no-trailing-spaces': 'error',
                'no-console': 'error'
            }
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
)

gulp.task('test', () =>
    gulp.src('test/**/*.js')
        .pipe(ava({ verbose: true }))
)

gulp.task('watch', () => {
    var watcher = gulp.watch(['chance.js', 'gulpfile.js', 'test/**/*.js'], ['lint', 'test'])
})

gulp.task('watch-lint', () => {
    var watcher = gulp.watch(['chance.js', 'gulpfile.js', 'test/**/*.js'], ['lint'])
})

gulp.task('travis', ['lint', 'test'])

gulp.task('default', ['watch', 'lint', 'test'])
<commit_msg>More stringent lint rules<commit_after>const gulp = require('gulp')
const eslint = require('gulp-eslint')
const ava = require('gulp-ava')

gulp.task('lint', () =>
    gulp.src(['chance.js', 'gulpfile.js', 'test/**/*.js', '!test/helpers/**/*.js'])
        .pipe(eslint({
            parser: 'babel-eslint',
            rules: {
                // quotes: ['error', 'single'],
                'curly': 'error',
                'eqeqeq': 'error',
                'no-console': 'error',
                'no-empty': 'error',
                'no-trailing-spaces': 'error',
            }
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
)

gulp.task('test', () =>
    gulp.src('test/**/*.js')
        .pipe(ava({ verbose: true }))
)

gulp.task('watch', () => {
    var watcher = gulp.watch(['chance.js', 'gulpfile.js', 'test/**/*.js'], ['lint', 'test'])
})

gulp.task('watch-lint', () => {
    var watcher = gulp.watch(['chance.js', 'gulpfile.js', 'test/**/*.js'], ['lint'])
})

gulp.task('travis', ['lint', 'test'])

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


<commit_before>var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var rename = require('gulp-rename');
var del = require('del');
var stripDebug = require('gulp-strip-debug');
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var gzip = require('gulp-gzip');
var fileInclude = require('gulp-file-include');
var markdown = require('gulp-markdown');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var frontMatter = require('gulp-front-matter');
var concat = require('gulp-concat');
var es = require('event-stream');
var mustache = require('mustache');
var fs = require('fs');
var sort = require('sort-stream');
var moment = require('moment');
var config = require('./config').config;

var destination = config.buildDest;

// command line params
// for instance: $ gulp --type production
var isProduction = args.type === 'production';

// blog page pipeline
gulp.task('blog', ['blog-posts-list'], function () {
  // taking the blog post list from the 'blog-posts-list' step
  // and including it into the blog.html template
  return gulp.src('src/blog/blog.html')
    .pipe(es.map(function (file, cb) {
      // first inject the build destination so include knows where to go
      var html = mustache.render(
        String(file.contents), {
          buildDest: config.buildDest
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // then actually include the headers, navs, blogposts, footer and tail
    .pipe(fileInclude())
    // then set the title
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(
        String(file.contents), {
          title: 'Blog'
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // now we have /blog tada
    .pipe(rename('blog/index.html'))
    .pipe(gulp.dest(destination));
});

function capitalize (string) {
  return string[0].toUpperCase() + string.substr(1);
}

// blog post list for blog page
gulp.task('blog-posts-list', ['blog-posts-html'], function () {
  var postlist = String(fs.readFileSync('src/blog/blogposts.html'));

  return gulp.src('src/blog/markdown/**/*.md')
    // extract the frontmatter from the .md add to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // use the frontmatter to populate a blog post list
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(postlist, {
        post: file.frontMatter,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors.map(function(a){return {
          lowercase: a,
          capital: capitalize(a)
        };})
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // sort the list newest-first
    .pipe(sort(function (a, b) {
      if (a.frontMatter.date > b.frontMatter.date) return -1;
      if (a.frontMatter.date < b.frontMatter.date) return 1;
      return 0;
    }))
    // concat the list into a single html
    .pipe(concat('blogposts.html'))
    .pipe(gulp.dest(destination));
});

// fill out the blog post templates
gulp.task('blog-posts-html', function () {
  var post = String(fs.readFileSync('src/blog/post.html'));
  var dir = '';
  return gulp.src('src/blog/markdown/**/*.md')
    // extract frontmatter from markdown, append to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // render the partial
    .pipe(markdown())
    // insert frontmatter and partial as mustache vars into post template
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(post, {
        buildDest: config.buildDest,
        include: file.frontMatter.readfullarticle,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors,
        rendered: file.contents
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // include stuff
    .pipe(fileInclude())
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.md', '');
      cb(null, file);
    }))
    // insert handlebars values from frontmatter into head template
    .pipe(es.map(function (file, cb) {
      file.contents = new Buffer(
        mustache.render(
          String(file.contents), {
            title: file.frontMatter.title,
            base: config.baseURL,
            include: file.frontMatter.readfullarticle,
            summary: file.frontMatter.summary
          }));
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    .pipe(rename(function (path) {
      path.dirname = dir.split('.')[0];
      path.basename = "index";
      path.extname = ".html";
    }))
    .pipe(gulp.dest(destination + '/blog'));
});

// html
gulp.task('html', ['blog'], function () {
  var dir = '';
  return gulp.src('src/html/**/*.html')
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    .pipe(fileInclude())
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(
        String(file.contents), {
          title: file.frontMatter.title
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    .pipe(gulpif(isProduction, gzip()))
    // get the page directory name from the file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.html', '');
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    // unless it is index.html in which case just ignore it
    .pipe(rename(function (path) {
      if (path.basename !== 'index') {
        path.dirname = path.dirname + '/' + dir;
        path.basename = "index";
        path.extname = ".html";
      }
    }))
    .pipe(gulp.dest(destination));
});

// copy some fonts over
gulp.task('fonts', function () {
  gulp.src('src/fonts/**/*.*', { base: './src/fonts/' })
    .pipe(gulp.dest(destination + '/assets/fonts'));
});

// sass
gulp.task('styles', ['fonts'], function() {
  return gulp.src('src/styles/**/*.scss')
    .pipe(sass({ style: 'expanded', container: './tmp' }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, minifycss()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/css'));
});

// browserify
gulp.task('browserify', ['jshint'], function () {
  return browserify('./src/scripts/main.js')
    .bundle()

    // Stops Gulp from crashing on JS code error
    // https://truongtx.me/2014/07/15/handle-errors-while-using-gulp-watch/
    .on('error', function(err){
      console.log(err.message);
      this.end();
    })

    //Pass desired output filename to vinyl-source-stream
    .pipe(source('bundle.js'))
    // Start piping stream to tasks!
    .pipe(gulp.dest(destination + '/assets/js'));
});

// jshint
gulp.task('jshint', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'));
});

// js
gulp.task('scripts', ['browserify'], function() {
  return gulp.src(destination + '/assets/js/bundle.js')
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, uglify()))
    .pipe(gulpif(isProduction, stripDebug()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/js'));
});

// images
gulp.task('images', function() {
  return gulp.src(['src/images/**/*.png', 'src/images/**/*.jpg', 'src/images/**/*.svg', 'src/images/**/*.gif', 'src/images/**/*.ico'])
    .pipe(
      gulpif(
        isProduction,
        imagemin(
          {
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
          }
        )
      )
    )
    .pipe(gulp.dest(destination + '/assets/img'));
});

// copy xml
gulp.task('xml', function () {
  gulp.src('src/**/*.xml')
    .pipe(gulp.dest(destination));
});

gulp.task('clean', function(cb) {
  del([destination + '/*', destination + '/assets/css', destination + '/assets/fonts', destination + '/assets/js', destination + '/assets/img', destination + '/prototype', '!'+destination+'/editor'], {force:true}, cb);
});

// default build task
gulp.task('default', ['clean'], function() {
  // clean first, then these
  gulp.start('html', 'xml', 'styles', 'scripts', 'images');
});

// watch
gulp.task('watch', ['default'], function() {
  // if anything changes, rebuild
  gulp.watch('src/markdown/**/*.md', ['html']);
  gulp.watch('src/templates/**/*.tpl', ['html']);
  gulp.watch('src/html/**/*.html', ['html']);
  gulp.watch('src/blog/**/*.md', ['html']);
  gulp.watch('src/styles/**/*.scss', ['styles']);
  gulp.watch('src/fonts/**/*.*', ['fonts']);
  gulp.watch('src/scripts/**/*.js', ['scripts']);
  gulp.watch('src/images/**/*', ['images']);
});

// test
<commit_msg>fixing a gulp bug<commit_after>var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var rename = require('gulp-rename');
var del = require('del');
var stripDebug = require('gulp-strip-debug');
var args = require('yargs').argv;
var gulpif = require('gulp-if');
var gzip = require('gulp-gzip');
var fileInclude = require('gulp-file-include');
var markdown = require('gulp-markdown');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var frontMatter = require('gulp-front-matter');
var concat = require('gulp-concat');
var es = require('event-stream');
var mustache = require('mustache');
var fs = require('fs');
var sort = require('sort-stream');
var moment = require('moment');
var config = require('./config').config;

var destination = config.buildDest;

// command line params
// for instance: $ gulp --type production
var isProduction = args.type === 'production';

// blog page pipeline
gulp.task('blog', ['blog-posts-list'], function () {
  // taking the blog post list from the 'blog-posts-list' step
  // and including it into the blog.html template
  return gulp.src('src/blog/blog.html')
    .pipe(es.map(function (file, cb) {
      // first inject the build destination so include knows where to go
      var html = mustache.render(
        String(file.contents), {
          buildDest: config.buildDest
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // then actually include the headers, navs, blogposts, footer and tail
    .pipe(fileInclude())
    // then set the title
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(
        String(file.contents), {
          title: 'Blog'
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // now we have /blog tada
    .pipe(rename('blog/index.html'))
    .pipe(gulp.dest(destination));
});

function capitalize (string) {
  return string[0].toUpperCase() + string.substr(1);
}

// blog post list for blog page
gulp.task('blog-posts-list', ['blog-posts-html'], function () {
  var postlist = String(fs.readFileSync('src/blog/blogposts.html'));

  return gulp.src('src/blog/markdown/**/*.md')
    // extract the frontmatter from the .md add to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // use the frontmatter to populate a blog post list
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(postlist, {
        post: file.frontMatter,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors.map(function(a){return {
          lowercase: a,
          capital: capitalize(a)
        };})
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // sort the list newest-first
    .pipe(sort(function (a, b) {
      if (a.frontMatter.date > b.frontMatter.date) return -1;
      if (a.frontMatter.date < b.frontMatter.date) return 1;
      return 0;
    }))
    // concat the list into a single html
    .pipe(concat('blogposts.html'))
    .pipe(gulp.dest(destination));
});

// fill out the blog post templates
gulp.task('blog-posts-html', function () {
  var post = String(fs.readFileSync('src/blog/post.html'));
  var dir = '';
  return gulp.src('src/blog/markdown/**/*.md')
    // extract frontmatter from markdown, append to file attributes
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    // render the partial
    .pipe(markdown())
    // insert frontmatter and partial as mustache vars into post template
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(post, {
        buildDest: config.buildDest,
        include: file.frontMatter.readfullarticle,
        date: moment(file.frontMatter.date).format('MMMM D, YYYY'),
        authors: file.frontMatter.authors,
        rendered: file.contents
      });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    // include stuff
    .pipe(fileInclude())
    // get the blog post directory name from the .md file name
    .pipe(es.map(function (file, cb) {
      dir = file.path.split('/');
      dir = dir[dir.length - 1].replace('.md', '');
      cb(null, file);
    }))
    // insert handlebars values from frontmatter into head template
    .pipe(es.map(function (file, cb) {
      file.contents = new Buffer(
        mustache.render(
          String(file.contents), {
            title: file.frontMatter.title,
            base: config.baseURL,
            include: file.frontMatter.readfullarticle,
            summary: file.frontMatter.summary
          }));
      cb(null, file);
    }))
    // rename the destination path for the file (avoiding .html)
    .pipe(rename(function (path) {
      path.dirname = dir.split('.')[0];
      path.basename = "index";
      path.extname = ".html";
    }))
    .pipe(gulp.dest(destination + '/blog'));
});

// html
gulp.task('html', ['blog'], function () {
  var dir = '';
  return gulp.src('src/html/**/*.html')
    .pipe(frontMatter({
      property: 'frontMatter',
      remove: true
    }))
    .pipe(fileInclude())
    .pipe(es.map(function (file, cb) {
      var html = mustache.render(
        String(file.contents), {
          title: file.frontMatter.title
        });
      file.contents = new Buffer(html);
      cb(null, file);
    }))
    .pipe(gulpif(isProduction, gzip()))
    // rename the destination path for the file (avoiding .html)
    // unless it is index.html in which case just ignore it
    .pipe(rename(function (path) {
      if (path.basename !== 'index') {
        path.dirname = path.dirname + '/' + path.basename;
        path.basename = "index";
        path.extname = ".html";
      }
    }))
    .pipe(gulp.dest(destination));
});

// copy some fonts over
gulp.task('fonts', function () {
  gulp.src('src/fonts/**/*.*', { base: './src/fonts/' })
    .pipe(gulp.dest(destination + '/assets/fonts'));
});

// sass
gulp.task('styles', ['fonts'], function() {
  return gulp.src('src/styles/**/*.scss')
    .pipe(sass({ style: 'expanded', container: './tmp' }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, minifycss()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/css'));
});

// browserify
gulp.task('browserify', ['jshint'], function () {
  return browserify('./src/scripts/main.js')
    .bundle()

    // Stops Gulp from crashing on JS code error
    // https://truongtx.me/2014/07/15/handle-errors-while-using-gulp-watch/
    .on('error', function(err){
      console.log(err.message);
      this.end();
    })

    //Pass desired output filename to vinyl-source-stream
    .pipe(source('bundle.js'))
    // Start piping stream to tasks!
    .pipe(gulp.dest(destination + '/assets/js'));
});

// jshint
gulp.task('jshint', function() {
  return gulp.src('src/scripts/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'));
});

// js
gulp.task('scripts', ['browserify'], function() {
  return gulp.src(destination + '/assets/js/bundle.js')
    .pipe(gulpif(isProduction, rename({suffix: '.min'})))
    .pipe(gulpif(isProduction, uglify()))
    .pipe(gulpif(isProduction, stripDebug()))
    .pipe(gulpif(isProduction, gzip()))
    .pipe(gulp.dest(destination + '/assets/js'));
});

// images
gulp.task('images', function() {
  return gulp.src(['src/images/**/*.png', 'src/images/**/*.jpg', 'src/images/**/*.svg', 'src/images/**/*.gif', 'src/images/**/*.ico'])
    .pipe(
      gulpif(
        isProduction,
        imagemin(
          {
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
          }
        )
      )
    )
    .pipe(gulp.dest(destination + '/assets/img'));
});

// copy xml
gulp.task('xml', function () {
  gulp.src('src/**/*.xml')
    .pipe(gulp.dest(destination));
});

gulp.task('clean', function(cb) {
  del([destination + '/*', destination + '/assets/css', destination + '/assets/fonts', destination + '/assets/js', destination + '/assets/img', destination + '/prototype', '!'+destination+'/editor'], {force:true}, cb);
});

// default build task
gulp.task('default', ['clean'], function() {
  // clean first, then these
  gulp.start('html', 'xml', 'styles', 'scripts', 'images');
});

// watch
gulp.task('watch', ['default'], function() {
  // if anything changes, rebuild
  gulp.watch('src/markdown/**/*.md', ['html']);
  gulp.watch('src/templates/**/*.tpl', ['html']);
  gulp.watch('src/html/**/*.html', ['html']);
  gulp.watch('src/blog/**/*.md', ['html']);
  gulp.watch('src/styles/**/*.scss', ['styles']);
  gulp.watch('src/fonts/**/*.*', ['fonts']);
  gulp.watch('src/scripts/**/*.js', ['scripts']);
  gulp.watch('src/images/**/*', ['images']);
});

// test
<|endoftext|>


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

'use strict';

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

var insideout = require('./data/insideout.json');

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

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

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

// Copy all files at the root level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/_layout',
    '!app/**/*.ejs',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

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

// Compile and automatically prefix stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/*.scss',
    'app/styles/**/*.css',
    'app/styles/components/components.scss'
  ])
    .pipe($.sourcemaps.init())
    .pipe($.changed('.tmp/styles', {extension: '.css'}))
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Compile the EJS templates
gulp.task('ejs', function () {
  return gulp.src('app/*.ejs')
    .pipe($.ejs({
      insideout: insideout
    }))
    .pipe($.useref())
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'ejs'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.ejs')
    .pipe($.ejs({
      insideout: insideout
    }))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove any unused CSS
    // Note: if not using the Style Guide, you can delete it from
    //       the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update production Style Guide paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean output directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch files for changes & reload
gulp.task('serve', ['styles', 'ejs'], function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: '2015CCARD',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

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

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

// Clear the Gulp caches
gulp.task('clearcache', function( done ) {
    $.cache.clearAll();
    done();
});

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

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

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

'use strict';

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

var insideout = require('./data/insideout.json');

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

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

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

// Copy all files at the root level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/_layout',
    '!app/**/*.ejs',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

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

// Compile and automatically prefix stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/*.scss',
    'app/styles/**/*.css',
    'app/styles/components/components.scss'
  ])
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      precision: 10,
      onError: console.error.bind(console, 'Sass error:')
    }))
    .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Compile the EJS templates
gulp.task('ejs', function () {
  return gulp.src('app/*.ejs')
    .pipe($.ejs({
      insideout: insideout
    }))
    .pipe($.useref())
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'ejs'}));
});

// Scan your HTML for assets & optimize them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/*.ejs')
    .pipe($.ejs({
      insideout: insideout
    }))
    .pipe(assets)
    // Concatenate and minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove any unused CSS
    // Note: if not using the Style Guide, you can delete it from
    //       the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate and minify styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update production Style Guide paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean output directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Watch files for changes & reload
gulp.task('serve', ['styles', 'ejs'], function () {
  browserSync({
    notify: false,
    // Customize the BrowserSync console logging prefix
    logPrefix: '2015CCARD',
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

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

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

// Clear the Gulp caches
gulp.task('clearcache', function( done ) {
    $.cache.clearAll();
    done();
});

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

// Run PageSpeed Insights
gulp.task('pagespeed', function (cb) {
  // Update the below URL to the public URL of your site
  pagespeed.output('example.com', {
    strategy: 'mobile',
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb);
});

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


<commit_before>/* eslint-env node */

/** Gulp Commands

  gulp command*
    [--export ModuleType]
    [--name ModuleName]
    [--testport TestPort]
    [--testfiles TestFiles]

  Module name (ModuleName):
    Compile this to "y.js" (default)

  Supported module types (ModuleType):
    - amd
    - amdStrict
    - common
    - commonStrict
    - ignore (default)
    - system
    - umd
    - umdStrict

  Test port (TestPort):
    Serve the specs on port 8888 (default)

  Test files (TestFiles):
    Specify which specs to use!

  Commands:
    - build:deploy
        Build this library for deployment (es6->es5, minified)
    - dev:browser
        Watch the ./src directory.
        Builds the library on changes.
        Starts an http-server and serves the test suite on http://127.0.0.1:8888.
    - dev:node
        Watch the ./src directory.
        Builds and specs the library on changes.
        Usefull to run with node-inspector.
        `node-debug $(which gulp) dev:node
    - test:
        Test this library
*/

var gulp = require('gulp')
var minimist = require('minimist')
var concat = require('gulp-concat')
var $ = require('gulp-load-plugins')()

var options = minimist(process.argv.slice(2), {
  string: ['export', 'name', 'testport', 'testfiles', 'regenerator'],
  default: {
    export: 'ignore',
    name: 'y-webrtc.js',
    testport: '8888',
    testfiles: 'src/**/*.js',
    regenerator: process.version < 'v0.12'
  }
})

var polyfills = [
]

var concatOrder = [
  'WebRTC.js'
]

var files = {
  src: polyfills.concat(concatOrder.map(function (f) {
    return 'src/' + f
  })),
  test: [].concat(concatOrder.map(function (f) {
    return 'build/' + f
  }).concat(['build/**/*.spec.js']))
}

if (options.regenerator) {
  files.test = polyfills.concat(files.test)
}

gulp.task('deploy:build', function () {
  return gulp.src(files.src)
    .pipe($.sourcemaps.init())
    .pipe(concat('y-webrtc.js'))
    .pipe($.babel({
      loose: 'all',
      modules: 'ignore',
      experimental: true
    }))
    .pipe($.uglify())
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('./dist/'))
})

gulp.task('deploy:updateSubmodule', function () {
  return $.git.updateSubmodule({ args: '--init' })
})

gulp.task('deploy:copy', function () {
  return gulp.src(['README.md'], {base: '.'})
    .pipe(gulp.dest('dist/'))
})

gulp.task('deploy:bump', function () {
  return gulp.src(['./package.json', './dist/package.json'], {base: '.'})
    .pipe($.bump({type: 'patch'}))
    .pipe(gulp.dest('./'))
})

gulp.task('deploy', ['deploy:updateSubmodule', 'deploy:bump', 'deploy:build', 'deploy:copy'], function () {
  return gulp.src('./package.json', {read: false})
    .pipe($.shell([
      'standard',
      'echo "Deploying version <%= getVersion(file.path) %>"',
      'git pull',
      'cd ./dist/ && git add -A',
      'cd ./dist/ && git commit -am "Deploy <%= getVersion(file.path) %>" -n',
      'cd ./dist/ && git push',
      'cd ./dist/ && git tag -a v<%= getVersion(file.path) %> -m "Release <%= getVersion(file.path) %>"',
      'cd ./dist/ && git push origin --tags',
      'git commit -am "Release <%= getVersion(file.path) %>" -n',
      'git push'
    ], {
      templateData: {
        getVersion: function (s) {
          return require(s).version
        }
      }
    }))
})

gulp.task('build:test', function () {
  var babelOptions = {
    loose: 'all',
    modules: 'ignore',
    experimental: true
  }
  if (!options.regenerator) {
    babelOptions.blacklist = 'regenerator'
  }
  gulp.src(files.src)
    .pipe($.sourcemaps.init())
    .pipe(concat('y-webrtc.js'))
    .pipe($.babel(babelOptions))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.'))

  return gulp.src('src/**/*.js')
    .pipe($.sourcemaps.init())
    .pipe($.babel(babelOptions))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('build'))
})

gulp.task('dev:node', ['test'], function () {
  gulp.watch('src/**/*.js', ['test'])
})

gulp.task('dev:browser', ['build:test'], function () {
  gulp.watch('src/**/*.js', ['build:test'])

  gulp.src(files.test)
    .pipe($.watch(['build/**/*.js']))
    .pipe($.jasmineBrowser.specRunner())
    .pipe($.jasmineBrowser.server({port: options.testport}))
})

gulp.task('dev', ['build:test'], function () {
  gulp.start('dev:browser')
  gulp.start('dev:node')
})

gulp.task('copy:dist', ['deploy:build'], function () {
  return gulp.src(['./dist/y-webrtc.js', './dist/y-webrtc.js.map'])
    .pipe(gulp.dest('./dist/Examples/bower_components/yjs/'))
})

gulp.task('dev:examples', ['copy:dist'], function () {
  gulp.watch('src/**/*.js', ['copy:dist'])
  return $.serve('dist/Examples')()
})

gulp.task('test', ['build:test'], function () {
  var testfiles = files.test
  if (typeof Promise === 'undefined') {
    testfiles.concat(['src/polyfills.js'])
  }
  return gulp.src(testfiles)
    .pipe($.jasmine({
      verbose: true,
      includeStuckTrace: true
    }))
})

gulp.task('default', ['test'])
<commit_msg>fixed copy:dist<commit_after>/* eslint-env node */

/** Gulp Commands

  gulp command*
    [--export ModuleType]
    [--name ModuleName]
    [--testport TestPort]
    [--testfiles TestFiles]

  Module name (ModuleName):
    Compile this to "y.js" (default)

  Supported module types (ModuleType):
    - amd
    - amdStrict
    - common
    - commonStrict
    - ignore (default)
    - system
    - umd
    - umdStrict

  Test port (TestPort):
    Serve the specs on port 8888 (default)

  Test files (TestFiles):
    Specify which specs to use!

  Commands:
    - build:deploy
        Build this library for deployment (es6->es5, minified)
    - dev:browser
        Watch the ./src directory.
        Builds the library on changes.
        Starts an http-server and serves the test suite on http://127.0.0.1:8888.
    - dev:node
        Watch the ./src directory.
        Builds and specs the library on changes.
        Usefull to run with node-inspector.
        `node-debug $(which gulp) dev:node
    - test:
        Test this library
*/

var gulp = require('gulp')
var minimist = require('minimist')
var concat = require('gulp-concat')
var $ = require('gulp-load-plugins')()

var options = minimist(process.argv.slice(2), {
  string: ['export', 'name', 'testport', 'testfiles', 'regenerator'],
  default: {
    export: 'ignore',
    name: 'y-webrtc.js',
    testport: '8888',
    testfiles: 'src/**/*.js',
    regenerator: process.version < 'v0.12'
  }
})

var polyfills = [
]

var concatOrder = [
  'WebRTC.js'
]

var files = {
  src: polyfills.concat(concatOrder.map(function (f) {
    return 'src/' + f
  })),
  test: [].concat(concatOrder.map(function (f) {
    return 'build/' + f
  }).concat(['build/**/*.spec.js']))
}

if (options.regenerator) {
  files.test = polyfills.concat(files.test)
}

gulp.task('deploy:build', function () {
  return gulp.src(files.src)
    .pipe($.sourcemaps.init())
    .pipe(concat('y-webrtc.js'))
    .pipe($.babel({
      loose: 'all',
      modules: 'ignore',
      experimental: true
    }))
    .pipe($.uglify())
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('./dist/'))
})

gulp.task('deploy:updateSubmodule', function () {
  return $.git.updateSubmodule({ args: '--init' })
})

gulp.task('deploy:copy', function () {
  return gulp.src(['README.md'], {base: '.'})
    .pipe(gulp.dest('dist/'))
})

gulp.task('deploy:bump', function () {
  return gulp.src(['./package.json', './dist/package.json'], {base: '.'})
    .pipe($.bump({type: 'patch'}))
    .pipe(gulp.dest('./'))
})

gulp.task('deploy', ['deploy:updateSubmodule', 'deploy:bump', 'deploy:build', 'deploy:copy'], function () {
  return gulp.src('./package.json', {read: false})
    .pipe($.shell([
      'standard',
      'echo "Deploying version <%= getVersion(file.path) %>"',
      'git pull',
      'cd ./dist/ && git add -A',
      'cd ./dist/ && git commit -am "Deploy <%= getVersion(file.path) %>" -n',
      'cd ./dist/ && git push',
      'cd ./dist/ && git tag -a v<%= getVersion(file.path) %> -m "Release <%= getVersion(file.path) %>"',
      'cd ./dist/ && git push origin --tags',
      'git commit -am "Release <%= getVersion(file.path) %>" -n',
      'git push'
    ], {
      templateData: {
        getVersion: function (s) {
          return require(s).version
        }
      }
    }))
})

gulp.task('build:test', function () {
  var babelOptions = {
    loose: 'all',
    modules: 'ignore',
    experimental: true
  }
  if (!options.regenerator) {
    babelOptions.blacklist = 'regenerator'
  }
  gulp.src(files.src)
    .pipe($.sourcemaps.init())
    .pipe(concat('y-webrtc.js'))
    .pipe($.babel(babelOptions))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.'))

  return gulp.src('src/**/*.js')
    .pipe($.sourcemaps.init())
    .pipe($.babel(babelOptions))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('build'))
})

gulp.task('dev:node', ['test'], function () {
  gulp.watch('src/**/*.js', ['test'])
})

gulp.task('dev:browser', ['build:test'], function () {
  gulp.watch('src/**/*.js', ['build:test'])

  gulp.src(files.test)
    .pipe($.watch(['build/**/*.js']))
    .pipe($.jasmineBrowser.specRunner())
    .pipe($.jasmineBrowser.server({port: options.testport}))
})

gulp.task('dev', ['build:test'], function () {
  gulp.start('dev:browser')
  gulp.start('dev:node')
})

gulp.task('copy:dist', ['deploy:build'], function () {
  return gulp.src(['./dist/y-webrtc.js', './dist/y-webrtc.js.map'])
    .pipe(gulp.dest('../yjs/dist/Examples/bower_components/y-webrtc/'))
})

gulp.task('dev:examples', ['copy:dist'], function () {
  return gulp.watch('src/**/*.js', ['copy:dist'])
})

gulp.task('test', ['build:test'], function () {
  var testfiles = files.test
  if (typeof Promise === 'undefined') {
    testfiles.concat(['src/polyfills.js'])
  }
  return gulp.src(testfiles)
    .pipe($.jasmine({
      verbose: true,
      includeStuckTrace: true
    }))
})

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


<commit_before>var gulp = require('gulp');
var karma = require('karma').server;
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var path = require('path');
var plumber = require('gulp-plumber');
var runSequence = require('run-sequence');
var jshint = require('gulp-jshint');
var bump = require('gulp-bump');
var git = require('gulp-git');
var filter = require('gulp-filter');
var tagVersion = require('gulp-tag-version');

/**
 * File patterns
 **/

// Root directory
var rootDirectory = path.resolve('./');

// Source directory for build process
var sourceDirectory = path.join(rootDirectory, './src');

var sourceFiles = [

    // Make sure module files are handled first
    path.join(sourceDirectory, '/**/*.module.js'),

    // Then add all JavaScript files
    path.join(sourceDirectory, '/**/*.js')
];

var lintFiles = [
    'gulpfile.js',
    // Karma configuration
    'karma-*.conf.js'
].concat(sourceFiles);

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */

function inc(importance) {
    // get all the files to bump version in
    return gulp.src(['./package.json', './bower.json'])
        // bump the version number in those files
        .pipe(bump({type: importance}))
        // save it back to filesystem
        .pipe(gulp.dest('./'))
        // commit the changed version number
        .pipe(git.commit('bumps package version'))

        // read only one file to get the version number
        .pipe(filter('package.json'))
        // **tag it in the repository**
        .pipe(tagVersion())
        .pipe(git.push('origin', 'master', {args: '--tags'}));
}

gulp.task('patch', function () {
    return inc('patch');
});
gulp.task('feature', function () {
    return inc('minor');
});
gulp.task('release', function () {
    return inc('major');
});

gulp.task('build', function () {
    gulp.src(sourceFiles)
        .pipe(plumber())
        .pipe(concat('core-games-ui.js'))
        .pipe(gulp.dest('./dist/'))
        .pipe(uglify())
        .pipe(rename('core-games-ui.min.js'))
        .pipe(gulp.dest('./dist'));
});

/**
 * Process
 */
gulp.task('process-all', function (done) {
    runSequence('jshint', 'test-src', 'build', done);
});

/**
 * Watch task
 */
gulp.task('watch', function () {

    // Watch JavaScript files
    gulp.watch(sourceFiles, ['process-all']);
});

/**
 * Validate source JavaScript
 */
gulp.task('jshint', function () {
    return gulp.src(lintFiles)
        .pipe(plumber())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail'));
});

/**
 * Run test once and exit
 */
gulp.task('test-src', function (done) {
    karma.start({
        configFile: __dirname + '/karma-src.conf.js',
        singleRun: true
    }, done);
});

/**
 * Run test once and exit
 */
gulp.task('test-dist-concatenated', function (done) {
    karma.start({
        configFile: __dirname + '/karma-dist-concatenated.conf.js',
        singleRun: true
    }, done);
});

/**
 * Run test once and exit
 */
gulp.task('test-dist-minified', function (done) {
    karma.start({
        configFile: __dirname + '/karma-dist-minified.conf.js',
        singleRun: true
    }, done);
});

gulp.task('default', function () {
    runSequence('process-all', 'watch');
});
<commit_msg>formatting gulpfile and trying to re-add git push<commit_after>var gulp = require('gulp');
var karma = require('karma').server;
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var path = require('path');
var plumber = require('gulp-plumber');
var runSequence = require('run-sequence');
var jshint = require('gulp-jshint');
var bump = require('gulp-bump');
var git = require('gulp-git');
var filter = require('gulp-filter');
var tagVersion = require('gulp-tag-version');

/**
 * File patterns
 **/

// Root directory
var rootDirectory = path.resolve('./');

// Source directory for build process
var sourceDirectory = path.join(rootDirectory, './src');

var sourceFiles = [

    // Make sure module files are handled first
    path.join(sourceDirectory, '/**/*.module.js'),

    // Then add all JavaScript files
    path.join(sourceDirectory, '/**/*.js')
];

var lintFiles = [
    'gulpfile.js',
    // Karma configuration
    'karma-*.conf.js'
].concat(sourceFiles);

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */

function inc(importance) {
    // get all the files to bump version in
    return gulp.src(['./package.json', './bower.json'])
        // bump the version number in those files
        .pipe(bump({type: importance}))
        // save it back to filesystem
        .pipe(gulp.dest('./'))
        // commit the changed version number
        .pipe(git.commit('bumps package version'))

        // read only one file to get the version number
        .pipe(filter('package.json'))
        // **tag it in the repository**
        .pipe(tagVersion());
}

gulp.task('patch', function () {
    return inc('patch');
});
gulp.task('feature', function () {
    return inc('minor');
});
gulp.task('release', function () {
    return inc('major');
});

gulp.task('build', function () {
    gulp.src(sourceFiles)
        .pipe(plumber())
        .pipe(concat('core-games-ui.js'))
        .pipe(gulp.dest('./dist/'))
        .pipe(uglify())
        .pipe(rename('core-games-ui.min.js'))
        .pipe(gulp.dest('./dist'));
});

/**
 * Process
 */
gulp.task('process-all', function (done) {
    runSequence('jshint', 'test-src', 'build', done);
});

/**
 * Watch task
 */
gulp.task('watch', function () {

    // Watch JavaScript files
    gulp.watch(sourceFiles, ['process-all']);
});

/**
 * Validate source JavaScript
 */
gulp.task('jshint', function () {
    return gulp.src(lintFiles)
        .pipe(plumber())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail'));
});

/**
 * Run test once and exit
 */
gulp.task('test-src', function (done) {
    karma.start({
        configFile: __dirname + '/karma-src.conf.js',
        singleRun: true
    }, done);
});

/**
 * Run test once and exit
 */
gulp.task('test-dist-concatenated', function (done) {
    karma.start({
        configFile: __dirname + '/karma-dist-concatenated.conf.js',
        singleRun: true
    }, done);
});

/**
 * Run test once and exit
 */
gulp.task('test-dist-minified', function (done) {
    karma.start({
        configFile: __dirname + '/karma-dist-minified.conf.js',
        singleRun: true
    }, done);
});

gulp.task('default', function () {
    runSequence('process-all', 'watch');
});
<|endoftext|>


<commit_before>import * as _collections from './collections'

// Source: https://gist.github.com/dperini/729294
export const URL_REGEX = /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[\/?#]\S*)?/i

export const typeSafeEq = (x, y) => x.toString() === y.toString()
export const orStr = e => e || ''
export const orArr = e => e || []
export const allPresent = (...objs) => objs.reduce((x,y) => !!x && !!y, true)

const escSpecialChars = str => str.replace(/\$|\{|\}|\_/g, e => `\\${e}`)
const toSource = re => re instanceof RegExp ? re.source : escSpecialChars(re)
const parenthesize = str => `(?:${str})`
export function or(res) {
  const strParts = res.map(toSource).filter(_collections.isPresent).map(parenthesize)
  const lengthSorted = _.sortBy(strParts, prt => -prt.length) // To avoid partial replacements.
  return new RegExp(parenthesize(lengthSorted.join('|')), 'g')
}

export function replaceByMap(str, replacementMap) {
  const regex = or(Object.keys(replacementMap))
  return str.replace(regex, match => replacementMap[match])
}

export function makeURLsMarkdown(text) {
  const fullRegex = new RegExp(`\\[.+\\]\\(${URL_REGEX.source}\\)`, 'g')
  let transformedText = ''
  let prevIndex = 0
  let matchArr
  while ((matchArr = fullRegex.exec(text)) !== null) {
    const partial = text.slice(prevIndex, matchArr.index)
    transformedText += partial.replace(URL_REGEX, match => `[${match}](${match})`)
    transformedText += matchArr[0]
    prevIndex = matchArr.index + matchArr[0].length
  }
  const partial = text.slice(prevIndex)
  transformedText += partial.replace(URL_REGEX, match => `[${match}](${match})`)

  return transformedText
}
<commit_msg>A bit more type safety to handle an error Icaught when navigatign to models.<commit_after>import * as _collections from './collections'

// Source: https://gist.github.com/dperini/729294
export const URL_REGEX = /(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[\/?#]\S*)?/i

export const typeSafeEq = (x, y) => !x ? !y : !!y && x.toString() === y.toString()
export const orStr = e => e || ''
export const orArr = e => e || []
export const allPresent = (...objs) => objs.reduce((x,y) => !!x && !!y, true)

const escSpecialChars = str => str.replace(/\$|\{|\}|\_/g, e => `\\${e}`)
const toSource = re => re instanceof RegExp ? re.source : escSpecialChars(re)
const parenthesize = str => `(?:${str})`
export function or(res) {
  const strParts = res.map(toSource).filter(_collections.isPresent).map(parenthesize)
  const lengthSorted = _.sortBy(strParts, prt => -prt.length) // To avoid partial replacements.
  return new RegExp(parenthesize(lengthSorted.join('|')), 'g')
}

export function replaceByMap(str, replacementMap) {
  const regex = or(Object.keys(replacementMap))
  return str.replace(regex, match => replacementMap[match])
}

export function makeURLsMarkdown(text) {
  const fullRegex = new RegExp(`\\[.+\\]\\(${URL_REGEX.source}\\)`, 'g')
  let transformedText = ''
  let prevIndex = 0
  let matchArr
  while ((matchArr = fullRegex.exec(text)) !== null) {
    const partial = text.slice(prevIndex, matchArr.index)
    transformedText += partial.replace(URL_REGEX, match => `[${match}](${match})`)
    transformedText += matchArr[0]
    prevIndex = matchArr.index + matchArr[0].length
  }
  const partial = text.slice(prevIndex)
  transformedText += partial.replace(URL_REGEX, match => `[${match}](${match})`)

  return transformedText
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create();

var DEST = 'build/';
var ExtractTextPlugin = require("extract-text-webpack-plugin");
gulp.task('scripts', function () {
    return gulp.src([
        'src/js/helpers/*.js',
        'src/js/*.js',
    ])
        .pipe(concat('custom.js'))
        .pipe(gulp.dest(DEST + '/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest(DEST + '/js'))
        .pipe(browserSync.stream());
});

// TODO: Maybe we can simplify how sass compile the minify and unminify version
var compileSASS = function (filename, options) {
    return sass('src/scss/*.scss', options)
        .pipe(autoprefixer('last 2 versions', '> 5%'))
        .pipe(concat(filename))
        .pipe(gulp.dest(DEST + '/css'))
        .pipe(browserSync.stream());
};

gulp.task('sass', function () {
    return compileSASS('custom.css', {});
});

gulp.task('sass-minify', function () {
    return compileSASS('custom.min.css', { style: 'compressed' });
});

gulp.task('browser-sync', function () {
    browserSync.init({
        server: {
            baseDir: './'
        },
        startPath: './production/index.html'
    });
});

gulp.task('watch', function () {
    // Watch .html files
    gulp.watch('production/*.html', browserSync.reload);
    // Watch .js files
    //gulp.watch('src/js/*.js', ['scripts']);
    // Watch .scss files
    gulp.watch('src/scss/*.scss', ['sass', 'sass-minify']);
});

// Default Task
gulp.task('default', ['browser-sync', 'watch']);
var webpackStream = require('webpack-stream');
var BowerWebpackPlugin = require('bower-webpack-plugin');
var webpack = require("webpack");
var named = require('vinyl-named');
var plugins = [];

plugins.push(new BowerWebpackPlugin({
    modulesDirectories: ["vendors"],
    manifestFiles: "bower.json",
    excludes: /.*\.less/
}));

plugins.push(new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
    jQuery: 'jquery',
    $: 'jquery'
}));

var getStyleConfig = function () {
    plugins = [];
    plugins.push(new BowerWebpackPlugin({
        modulesDirectories: ["vendors"],
        manifestFiles: "bower.json",
        excludes: /.*\.less/
    }));

    plugins.push(new webpack.ProvidePlugin({
        'window.jQuery': 'jquery',
        'window.$': 'jquery',
        jQuery: 'jquery',
        $: 'jquery'
    }));

    return {
        devtool: 'source-map',
        module: {
            loaders: [
                { test: /\.png$/, loader: 'url-loader?limit=100000' },
                { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css?minimize!sass") },
                {
                    test: /\.scss$/,
                    loader: ExtractTextPlugin.extract("style", "css?minimize!sass")
                },
                { test: /\.(jpg|woff|svg|ttf|eot)([\?]?.*)$/, loader: "file-loader?name=img/[name].[ext]" }
            ]
        },
        plugins: plugins
    };
};
gulp.task('build-common-style', function () {
    let config = getStyleConfig();
    config.plugins.push(new ExtractTextPlugin("common.style.css"));
    return gulp.src('src/config/common-style.js')
        .pipe(named())
        .pipe(webpackStream(config))
        .pipe(gulp.dest('production/assets/css/'));
});
gulp.task('build-custom-style', function () {
    var config = getStyleConfig();
    config.plugins.push(new ExtractTextPlugin("custom.style.css"));
    return gulp.src('src/config/custom-style.js')
        .pipe(named())
        .pipe(webpackStream(config))
        .pipe(gulp.dest('production/assets/css/'));
});
var jsDist = 'production/assets/js/';
gulp.task('build-vendors', function () {
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }, exclude: /css|png|jpg|gif｜\.min\.js$/, minimize: true
    }));
    plugins.push(new webpack.optimize.DedupePlugin());
    return gulp.src('src/config/vendors.js')
        .pipe(named())
        .pipe(webpackStream({
            devtool: 'eval-source-map',
            module: {
                loaders: [
                    { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
                    {
                        test: /\.scss$/,
                        loaders: ["style", "css", "sass"]
                    }
                ]
            },
            plugins: plugins
        }))
        .pipe(gulp.dest(jsDist));
});

gulp.task('joe', function () {
    return gulp.src('src/config/joe.js')
        .pipe(named())
        .pipe(webpackStream({
            devtool: 'eval-source-map',
            module: {
                loaders: [

                    { test: /\.css$/, loader: "style!css" },
                    {
                        test: /\.scss$/,
                        loaders: ["style", "css", "sass"]
                    }
                ]
            },
            plugins: plugins
        }))
        .pipe(gulp.dest(jsDist));
});<commit_msg>build css task<commit_after>var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    browserSync = require('browser-sync').create();

var DEST = 'build/';
var ExtractTextPlugin = require("extract-text-webpack-plugin");
gulp.task('scripts', function () {
    return gulp.src([
        'src/js/helpers/*.js',
        'src/js/*.js',
    ])
        .pipe(concat('custom.js'))
        .pipe(gulp.dest(DEST + '/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest(DEST + '/js'))
        .pipe(browserSync.stream());
});

// TODO: Maybe we can simplify how sass compile the minify and unminify version
var compileSASS = function (filename, options) {
    return sass('src/scss/*.scss', options)
        .pipe(autoprefixer('last 2 versions', '> 5%'))
        .pipe(concat(filename))
        .pipe(gulp.dest(DEST + '/css'))
        .pipe(browserSync.stream());
};

gulp.task('sass', function () {
    return compileSASS('custom.css', {});
});

gulp.task('sass-minify', function () {
    return compileSASS('custom.min.css', { style: 'compressed' });
});

gulp.task('browser-sync', function () {
    browserSync.init({
        server: {
            baseDir: './'
        },
        startPath: './production/index.html'
    });
});

gulp.task('watch', function () {
    // Watch .html files
    gulp.watch('production/*.html', browserSync.reload);
    // Watch .js files
    //gulp.watch('src/js/*.js', ['scripts']);
    // Watch .scss files
    gulp.watch('src/scss/*.scss', ['sass', 'sass-minify']);
});

// Default Task
gulp.task('default', ['browser-sync', 'watch']);
var webpackStream = require('webpack-stream');
var BowerWebpackPlugin = require('bower-webpack-plugin');
var webpack = require("webpack");
var named = require('vinyl-named');
var plugins = [];

plugins.push(new BowerWebpackPlugin({
    modulesDirectories: ["vendors"],
    manifestFiles: "bower.json",
    excludes: /.*\.less/
}));

plugins.push(new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
    jQuery: 'jquery',
    $: 'jquery'
}));

var getStyleConfig = function () {
    plugins = [];
    return {
        module: {
            loaders: [
                { test: /\.png$/, loader: 'url-loader?limit=100000' },
                { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css?minimize!sass") },
                {
                    test: /\.scss$/,
                    loader: ExtractTextPlugin.extract("style", "css?minimize!sass")
                },
                { test: /\.(jpg|woff|svg|ttf|eot)([\?]?.*)$/, loader: "file-loader?name=img/[name].[ext]" }
            ]
        },
        plugins: plugins
    };
};
//bulid css
gulp.task('build-common-style', function () {
    var config = getStyleConfig();
    config.plugins.push(new ExtractTextPlugin("common.style.css"));
    return gulp.src('src/config/common-style.js')
        .pipe(named())
        .pipe(webpackStream(config))
        .pipe(gulp.dest('production/assets/css/'));
});
gulp.task('build-custom-style', function () {
    var config = getStyleConfig();
    config.plugins.push(new ExtractTextPlugin("custom.style.css"));
    return gulp.src('src/config/custom-style.js')
        .pipe(named())
        .pipe(webpackStream(config))
        .pipe(gulp.dest('production/assets/css/'));
});
gulp.task('watch-css', function () {
    // Watch .html files
    // Watch .scss files
    gulp.watch('src/scss/**.scss', ['build-custom-style']);
});
//end css build
var jsDist = 'production/assets/js/';
gulp.task('build-vendors', function () {
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }, exclude: /css|png|jpg|gif｜\.min\.js$/, minimize: true
    }));
    plugins.push(new webpack.optimize.DedupePlugin());
    return gulp.src('src/config/vendors.js')
        .pipe(named())
        .pipe(webpackStream({
            devtool: 'eval-source-map',
            module: {
                loaders: [
                    { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
                    {
                        test: /\.scss$/,
                        loaders: ["style", "css", "sass"]
                    }
                ]
            },
            plugins: plugins
        }))
        .pipe(gulp.dest(jsDist));
});

gulp.task('joe', function () {
    return gulp.src('src/config/joe.js')
        .pipe(named())
        .pipe(webpackStream({
            devtool: 'eval-source-map',
            module: {
                loaders: [

                    { test: /\.css$/, loader: "style!css" },
                    {
                        test: /\.scss$/,
                        loaders: ["style", "css", "sass"]
                    }
                ]
            },
            plugins: plugins
        }))
        .pipe(gulp.dest(jsDist));
});<|endoftext|>


<commit_before>/*jshint node: true */

'use strict';

var gulp = require('gulp');

var argv = require('yargs').argv;
var fs = require('fs');
var request = require('request');
var through = require('through2');
var typescript = require('gulp-tsc');

var onError = function(err) {
  if (err) {
    console.log(err);
  }
};

var options = {
  mlHost: argv['ml-host'] || 'ml8-ml1',
  mlPort: argv['ml-port'] || '8000',
  mlUser: argv['ml-user'] || 'admin',
  mlPass: argv['ml-pass'] || 'admin'
};

gulp.task('generate', function(){
  var query;

  fs.readFile('qconsole/generate-definitions.xqy', null, function(err, data) {
    query = data.toString();
  });

  return gulp.src(['xml/**/*.xml'])
  .pipe(through.obj(function (file, enc, cb) {

    console.log(file.path);

    var outFile = file.path.replace('/xml/', '/ts/').replace('.xml', '.d.ts');

    var xml = file.contents.toString();
    var escapedXml = xml.replace(/\\/gm, '\\\\').replace(/"/gm, '\\"').replace(/(\n\r|\r\n|\n|\r)/gm, '\\n').replace(/\t/gm, '\\t');

    request({
      method: 'POST',
      url: 'http://' + options.mlHost + ':' + options.mlPort + '/v1/eval',
      form: {
        xquery: query,
        vars: '{ xml: "'+ escapedXml +'"}'
      },
      auth: {
        user: options.mlUser,
        pass: options.mlPass,
        sendImmediately: false
      }
    }, function(err, httpResponse, body) {
      // get rid of multipart response wrapping
      body = body.replace(/^([^\r]*\r\n){5}/, '').replace(/\r\n[^\r]*\r\n$/, '');

      if (err || httpResponse.statusCode !== 200) {
        console.log('FAILED!');
        console.log(body);
        //console.log(escapedXml);
      } else {
        fs.writeFile(outFile, body, onError);
      }
    });

    cb(null, file);
  }));
});

gulp.task('validate', function(){
  gulp.src(['ts/**/*.ts'])
  .pipe(typescript());
});

// Default Task
gulp.task('default', ['generate', 'validate']);
<commit_msg>Fixed #11: fixed typescript validation, made gulpfile more robust<commit_after>/*jshint node: true */

'use strict';

var gulp = require('gulp');

var argv = require('yargs').argv;
var fs = require('fs');
var request = require('request');
var through = require('through2');
var typescript = require('gulp-tsc');

var onError = function(err) {
  if (err) {
    console.log(err);
  }
};

var options = {
  mlHost: argv['ml-host'] || 'ml8-ml1',
  mlPort: argv['ml-port'] || '8000',
  mlUser: argv['ml-user'] || 'admin',
  mlPass: argv['ml-pass'] || 'admin'
};

gulp.task('generate', function(){
  var query;

  fs.readFile('qconsole/generate-definitions.xqy', null, function(err, data) {
    query = data.toString();
  });

  return gulp.src(['xml/**/*.xml'])
  .pipe(through.obj(function (file, enc, cb) {

    console.log(file.path);

    var outFile = file.path.replace('/xml/', '/ts/').replace('.xml', '.d.ts');

    var xml = file.contents.toString();
    var escapedXml = xml.replace(/\\/gm, '\\\\').replace(/"/gm, '\\"').replace(/(\n\r|\r\n|\n|\r)/gm, '\\n').replace(/\t/gm, '\\t');

    request({
      method: 'POST',
      url: 'http://' + options.mlHost + ':' + options.mlPort + '/v1/eval',
      form: {
        xquery: query,
        vars: '{ xml: "'+ escapedXml +'"}'
      },
      auth: {
        user: options.mlUser,
        pass: options.mlPass,
        sendImmediately: false
      }
    }, function(err, httpResponse, body) {
      //console.log(body);
      try {
        // get rid of multipart response wrapping
        body = body.replace(/^([^\r]*\r\n){5}/, '').replace(/\r\n[^\r]*\r\n$/, '');

        if (err || httpResponse.statusCode !== 200) {
          console.log('FAILED!');
          console.log(body);
          //console.log(escapedXml);
        } else {
          fs.writeFile(outFile, body, onError);
        }

        cb(null, file);
      } catch (e) {
        console.log(e);
      }
    });
  }));
});

gulp.task('validate', ['generate'], function(){
  gulp.src(['ts/**/*.ts'])
  .pipe(typescript({emitError: false}))
  ;
});

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