<commit_before>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

/*eslint-env node */

'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 reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');

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

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// 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 () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/precache.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .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'}));
});

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

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  var DEST_DIR = 'dist/elements';

  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate a list of files that should be precached when serving from 'dist'.
// The list will be consumed by the <platinum-sw-cache> element.
gulp.task('precache', function (callback) {
  var dir = 'dist';

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      var filePath = path.join(dir, 'precache.json');
      fs.writeFile(filePath, JSON.stringify(files), callback);
    }
  });
});

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

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // 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: {
      baseDir: ['.tmp', 'app'],
      middleware: [ historyApiFallback() ],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // 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',
    middleware: [ historyApiFallback() ]
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['images', 'fonts', 'html'],
    'vulcanize',
    'precache',
    cb);
    // Note: add , 'precache' , after 'vulcanize', if your are going to use Service Worker
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
// require('web-component-tester').gulp.init(gulp);

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {
  // Ignore
}
<commit_msg>Add deploy task<commit_after>/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/

/*eslint-env node */

'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 reload = browserSync.reload;
var merge = require('merge-stream');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var historyApiFallback = require('connect-history-api-fallback');

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

var styleTask = function (stylesPath, srcs) {
  return gulp.src(srcs.map(function(src) {
      return path.join('app', stylesPath, src);
    }))
    .pipe($.changed(stylesPath, {extension: '.css'}))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/' + stylesPath))
    .pipe($.if('*.css', $.cssmin()))
    .pipe(gulp.dest('dist/' + stylesPath))
    .pipe($.size({title: stylesPath}));
};

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  return styleTask('styles', ['**/*.css']);
});

gulp.task('elements', function () {
  return styleTask('elements', ['**/*.css']);
});

// 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 () {
  var app = gulp.src([
    'app/*',
    '!app/test',
    '!app/precache.json'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));

  var bower = gulp.src([
    'bower_components/**/*'
  ]).pipe(gulp.dest('dist/bower_components'));

  var elements = gulp.src(['app/elements/**/*.html'])
    .pipe(gulp.dest('dist/elements'));

  var swBootstrap = gulp.src(['bower_components/platinum-sw/bootstrap/*.js'])
    .pipe(gulp.dest('dist/elements/bootstrap'));

  var swToolbox = gulp.src(['bower_components/sw-toolbox/*.js'])
    .pipe(gulp.dest('dist/sw-toolbox'));

  var vulcanized = gulp.src(['app/elements/elements.html'])
    .pipe($.rename('elements.vulcanized.html'))
    .pipe(gulp.dest('dist/elements'));

  return merge(app, bower, elements, vulcanized, swBootstrap, swToolbox)
    .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'}));
});

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

  return gulp.src(['app/**/*.html', '!app/{elements,test}/**/*.html'])
    // Replace path for vulcanized assets
    .pipe($.if('*.html', $.replace('elements/elements.html', 'elements/elements.vulcanized.html')))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.cssmin()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({
      quotes: true,
      empty: true,
      spare: true
    })))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Vulcanize imports
gulp.task('vulcanize', function () {
  var DEST_DIR = 'dist/elements';

  return gulp.src('dist/elements/elements.vulcanized.html')
    .pipe($.vulcanize({
      stripComments: true,
      inlineCss: true,
      inlineScripts: true
    }))
    .pipe(gulp.dest(DEST_DIR))
    .pipe($.size({title: 'vulcanize'}));
});

// Generate a list of files that should be precached when serving from 'dist'.
// The list will be consumed by the <platinum-sw-cache> element.
gulp.task('precache', function (callback) {
  var dir = 'dist';

  glob('{elements,scripts,styles}/**/*.*', {cwd: dir}, function(error, files) {
    if (error) {
      callback(error);
    } else {
      files.push('index.html', './', 'bower_components/webcomponentsjs/webcomponents-lite.min.js');
      var filePath = path.join(dir, 'precache.json');
      fs.writeFile(filePath, JSON.stringify(files), callback);
    }
  });
});

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

// Deploy to github pages
gulp.task('deploy', function () {
  return gulp.src('./dist/**/*')
  .pipe($.ghPages());
});

// Watch Files For Changes & Reload
gulp.task('serve', ['styles', 'elements', 'images'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // 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: {
      baseDir: ['.tmp', 'app'],
      middleware: [ historyApiFallback() ],
      routes: {
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    logPrefix: 'PSK',
    snippetOptions: {
      rule: {
        match: '',
        fn: function (snippet) {
          return snippet;
        }
      }
    },
    // 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',
    middleware: [ historyApiFallback() ]
  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence(
    ['copy', 'styles'],
    'elements',
    ['images', 'fonts', 'html'],
    'vulcanize',
    'precache',
    cb);
    // Note: add , 'precache' , after 'vulcanize', if your are going to use Service Worker
});

// Load tasks for web-component-tester
// Adds tasks for `gulp test:local` and `gulp test:remote`
// require('web-component-tester').gulp.init(gulp);

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


<commit_before>var concat = require('gulp-concat-util');
var minifyCSS = require('gulp-minify-css');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var less = require('gulp-less');
var filter = require('gulp-filter');
var config = require('./gulp.conf');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var rimraf = require('rimraf');
var mainBowerFiles = require('main-bower-files');
var spawn = require('child_process').spawn;
var templateCache = require('gulp-angular-templatecache');

var gulp = require('gulp-help')(require('gulp'));

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

gulp.task('dev', 'Builds, runs the server and watches for changes to rebuild.', [
    // 'auto-reload',
    'watch',
    'serve'
]);

gulp.task('serve', 'Runs the server with sync between browsers.', function() {
    browserSync({
        server: {
            baseDir: "./build/"
        }
    });
});

gulp.task('watch', 'Watches for changes on the source and runs the build task.', ['build'], function() {
    return gulp
        .watch('src/**', ['build']);
});

gulp.task('build', 'Builds the application on the build directory.', ['clean'], function() {

    gulp.src(config.app.partials)
        .pipe(templateCache({
            module: 'angular-initial'
        }))
        .pipe(gulp.dest('build/js/'));

    var bower_files = mainBowerFiles();

    gulp.src(bower_files)
        .pipe(filter('*.js'))
        .pipe(concat('vendor.js'))
        .pipe(gulp.dest('build/js/'));

    gulp.src(config.app.js)
        .pipe(concat('angular-initial.js'))
        .pipe(ngAnnotate())
        // .pipe(uglify())

        .pipe(concat.header('(function(window, document, undefined) {\n\'use strict\';\n'))
        .pipe(concat.footer('\n})(window, document);\n'))
        .pipe(gulp.dest('build/js/'));

    gulp.src(config.app.index)
        .pipe(gulp.dest('build'));

    gulp.src(config.app.less)
        .pipe(less())
        .pipe(concat('angular-initial.css'))
        .pipe(gulp.dest('build/css'));

    gulp.src(config.img)
        .pipe(gulp.dest('build/'));

    return gulp.src('*', {
            read: false
        })
        .pipe(reload({
            stream: true
        }));

});
gulp.task('clean', 'Cleans the build directory.', function(cb) {
    rimraf('./build', cb);
});

gulp.task('auto-reload', 'Reloads the default task when the gulpfile is updated.', function() {
    var process;

    function restart() {
        if (process) {
            process.kill();
        }

        process = spawn('gulp', ['default'], {
            stdio: 'inherit'
        });
    }

    gulp.watch(['gulpfile.js', 'gulp.conf.json'], restart);
    // restart();
});
<commit_msg>Bug fix: gulp execution halted when cleaning the build directory<commit_after>var concat = require('gulp-concat-util');
var minifyCSS = require('gulp-minify-css');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var less = require('gulp-less');
var filter = require('gulp-filter');
var config = require('./gulp.conf');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var rimraf = require('rimraf');
var mainBowerFiles = require('main-bower-files');
var spawn = require('child_process').spawn;
var templateCache = require('gulp-angular-templatecache');

var gulp = require('gulp-help')(require('gulp'));

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

gulp.task('dev', 'Builds, runs the server and watches for changes to rebuild.', [
    // 'auto-reload',
    'watch',
    'serve'
]);

gulp.task('serve', 'Runs the server with sync between browsers.', function() {
    browserSync({
        server: {
            baseDir: "./build/"
        }
    });
});

gulp.task('watch', 'Watches for changes on the source and runs the build task.', ['build'], function() {
    return gulp
        .watch('src/**', ['build']);
});

gulp.task('build', 'Builds the application on the build directory.', ['clean'], function() {

    gulp.src(config.app.partials)
        .pipe(templateCache({
            module: 'angular-initial'
        }))
        .pipe(gulp.dest('build/js/'));

    var bower_files = mainBowerFiles();

    gulp.src(bower_files)
        .pipe(filter('*.js'))
        .pipe(concat('vendor.js'))
        .pipe(gulp.dest('build/js/'));

    gulp.src(config.app.js)
        .pipe(concat('angular-initial.js'))
        .pipe(ngAnnotate())
        // .pipe(uglify())

        .pipe(concat.header('(function(window, document, undefined) {\n\'use strict\';\n'))
        .pipe(concat.footer('\n})(window, document);\n'))
        .pipe(gulp.dest('build/js/'));

    gulp.src(config.app.index)
        .pipe(gulp.dest('build'));

    gulp.src(config.app.less)
        .pipe(less())
        .pipe(concat('angular-initial.css'))
        .pipe(gulp.dest('build/css'));

    gulp.src(config.img)
        .pipe(gulp.dest('build/'));

    return gulp.src('*', {
            read: false
        })
        .pipe(reload({
            stream: true
        }));

});
gulp.task('clean', 'Cleans the build directory.', function(cb) {
    rimraf('./build/*', cb);
});

gulp.task('auto-reload', 'Reloads the default task when the gulpfile is updated.', function() {
    var process;

    function restart() {
        if (process) {
            process.kill();
        }

        process = spawn('gulp', ['default'], {
            stdio: 'inherit'
        });
    }

    gulp.watch(['gulpfile.js', 'gulp.conf.json'], restart);
    // restart();
});
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Snackbar from '@material-ui/core/Snackbar';
import Dropzone from 'react-dropzone';
import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import Grid from '@material-ui/core/Grid';
import {convertBytesToMbsOrKbs} from './helpers/helpers'
import SnackbarContentWrapper from './SnackbarContentWrapper';
import PreviewList from './PreviewList';
import classNames from 'classnames';
const styles = {
   '@keyframes progress': {
     '0%': {
       backgroundPosition: '0 0',
     },
     '100%': {
       backgroundPosition: '-70px 0',
     },
   },
   dropZone: {
     position: 'relative',
     width: '100%',
     minHeight: '250px',
     backgroundColor: '#F0F0F0',
     border: 'dashed',
     borderColor: '#C8C8C8',
     cursor: 'pointer',
     boxSizing: 'border-box',
   },
   stripes: {
     border: 'solid',
     backgroundImage: 'repeating-linear-gradient(-45deg, #F0F0F0, #F0F0F0 25px, #C8C8C8 25px, #C8C8C8 50px)',
     animation: 'progress 2s linear infinite !important',
     backgroundSize: '150% 100%',
   },
   rejectStripes: {
     border: 'solid',
     backgroundImage: 'repeating-linear-gradient(-45deg, #fc8785, #fc8785 25px, #f4231f 25px, #f4231f 50px)',
     animation: 'progress 2s linear infinite !important',
     backgroundSize: '150% 100%',
   },
    dropzoneTextStyle:{
        textAlign: 'center'
    },
    uploadIconSize: {
        width: 51,
        height: 51,
        color: '#909090'
    },
    dropzoneParagraph:{
        fontSize: 24
    }
}

class DropzoneArea extends Component{
    constructor(props){
        super(props);
        this.state = {
            fileObjects: [],
            openSnackBar: false,
            snackbarMessage: '',
            snackbarVariant: 'success'
        }
    }
    componentWillUnmount(){
        if(this.props.clearOnUnmount){
            this.setState({
                fileObjects: []
            })
        }
    }
    onDrop(files){
        const _this = this;
        if(this.state.fileObjects.length + files.length > this.props.filesLimit){
            this.setState({
                openSnackBar: true,
                snackbarMessage: `Maximum allowed number of files exceeded. Only ${this.props.filesLimit} allowed`,
                snackbarVariant: 'error'
            });
        }else{
            var count = 0;
            var message = '';
            files.forEach((file) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    _this.setState({
                        fileObjects: _this.state.fileObjects.concat({file: file, data: event.target.result})
                    },() => {
                        if(this.props.onChange){
                            this.props.onChange(_this.state.fileObjects.map(fileObject => fileObject.file));
                        }
                        if(this.props.onDrop){
                            this.props.onDrop(file)
                        }
                        message += `File ${file.name} successfully uploaded. `;
                        count++; // we cannot rely on the index because this is asynchronous
                        if(count === files.length){
                            // display message when the last one fires
                            this.setState({
                                openSnackBar: true,
                                snackbarMessage: message,
                                snackbarVariant: 'success'
                            });
                        }
                    });
                };
                reader.readAsDataURL(file);
            })
        }
    }
    handleRemove = fileIndex => event => {
        event.stopPropagation();
        const {fileObjects} = this.state;
        const file = fileObjects.filter((fileObject, i) => { return i === fileIndex})[0].file;
        fileObjects.splice(fileIndex, 1);
        this.setState(fileObjects,() => {
            if(this.props.onDelete){
                this.props.onDelete(file);
            }
            if(this.props.onChange){
                this.props.onChange(this.state.fileObjects.map(fileObject => fileObject.file));
            }
            this.setState({
                openSnackBar: true,
                snackbarMessage: ('File ' + file.name+ ' removed'),
                snackbarVariant: 'info'
            });
        });
    }
    handleDropRejected(rejectedFiles, evt) {
        var message = '';
        rejectedFiles.forEach((rejectedFile) => {
            message = `File ${rejectedFile.name} was rejected. `;
            if(!this.props.acceptedFiles.includes(rejectedFile.type)){
                message += 'File type not supported. '
            }
            if(rejectedFile.size > this.props.fileSizeLimit){
                message += 'File is too big. Size limit is ' + convertBytesToMbsOrKbs(this.props.fileSizeLimit) + '. ';
            }
        });
        if(this.props.onDropRejected){
            this.props.onDropRejected(rejectedFiles, evt);
        }
        this.setState({
            openSnackBar: true,
            snackbarMessage: message,
            snackbarVariant: 'error'
        });
    }
    onCloseSnackbar = () => {
        this.setState({
            openSnackBar: false,
        });
    };
    render(){
        const {classes} = this.props;
        const showPreviews = this.props.showPreviews && this.state.fileObjects.length > 0;
        const showPreviewsInDropzone = this.props.showPreviewsInDropzone && this.state.fileObjects.length > 0;
        return (
            <Fragment>
                <Dropzone
                    accept={this.props.acceptedFiles.join(',')}
                    onDrop={this.onDrop.bind(this)}
                    onDropRejected={this.handleDropRejected.bind(this)}
                    className={classNames(classes.dropZone,this.props.dropZone.class)}
                    acceptClassName={classes.stripes}
                    rejectClassName={classes.rejectStripes}
                    maxSize={this.props.maxFileSize}
                     >

                            {this.props.dropzoneText}

                        <CloudUploadIcon className={classes.uploadIconSize}/>

                    {showPreviewsInDropzone &&
                        <PreviewList
                            fileObjects={this.state.fileObjects}
                            handleRemove={this.handleRemove.bind(this)}
                        />
                    }
                </Dropzone>
                {showPreviews &&
                    <Fragment>
                        <Grid container>
                            Preview:
                        </Grid>
                        <PreviewList
                            fileObjects={this.state.fileObjects}
                            handleRemove={this.handleRemove.bind(this)}
                        />
                    </Fragment>
                }
                {this.props.showAlerts &&
                    <Snackbar
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'left',
                        }}
                        open={this.state.openSnackBar}
                        autoHideDuration={6000}
                        onClose={this.onCloseSnackbar}
                        >
                        <SnackbarContentWrapper
                            onClose={this.onCloseSnackbar}
                            variant={this.state.snackbarVariant}
                            message={this.state.snackbarMessage}
                        />
                    </Snackbar>
                }
            </Fragment>
        )
    }
}

DropzoneArea.defaultProps = {
    acceptedFiles: ['image/*', 'video/*', 'application/*'],
    filesLimit: 3,
    maxFileSize: 3000000,
    dropzoneText: 'Drag and drop an image file here or click',
    showPreviews: false, // By default previews show up under in the dialog and inside in the standalone
    showPreviewsInDropzone: true,
    showAlerts: true,
    clearOnUnmount: true,
    onChange: () => {},
    onDrop: () => {},
    onDropRejected: () => {},
    onDelete: () => {}
}
DropzoneArea.propTypes = {
    acceptedFiles: PropTypes.array,
    filesLimit: PropTypes.number,
    maxFileSize: PropTypes.number,
    dropzoneText: PropTypes.string,
    showPreviews: PropTypes.bool,
    showPreviewsInDropzone: PropTypes.bool,
    showAlerts: PropTypes.bool,
    clearOnUnmount: PropTypes.bool,
    onChange: PropTypes.func,
    onDrop: PropTypes.func,
    onDropRejected: PropTypes.func,
    onDelete: PropTypes.func
}
export default withStyles(styles)(DropzoneArea)
<commit_msg>Added support for Custom CSS class<commit_after>import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Snackbar from '@material-ui/core/Snackbar';
import Dropzone from 'react-dropzone';
import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import Grid from '@material-ui/core/Grid';
import {convertBytesToMbsOrKbs} from './helpers/helpers'
import SnackbarContentWrapper from './SnackbarContentWrapper';
import PreviewList from './PreviewList';
import classNames from 'classnames';
const styles = {
   '@keyframes progress': {
     '0%': {
       backgroundPosition: '0 0',
     },
     '100%': {
       backgroundPosition: '-70px 0',
     },
   },
   dropZone: {
     position: 'relative',
     width: '100%',
     minHeight: '250px',
     backgroundColor: '#F0F0F0',
     border: 'dashed',
     borderColor: '#C8C8C8',
     cursor: 'pointer',
     boxSizing: 'border-box',
   },
   stripes: {
     border: 'solid',
     backgroundImage: 'repeating-linear-gradient(-45deg, #F0F0F0, #F0F0F0 25px, #C8C8C8 25px, #C8C8C8 50px)',
     animation: 'progress 2s linear infinite !important',
     backgroundSize: '150% 100%',
   },
   rejectStripes: {
     border: 'solid',
     backgroundImage: 'repeating-linear-gradient(-45deg, #fc8785, #fc8785 25px, #f4231f 25px, #f4231f 50px)',
     animation: 'progress 2s linear infinite !important',
     backgroundSize: '150% 100%',
   },
    dropzoneTextStyle:{
        textAlign: 'center'
    },
    uploadIconSize: {
        width: 51,
        height: 51,
        color: '#909090'
    },
    dropzoneParagraph:{
        fontSize: 24
    }
}

class DropzoneArea extends Component{
    constructor(props){
        super(props);
        this.state = {
            fileObjects: [],
            openSnackBar: false,
            snackbarMessage: '',
            snackbarVariant: 'success'
        }
    }
    componentWillUnmount(){
        if(this.props.clearOnUnmount){
            this.setState({
                fileObjects: []
            })
        }
    }
    onDrop(files){
        const _this = this;
        if(this.state.fileObjects.length + files.length > this.props.filesLimit){
            this.setState({
                openSnackBar: true,
                snackbarMessage: `Maximum allowed number of files exceeded. Only ${this.props.filesLimit} allowed`,
                snackbarVariant: 'error'
            });
        }else{
            var count = 0;
            var message = '';
            files.forEach((file) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    _this.setState({
                        fileObjects: _this.state.fileObjects.concat({file: file, data: event.target.result})
                    },() => {
                        if(this.props.onChange){
                            this.props.onChange(_this.state.fileObjects.map(fileObject => fileObject.file));
                        }
                        if(this.props.onDrop){
                            this.props.onDrop(file)
                        }
                        message += `File ${file.name} successfully uploaded. `;
                        count++; // we cannot rely on the index because this is asynchronous
                        if(count === files.length){
                            // display message when the last one fires
                            this.setState({
                                openSnackBar: true,
                                snackbarMessage: message,
                                snackbarVariant: 'success'
                            });
                        }
                    });
                };
                reader.readAsDataURL(file);
            })
        }
    }
    handleRemove = fileIndex => event => {
        event.stopPropagation();
        const {fileObjects} = this.state;
        const file = fileObjects.filter((fileObject, i) => { return i === fileIndex})[0].file;
        fileObjects.splice(fileIndex, 1);
        this.setState(fileObjects,() => {
            if(this.props.onDelete){
                this.props.onDelete(file);
            }
            if(this.props.onChange){
                this.props.onChange(this.state.fileObjects.map(fileObject => fileObject.file));
            }
            this.setState({
                openSnackBar: true,
                snackbarMessage: ('File ' + file.name+ ' removed'),
                snackbarVariant: 'info'
            });
        });
    }
    handleDropRejected(rejectedFiles, evt) {
        var message = '';
        rejectedFiles.forEach((rejectedFile) => {
            message = `File ${rejectedFile.name} was rejected. `;
            if(!this.props.acceptedFiles.includes(rejectedFile.type)){
                message += 'File type not supported. '
            }
            if(rejectedFile.size > this.props.fileSizeLimit){
                message += 'File is too big. Size limit is ' + convertBytesToMbsOrKbs(this.props.fileSizeLimit) + '. ';
            }
        });
        if(this.props.onDropRejected){
            this.props.onDropRejected(rejectedFiles, evt);
        }
        this.setState({
            openSnackBar: true,
            snackbarMessage: message,
            snackbarVariant: 'error'
        });
    }
    onCloseSnackbar = () => {
        this.setState({
            openSnackBar: false,
        });
    };
    render(){
        const {classes} = this.props;
        const showPreviews = this.props.showPreviews && this.state.fileObjects.length > 0;
        const showPreviewsInDropzone = this.props.showPreviewsInDropzone && this.state.fileObjects.length > 0;
        return (
            <Fragment>
                <Dropzone
                    accept={this.props.acceptedFiles.join(',')}
                    onDrop={this.onDrop.bind(this)}
                    onDropRejected={this.handleDropRejected.bind(this)}
                    className={classNames(classes.dropZone,this.props.dropZoneClass)}
                    acceptClassName={classes.stripes}
                    rejectClassName={classes.rejectStripes}
                    maxSize={this.props.maxFileSize}
                     >

                            {this.props.dropzoneText}

                        <CloudUploadIcon className={classes.uploadIconSize}/>

                    {showPreviewsInDropzone &&
                        <PreviewList
                            fileObjects={this.state.fileObjects}
                            handleRemove={this.handleRemove.bind(this)}
                        />
                    }
                </Dropzone>
                {showPreviews &&
                    <Fragment>
                        <Grid container>
                            Preview:
                        </Grid>
                        <PreviewList
                            fileObjects={this.state.fileObjects}
                            handleRemove={this.handleRemove.bind(this)}
                        />
                    </Fragment>
                }
                {this.props.showAlerts &&
                    <Snackbar
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'left',
                        }}
                        open={this.state.openSnackBar}
                        autoHideDuration={6000}
                        onClose={this.onCloseSnackbar}
                        >
                        <SnackbarContentWrapper
                            onClose={this.onCloseSnackbar}
                            variant={this.state.snackbarVariant}
                            message={this.state.snackbarMessage}
                        />
                    </Snackbar>
                }
            </Fragment>
        )
    }
}

DropzoneArea.defaultProps = {
    acceptedFiles: ['image/*', 'video/*', 'application/*'],
    filesLimit: 3,
    maxFileSize: 3000000,
    dropzoneText: 'Drag and drop an image file here or click',
    showPreviews: false, // By default previews show up under in the dialog and inside in the standalone
    showPreviewsInDropzone: true,
    showAlerts: true,
    clearOnUnmount: true,
    onChange: () => {},
    onDrop: () => {},
    onDropRejected: () => {},
    onDelete: () => {}
}
DropzoneArea.propTypes = {
    acceptedFiles: PropTypes.array,
    filesLimit: PropTypes.number,
    maxFileSize: PropTypes.number,
    dropzoneText: PropTypes.string,
    showPreviews: PropTypes.bool,
    showPreviewsInDropzone: PropTypes.bool,
    showAlerts: PropTypes.bool,
    clearOnUnmount: PropTypes.bool,
    onChange: PropTypes.func,
    onDrop: PropTypes.func,
    onDropRejected: PropTypes.func,
    onDelete: PropTypes.func
}
export default withStyles(styles)(DropzoneArea)
<|endoftext|>


<commit_before>import React from "react";
import axios from "axios";
import {Line} from "react-chartjs-2";
import Spinner from './Spinner';

class DynamicChart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      error: null,
      chartData: {
        datasets: [ ]
      },
    }
  }

  componentDidMount() {
    this.fetchJson();
  }

  render() {
    const options = {
      spanGaps: false,
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            displayFormats: {
              quarter: 'HH:mm'
            }
          }
        }]
      }
    };

    let element = null;
    if (this.state.loading === true)
      element = <Spinner/>;
    else if (this.state.error)
      element =
{ this.state.error.toString() }

    else
      element = <Line data={ this.state.chartData } options={options}/>

    return

      { element }

  }

  fetchJson() {
    const colors = ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'];

    axios.get('http://localhost:11900/temperature.json')
        .then(response => {
          this.setState({
            loading: false,
            error: null,
            chartData: {
              datasets: response.data.map((dataset, index) =>
                  Object.assign({}, dataset, {
                    fill: false,
                    radius: 0,
                    spanGaps: false,
                    borderColor: colors[index]
                  })
              )
            }
          });
        })
        .catch(error => {
          this.setState({
            loading: false,
            error: error
          })
        });
  }

}

export default DynamicChart;
<commit_msg>adding y label and background color for the legend<commit_after>import React from "react";
import axios from "axios";
import {Line} from "react-chartjs-2";
import Spinner from './Spinner';

class DynamicChart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      error: null,
      chartData: {
        datasets: [ ]
      },
    }
  }

  componentDidMount() {
    this.fetchJson();
  }

  render() {
    const options = {
      spanGaps: false,
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'Temperature (°C)'
          }
        }],
        xAxes: [{
          type: 'time',
          time: {
            displayFormats: {
              quarter: 'HH:mm'
            }
          }
        }]
      }
    };

    let element = null;
    if (this.state.loading === true)
      element = <Spinner/>;
    else if (this.state.error)
      element =
{ this.state.error.toString() }

    else
      element = <Line data={ this.state.chartData } options={options}/>

    return

      { element }

  }

  fetchJson() {
    const colors = ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'];

    axios.get('http://localhost:11900/temperature.json')
        .then(response => {
          this.setState({
            loading: false,
            error: null,
            chartData: {
              datasets: response.data.map((dataset, index) =>
                  Object.assign({}, dataset, {
                    fill: false,
                    radius: 0,
                    spanGaps: false,
                    borderColor: colors[index],
                    backgroundColor: colors[index]
                  })
              )
            }
          });
        })
        .catch(error => {
          this.setState({
            loading: false,
            error: error
          })
        });
  }

}

export default DynamicChart;
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');

var gulp = require('gulp');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var replace = require('gulp-just-replace');
var license = require('gulp-header');

//替换文本数组
// var replaceArr = [{
//   search: /\"preScroll\"/g,
//   replacement: '1'
// }, {
//   search: /\"preZoom\"/g,
//   replacement: '2'
// }, {
//   search: /\"scrollX\"/g,
//   replacement: '3'
// }, {
//   search: /\"scrollY\"/g,
//   replacement: '4'
// }, {
//   search: /\"scrollFree\"/g,
//   replacement: '5'
// }];

//压缩/备份JRoll主文件
gulp.task('default', function() {

  //获取头部注释
  fs.readFile('src/jroll.js', function(err, data) {
    if (err) throw err;
    var head = /\/\*.+v(\d+\.\d+\.\d+).+\*\//.exec(data.toString());
    var copyright = "/*! JRoll v2.0.0 ~ (c) 2015-2016 Author:jlong, Email:jlong@chjtx.com Website:http://www.chjtx.com/JRoll/ */\n;";
    var version = "2.0.0";
    if (head) {
      copyright = head[0] + '\n;';  //头部注释
      version = head[1];    //版本号
    }

    gulp.src('src/jroll.js')

      //备份原文件
      .pipe(rename({
        basename: 'jroll',
        extname: '.'+version+'.js'
      }))
      .pipe(gulp.dest('build/'))

      //替换（手动压缩）
      // .pipe(replace(replaceArr))

      //压缩
      .pipe(uglify())

      //加入头部注释
      .pipe(license(copyright))

      //修改后缀
      .pipe(rename({
        basename: 'jroll',
        extname: '.min.js'
      }))

      //输出
      .pipe(gulp.dest('build/'))

      //备份
      .pipe(rename({
        basename: 'jroll',
        extname: '.'+version+'.min.js'
      }))
      .pipe(gulp.dest('build/'));

  });

});

//压缩jroll-pulldown.js
gulp.task('pulldown', function() {
  //获取头部注释
  fs.readFile('plugins/jroll-pulldown/jroll-pulldown.js', function(err, data) {
    if (err) throw err;
    var head = /\/\*.+v(\d+\.\d+\.\d+).+\*\//.exec(data.toString());
    var copyright = "/*! JRoll-PullDown v1.0.0 ~ (c) 2015-2016 Author:BarZu Git:https://git.oschina.net/chenjianlong/JRoll2/ */\n;";
    var version = "1.0.0";
    if (head) {
      copyright = head[0] + '\n;';  //头部注释
      version = head[1];    //版本号
    }

    gulp.src('plugins/jroll-pulldown/jroll-pulldown.js')

      //备份原文件
      .pipe(rename({
        basename: 'jroll-pulldown',
        extname: '.'+version+'.js'
      }))
      .pipe(gulp.dest('plugins/jroll-pulldown/build/'))

      //压缩
      .pipe(uglify())

      //加入头部注释
      .pipe(license(copyright))

      //备份
      .pipe(rename({
        basename: 'jroll-pulldown',
        extname: '.'+version+'.min.js'
      }))
      .pipe(gulp.dest('plugins/jroll-pulldown/build/'));

  });
});

//压缩jroll-infinite.js
gulp.task('infinite', function() {
  //获取头部注释
  fs.readFile('plugins/jroll-infinite/jroll-infinite.js', function(err, data) {
    if (err) throw err;
    var head = /\/\*.+v(\d+\.\d+\.\d+).+\*\//.exec(data.toString());
    var copyright = "/*! JRoll-Infinite v1.0.0 ~ (c) 2015-2016 Author:BarZu Git:https://git.oschina.net/chenjianlong/JRoll2/ */\n;";
    var version = "1.0.0";
    if (head) {
      copyright = head[0] + '\n;';  //头部注释
      version = head[1];    //版本号
    }

    gulp.src('plugins/jroll-infinite/jroll-infinite.js')

      //备份原文件
      .pipe(rename({
        basename: 'jroll-infinite',
        extname: '.'+version+'.js'
      }))
      .pipe(gulp.dest('plugins/jroll-infinite/build/'))

      //压缩
      .pipe(uglify())

      //加入头部注释
      .pipe(license(copyright))

      //备份
      .pipe(rename({
        basename: 'jroll-infinite',
        extname: '.'+version+'.min.js'
      }))
      .pipe(gulp.dest('plugins/jroll-infinite/build/'));

  });
});

//压缩jroll-fixedinput.js
gulp.task('fixedinput', function() {
  //获取头部注释
  fs.readFile('plugins/jroll-fixedinput/jroll-fixedinput.js', function(err, data) {
    if (err) throw err;
    var head = /\/\*.+v(\d+\.\d+\.\d+).+\*\//.exec(data.toString());
    var copyright = "/*! JRoll-FixedInput v1.0.0 ~ (c) 2015-2016 Author:BarZu Git:https://git.oschina.net/chenjianlong/JRoll2/ */\n;";
    var version = "1.0.0";
    if (head) {
      copyright = head[0] + '\n;';  //头部注释
      version = head[1];    //版本号
    }

    gulp.src('plugins/jroll-fixedinput/jroll-fixedinput.js')

      //备份原文件
      .pipe(rename({
        basename: 'jroll-fixedinput',
        extname: '.'+version+'.js'
      }))
      .pipe(gulp.dest('plugins/jroll-fixedinput/build/'))

      //压缩
      .pipe(uglify())

      //加入头部注释
      .pipe(license(copyright))

      //备份
      .pipe(rename({
        basename: 'jroll-fixedinput',
        extname: '.'+version+'.min.js'
      }))
      .pipe(gulp.dest('plugins/jroll-fixedinput/build/'));

  });
});<commit_msg>构建代码整理<commit_after>'use strict'

var fs = require('fs')

var gulp = require('gulp')
var rename = require('gulp-rename')
var uglify = require('gulp-uglify')
var replace = require('gulp-just-replace')
var license = require('gulp-header')

// 压缩/备份JRoll主文件
gulp.task('default', function () {
  // 获取头部注释
  fs.readFile('src/jroll.js', function (err, data) {
    if (err) throw err
    var head = /\/\*.+v(\d+\.\d+\.\d+).+\*\//.exec(data.toString())
    var copyright = '/*! JRoll v2.0.0 ~ (c) 2015-2016 Author:jlong, Email:jlong@chjtx.com Website:http://www.chjtx.com/JRoll/ */\n;'
    var version = '2.0.0'
    if (head) {
      copyright = head[0] + '\n;'  // 头部注释
      version = head[1]    // 版本号
    }

    gulp.src('src/jroll.js')

      // 备份原文件
      .pipe(rename({
        basename: 'jroll',
        extname: '.' + version + '.js'
      }))
      .pipe(gulp.dest('build/'))

      // 压缩
      .pipe(uglify())

      // 加入头部注释
      .pipe(license(copyright))

      // 修改后缀
      .pipe(rename({
        basename: 'jroll',
        extname: '.min.js'
      }))

      // 输出
      .pipe(gulp.dest('build/'))

      // 备份
      .pipe(rename({
        basename: 'jroll',
        extname: '.' + version + '.min.js'
      }))
      .pipe(gulp.dest('build/'))
  })
})

// 压缩、备份扩展组件等
function build (options) {
  gulp.src(options.src)

    // 备份原文件
    .pipe(rename({
      basename: options.basename,
      extname: '.' + options.version + '.js'
    }))
    .pipe(license(options.copyright))
    .pipe(replace([{
      search: /\{\{version\}\}/g,
      replacement: options.version
    }]))
    .pipe(gulp.dest(options.dest))

    // 压缩
    .pipe(uglify())

    // 加入头部注释
    .pipe(license(options.copyright))
    .pipe(rename({
      basename: options.basename,
      extname: '.' + options.version + '.min.js'
    }))
    .pipe(gulp.dest(options.dest))
}

// JRollViewer 压缩、备份
gulp.task('viewer', function () {
  let version = JSON.parse(fs.readFileSync('./package.json'))['version-viewer']
  let copyright = `/*! JRollViewer v${version} ~ (c) 2016 Author:BarZu Git:https://github.com/chjtx/JRoll/tree/master/plugins/jroll-viewer */\n`

  build({
    version: version,
    copyright: copyright,
    src: 'plugins/jroll-viewer/jroll-viewer.js',
    dest: 'plugins/jroll-viewer/build/',
    basename: 'jroll-viewer'
  })
})

// jroll-fixedinput 压缩、备份
gulp.task('fixedinput', function () {
  let version = JSON.parse(fs.readFileSync('./package.json'))['version-fixedinput']
  let copyright = `/*! JRoll-FixedInput v${version} ~ (c) 2016 Author:BarZu Git:https://github.com/chjtx/JRoll/tree/master/extends/jroll-fixedinput */\n`

  build({
    version: version,
    copyright: copyright,
    src: 'extends/jroll-fixedinput/jroll-fixedinput.js',
    dest: 'extends/jroll-fixedinput/build/',
    basename: 'jroll-fixedinput'
  })
})

// jroll-infinite 压缩、备份
gulp.task('infinite', function () {
  let version = JSON.parse(fs.readFileSync('./package.json'))['version-infinite']
  let copyright = `/*! JRoll-Infinite v${version} ~ (c) 2016 Author:BarZu Git:https://github.com/chjtx/JRoll/tree/master/extends/jroll-infinite */\n`

  build({
    version: version,
    copyright: copyright,
    src: 'extends/jroll-infinite/jroll-infinite.js',
    dest: 'extends/jroll-infinite/build/',
    basename: 'jroll-infinite'
  })
})

// jroll-pulldown 压缩、备份
gulp.task('pulldown', function () {
  let version = JSON.parse(fs.readFileSync('./package.json'))['version-pulldown']
  let copyright = `/*! JRoll-Pulldown v${version} ~ (c) 2016 Author:BarZu Git:https://github.com/chjtx/JRoll/tree/master/extends/jroll-pulldown */\n`

  build({
    version: version,
    copyright: copyright,
    src: 'extends/jroll-pulldown/jroll-pulldown.js',
    dest: 'extends/jroll-pulldown/build/',
    basename: 'jroll-pulldown'
  })
})
<|endoftext|>


<commit_before>const
    path = require('path'),
    fs = require('fs'),
    expect = require("chai").expect,
    execFile = require('child_process').execFile,
    exec = require('child_process').exec,
    Templatefy = require("../lib/templatefy"),
    cmd = path.resolve('./bin/templatefy'),
    pkg = JSON.parse(fs.readFileSync('./package.json'), 'utf8'),
    templatefy = function() {
        var args = Array.prototype.slice.call(arguments),
            cb = args.splice(-1)[0];

        return args[0] && args[0].join
              ? exec([args[0].concat([cmd]).join('|')].concat(args.slice(1)).join(' '), cb)
              : exec([cmd].concat(args).join(' '), cb);
    };

describe('Templatefy', function() {

    describe('#command-line', function() {

        it('should print help to stdout', function(done) {
            templatefy('--help', function(error, stdout, stderr) {
                expect(stdout).to.have.string('Usage:');
                expect(stdout).to.have.string('-i, --input');
                expect(stdout).to.have.string('-o, --output');
                expect(stdout).to.have.string('-m, --minify');
                expect(stdout).to.have.string('-a, --angular');
                expect(stdout).to.have.string('-am, --angular-module');
                expect(stdout).to.have.string('-ll, --log-level');
                expect(stdout).to.have.string('-lf, --log-file');
                expect(stdout).to.have.string('-v, --version ');
                done();
            });
        });

        it('should print version to stdout', function(done) {
            templatefy('--version', function(error, stdout, stderr) {
                expect(stdout).to.have.string(pkg.version);
                done();
            });
        });

        it('should show error unexpected paramenter message', function(done) {
            templatefy('--wrong-param', function(error, stdout, stderr) {
                expect(stdout).to.have.string('\'--wrong-param\' expects a value');
                done();
            });
        });

        // it('should require --input argument if not pipe stdin defined', function(done) {
        //    templatefy(function(error, stdout, stderr) {
        //        done();
        //    });
        // });

        it('should print the string template by input parameter to parsed through stdout', function(done) {
            templatefy('--input=\'
Test
\'', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the path of template by input parameter to parsed through stdout', function(done) {
            templatefy('--input=\'./test/fixtures/template-element.html\'', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the string template by stdin pipe to parsed through stdout', function(done) {
            templatefy(['echo \'
Test
\''], function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the string template by stdin file redirection to parsed through stdout', function(done) {
            templatefy('< ./test/fixtures/template-element.html', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });
    });

    describe('#api', function() {

        // it('should instantiate templatefy object', function(done) {
        //       Templatefy.parse();
        // });
        //
        // it('should instantiate templatefy object', function(done) {
        //
        // });
    });
});

 // echo '<hola    asdasdasd="asdasd"></hola>' | node bin/templatefy --angular=true --angular-module='jaja' --log-level=debug

 // node bin/templatefy --input='<hola    asdasdasd="asdasd"></hola>' --angular=true --angular-module='jaja' --log-level=debug
<commit_msg>fix: unit test<commit_after>const
    path = require('path'),
    fs = require('fs'),
    expect = require("chai").expect,
    execFile = require('child_process').execFile,
    exec = require('child_process').exec,
    Templatefy = require("../lib/templatefy"),
    cmd = path.resolve('./bin/templatefy'),
    pkg = JSON.parse(fs.readFileSync('./package.json'), 'utf8'),
    templatefy = function() {
        var args = Array.prototype.slice.call(arguments),
            cb = args.splice(-1)[0];

        return args[0] && args[0].join
              ? exec([args[0].concat([cmd]).join('|')].concat(args.slice(1)).join(' '), cb)
              : exec([cmd].concat(args).join(' '), cb);
    };

describe('Templatefy', function() {

    describe('#command-line', function() {

        it('should print help to stdout', function(done) {
            templatefy('--help', function(error, stdout, stderr) {
                expect(stdout).to.have.string('Usage:');
                expect(stdout).to.have.string('-i, --input');
                expect(stdout).to.have.string('-o, --output');
                expect(stdout).to.have.string('-m, --minify');
                expect(stdout).to.have.string('-ll, --log-level');
                expect(stdout).to.have.string('-lf, --log-file');
                expect(stdout).to.have.string('-v, --version ');
                done();
            });
        });

        it('should print version to stdout', function(done) {
            templatefy('--version', function(error, stdout, stderr) {
                expect(stdout).to.have.string(pkg.version);
                done();
            });
        });

        it('should show error unexpected paramenter message', function(done) {
            templatefy('--wrong-param', function(error, stdout, stderr) {
                expect(stdout).to.have.string('\'--wrong-param\' expects a value');
                done();
            });
        });

        // it('should require --input argument if not pipe stdin defined', function(done) {
        //    templatefy(function(error, stdout, stderr) {
        //        done();
        //    });
        // });

        it('should print the string template by input parameter to parsed through stdout', function(done) {
            templatefy('--input=\'
Test
\'', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the path of template by input parameter to parsed through stdout', function(done) {
            templatefy('--input=\'./test/fixtures/template-element.html\'', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the string template by stdin pipe to parsed through stdout', function(done) {
            templatefy(['echo \'
Test
\''], function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });

        it('should print the string template by stdin file redirection to parsed through stdout', function(done) {
            templatefy('< ./test/fixtures/template-element.html', function(error, stdout, stderr) {
                expect(stdout).to.have.string('
Test
');
                done();
            });
        });
    });

    describe('#api', function() {

        // it('should instantiate templatefy object', function(done) {
        //       Templatefy.parse();
        // });
        //
        // it('should instantiate templatefy object', function(done) {
        //
        // });
    });
});

 // echo '<hola    asdasdasd="asdasd"></hola>' | node bin/templatefy --angular=true --angular-module='jaja' --log-level=debug

 // node bin/templatefy --input='<hola    asdasdasd="asdasd"></hola>' --angular=true --angular-module='jaja' --log-level=debug
<|endoftext|>


<commit_before>'use strict';

var _              = require('lodash');
var events         = require('events');
var Bro            = require('../../lib/bro');
var BundleFile     = require('../../lib/bundle-file');
var RestorableFile = require('../restorable-file');
var LoggerFactory  = require('./logger-factory');
var chai           = require('chai');
var path           = require('path');
var fs             = require('fs');
var unpack         = require('browser-unpack');
var escape         = require('js-string-escape');

var BUNDLE_UPDATE_CHECK_DELAY = 3000;

function delay(fn, time) {
  setTimeout(fn, time || 205);
}

function createFilePattern(file) {
  return {
    pattern: file,
    served: true,
    included: true,
    watched: true
  };
}

function createFile(p) {
  return {
    path: path.resolve(p),
    realContents: function() {
      return fs.readFileSync(this.path, 'utf-8');
    }
  };
}

function createConfig(config) {
  config = config || {};

  return _.extend({}, {
    basePath: '',
    files: [ createFilePattern('*.js') ],
    preprocessors: {
      '*.js': [ 'browserify' ]
    }
  }, config);
}

/**
 * Preprocess bundle and test files, collect async results
 * and call the callback with all files in the order they have been processed.
 */
function preprocess(bundle, testFiles, done) {

  /*jshint validthis:true */
  var plugin = this;

  var total = 1 + testFiles.length;

  var processed = [];

  function fileProcessed(file, result) {
    file.bundled = result;

    processed.push(file);

    if (processed.length == total) {
      done();
    }
  }

  function process(preprocessor, file) {
    preprocessor(file.bundled || '', file, function(result) {
      fileProcessed(file, result);
    });
  }

  process(plugin.bundlePreprocessor, bundle);

  // Karma does not necessarily preprocess test files in the order they are given.
  var shuffledTestFiles = testFiles.slice(0).reverse();

  _.forEach(shuffledTestFiles, function(file) {
    process(plugin.testFilePreprocessor, file);
  });
}

function expectedBundleFile(filename) {
  return escape(path.resolve(filename));
}

function expectedBundle(filename) {
  return 'require("' + expectedBundleFile(filename) + '");';
}

function expectBundleContainments(bundleFile, testFiles) {
  var extractedFiles = unpack(bundleFile.bundled).map(function(row) { return row.id; });

  _.forEach(testFiles, function(f) {
    expect(extractedFiles).to.contain(f.path);
  });
}

describe('karma-browserify', function() {

  var emitter, loggerFactory, bundle, bro;

  beforeEach(function() {

    emitter = new events.EventEmitter();
    loggerFactory = new LoggerFactory();

    bundle = new BundleFile();

    bundle.update = chai.spy(bundle.update);
    bundle.touch = chai.spy(bundle.touch);
    bundle.remove = chai.spy(bundle.remove);

    bro = new Bro(bundle);
  });

  afterEach(function(done) {
    emitter.emit('exit', done);
  });

  // increase timeout
  this.timeout(8000);

  function createPlugin(config) {

    config = createConfig(config);

    function TestPlugin(bro) {

      this.framework = bro.framework(emitter, config, loggerFactory);
      this.testFilePreprocessor = bro.testFilePreprocessor(config);
      this.bundlePreprocessor = bro.bundlePreprocessor(config);

      this.preprocess = preprocess.bind(this);
    }

    return new TestPlugin(bro);
  }

  describe('framework', function() {

    describe('init', function() {

      it('should prepend and init bundle file', function() {

        // given
        var config = createConfig();

        // when
        createPlugin(config);

        // then
        expect(bundle.touch).to.have.been.called();

        expect(config.files[0].pattern).to.eql(bundle.location);
      });

      it('should insert bundle file right before first preprocessed file', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*Spec.js' }
          ],
          preprocessors: {
            'foo/*Spec.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // expect bundle file to be inserted at pos=1
        expect(config.files).to.deep.eql([
          { pattern : 'vendor/external.js' },
          { pattern : bundle.location, served : true, included : true, watched : true },
          { pattern : 'foo/*Spec.js' }
        ]);

      });

      it('should insert bundle file before more-specific preprocessed pattern', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*Spec.js' }
          ],
          preprocessors: {
            'foo/*.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // expect bundle file to be inserted at pos=1
        // since foo/*Spec.js matches the foo/*.js glob
        expect(config.files).to.deep.eql([
          { pattern : 'vendor/external.js' },
          { pattern : bundle.location, served : true, included : true, watched : true },
          { pattern : 'foo/*Spec.js' }
        ]);

      });

      it('should not insert bundle file before less-specific preprocessed pattern', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*.js' }
          ],
          preprocessors: {
            'foo/*Spec.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // then
        expect(config.files[0].pattern).to.eql(bundle.location);

      });

    });

    describe('cleanup', function() {

      it('should remove bundle file on exit', function() {

        // given
        createPlugin();

        // when
        emitter.emit('exit', function() { });

        // then
        expect(bundle.remove).to.have.been.called();
      });

    });

  });

  describe('preprocessing', function() {

    it('should create bundle', function(done) {

      // given
      var plugin = createPlugin();

      var bundleFile = createFile(bundle.location);
      var testFileB = createFile('test/fixtures/b.js');
      var testFileC = createFile('test/fixtures/c.js');

      // when
      plugin.preprocess(bundleFile, [ testFileB, testFileC ], function() {

        // then
        // bundle got created
        expectBundleContainments(bundleFile, [ testFileB, testFileC ]);

        // test file stub got created
        expect(testFileB.bundled).to.eql(expectedBundle('test/fixtures/b.js'));
        expect(testFileC.bundled).to.eql(expectedBundle('test/fixtures/c.js'));

        done();
      });

    });

    it('should pass through on updates', function(done) {

      // given
      var plugin = createPlugin();

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/b.js');

      // initial bundle creation
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // when
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // then

          // bundle got passed through
          expectBundleContainments(bundleFile, [ testFile ]);

          // test file got regenerated
          expect(testFile.bundled).to.eql(expectedBundle('test/fixtures/b.js'));

          done();
        });

      });

    });

    describe('automatic rebuild (autoWatch=true)', function() {

      // remember test files and restore them later
      // because they are going to be updated
      var aFile = new RestorableFile(__dirname + '/../fixtures/a.js');
      var bFile = new RestorableFile(__dirname + '/../fixtures/b.js');

      beforeEach(function() {
        aFile.load();
        bFile.load();
      });

      afterEach(function() {
        aFile.restore();
        bFile.restore();
      });

      it('should update on change', function(done) {

        // given
        var plugin = createPlugin({ autoWatch: true });

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/b.js');

        // initial bundle creation
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // reset spy on bundle
          bundle.update.__spy.calls = [];
          bundle.update.__spy.called = false;

          // when
          // update bundle file
          delay(function() {
            aFile.update('module.exports = "UPDATED";');
          });

          // give watch a chance to trigger
          delay(function() {

            // then
            expect(bundle.update).to.have.been.called();

            done();
          }, BUNDLE_UPDATE_CHECK_DELAY);

        });

      });

      it('should handle bundle error', function(done) {

        // given
        var plugin = createPlugin();

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/error.js');

        // when
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // then
          // bundle reports error
          expect(bundleFile.bundled).to.exist;
          expect(bundleFile.bundled.message).to.eql('Unexpected token');

          // test file stub got created anyway
          expect(testFile.bundled).to.eql(expectedBundle('test/fixtures/error.js'));

          done();
        });
      });

      it('should handle bundle update error', function(done) {

        // given
        var plugin = createPlugin({ autoWatch: true });

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/b.js');

        // initial bundle creation
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // reset spy on bundle
          bundle.update.__spy.calls = [];
          bundle.update.__spy.called = false;

          // when
          // update bundle file
          delay(function() {
            aFile.update('unpoarsable / {{ code');
          });

          // give watch a chance to trigger
          delay(function() {

            // then
            // no update on parse error
            expect(bundle.update).not.to.have.been.called();

            done();
          }, BUNDLE_UPDATE_CHECK_DELAY);

        });

      });

      // TODO(nikku): Yup, aint gonna work on travis CI :-(
      if (!process.env.TRAVIS) {

        it('should handle file remove', function(done) {

          // given
          var plugin = createPlugin({ autoWatch: true });

          var bundleFile = createFile(bundle.location);
          var testFile = createFile('test/fixtures/b.js');

          // initial bundle creation
          plugin.preprocess(bundleFile, [ testFile ], function() {

            // reset spy on bundle
            bundle.update.__spy.calls = [];
            bundle.update.__spy.called = false;

            // when
            // remove file
            delay(function() {
              bFile.remove();
            });

            // update a bundled file
            delay(function() {
              aFile.update('module.exports = "UPDATED";');
            }, 500);

            // give watch a chance to trigger
            delay(function() {

              // then
              // update with file deleted
              expect(bundle.update).to.have.been.called();

              expect(bundleFile.realContents()).not.to.contain('/b.js');
              done();
            }, BUNDLE_UPDATE_CHECK_DELAY);

          });

        });

      }

    });

  });

  describe('browserify', function() {

    it('should configure transform', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          transform: [ 'brfs' ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle got created
        expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");

        done();
      });
    });

    it('should configure transform with options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          transform: [ ['brfs', { foo: 'bar' }] ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle got created
        expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");

        done();
      });
    });

    it('should support configure hook in the options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          configure: function(bundle) {
            bundle.external('foobar');
          }
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/configure.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then
        // bundle got created
        expect(bundleFile.bundled).to.exist;
        expect(bundleFile.bundled).to.contain('require(\'foobar\')');

        done();
      });
    });

    it('should configure debug with source map support', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          debug: true
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/a.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // contains source map
        expect(bundleFile.bundled).to.contain('//# sourceMappingURL');

        // and has the parsed mapping attached
        expect(bundleFile.sourceMap).to.exist;

        done();
      });
    });

    it('should configure plugin with options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          plugin: [ ['tsify', { removeComments: true } ] ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/plugin.ts');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle file got processed via plug-in
        expect(bundleFile.bundled).to.contain('module.exports = plugin');
        expect(bundleFile.bundled).not.to.contain('// typescript');

        done();
      });
    });

    it('should persist transforms', function(done) {
      // given
      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      var plugin = createPlugin({
        browserify: {
          transform: [ 'brfs' ],
          // Hook into bundler/pipeline events for success/error
          configure: function(bundle) {

            // after first bundle
            bundle.once('bundled', function (err) {

              // fail if there was an error
              if (err) return done(err);

              // set up error/success handlers
              bundle.on('bundle', function (pipeline) {
                pipeline
                  .on('error', done)
                  .on('end', function() {
                    expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");
                    done();
                  });
              });

              // rebundle
              plugin.preprocess(bundleFile, [ testFile ], function() {});
            });
          }
        }
      });

      // initial bundle
      plugin.preprocess(bundleFile, [ testFile ], function() {});
    });

    it('should persist plugins', function(done) {
      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/plugin.ts');
      var plugin = createPlugin({
        browserify: {
          plugin: [ ['tsify', { removeComments: true } ] ],
          // Hook into bundler/pipeline events for success/error
          configure: function(bundle) {
            // After first bundle
            bundle.once('bundled', function (err) {
              // Fail if there was an error
              if (err) return done(err);
              // Set up error/success handlers
              bundle.on('bundle', function (pipeline) {
                pipeline
                  .on('error', done)
                  .on('end', done);
              });
              // Rebundle
              plugin.preprocess(bundleFile, [ testFile ], function() {});
            });
          }
        }
      });
      // Initial bundle
      plugin.preprocess(bundleFile, [ testFile ], function() {});
    });

  });

});
<commit_msg>test(bro): refactor test cases<commit_after>'use strict';

var _              = require('lodash');
var events         = require('events');
var Bro            = require('../../lib/bro');
var BundleFile     = require('../../lib/bundle-file');
var RestorableFile = require('../restorable-file');
var LoggerFactory  = require('./logger-factory');
var chai           = require('chai');
var path           = require('path');
var fs             = require('fs');
var unpack         = require('browser-unpack');
var escape         = require('js-string-escape');

var BUNDLE_UPDATE_CHECK_DELAY = 3000;

function delay(fn, time) {
  setTimeout(fn, time || 205);
}

function createFilePattern(file) {
  return {
    pattern: file,
    served: true,
    included: true,
    watched: true
  };
}

function createFile(p) {
  return {
    path: path.resolve(p),
    realContents: function() {
      return fs.readFileSync(this.path, 'utf-8');
    }
  };
}

function createConfig(config) {
  config = config || {};

  return _.extend({}, {
    basePath: '',
    files: [ createFilePattern('*.js') ],
    preprocessors: {
      '*.js': [ 'browserify' ]
    }
  }, config);
}

function expectedBundleFile(filename) {
  return escape(path.resolve(filename));
}

function expectedBundle(filename) {
  return 'require("' + expectedBundleFile(filename) + '");';
}

function expectBundleContainments(bundleFile, testFiles) {
  var extractedFiles = unpack(bundleFile.bundled).map(function(row) { return row.id; });

  _.forEach(testFiles, function(f) {
    expect(extractedFiles).to.contain(f.path);
  });
}

/**
 * A test karma plugin, wrapping bro.
 */
function TestPlugin(bro, emitter, config, loggerFactory) {
  this.framework = bro.framework(emitter, config, loggerFactory);
  this.testFilePreprocessor = bro.testFilePreprocessor(config);
  this.bundlePreprocessor = bro.bundlePreprocessor(config);
}

/**
 * Preprocess bundle and test files, collect async results
 * and call the callback with all files in the order they have been processed.
 */
TestPlugin.prototype.preprocess = function preprocess(bundle, testFiles, done) {

  /*jshint validthis:true */
  var plugin = this;

  var total = 1 + testFiles.length;

  var processed = [];

  function fileProcessed(file, result) {
    file.bundled = result;

    processed.push(file);

    if (processed.length == total) {
      done();
    }
  }

  function process(preprocessor, file) {
    preprocessor(file.bundled || '', file, function(result) {
      fileProcessed(file, result);
    });
  }

  process(plugin.bundlePreprocessor, bundle);

  // Karma does not necessarily preprocess test files in the order they are given.
  var shuffledTestFiles = testFiles.slice(0).reverse();

  _.forEach(shuffledTestFiles, function(file) {
    process(plugin.testFilePreprocessor, file);
  });
};

describe('karma-browserify', function() {

  var emitter, loggerFactory, bundle, bro;

  beforeEach(function() {

    emitter = new events.EventEmitter();
    loggerFactory = new LoggerFactory();

    bundle = new BundleFile();

    bundle.update = chai.spy(bundle.update);
    bundle.touch = chai.spy(bundle.touch);
    bundle.remove = chai.spy(bundle.remove);

    bro = new Bro(bundle);
  });

  afterEach(function(done) {
    emitter.emit('exit', done);
  });

  // increase timeout
  this.timeout(8000);

  function createPlugin(config) {
    config = createConfig(config);

    return new TestPlugin(bro, emitter, config, loggerFactory);
  }

  describe('framework', function() {

    describe('init', function() {

      it('should prepend and init bundle file', function() {

        // given
        var config = createConfig();

        // when
        createPlugin(config);

        // then
        expect(bundle.touch).to.have.been.called();

        expect(config.files[0].pattern).to.eql(bundle.location);
      });

      it('should insert bundle file right before first preprocessed file', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*Spec.js' }
          ],
          preprocessors: {
            'foo/*Spec.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // expect bundle file to be inserted at pos=1
        expect(config.files).to.deep.eql([
          { pattern : 'vendor/external.js' },
          { pattern : bundle.location, served : true, included : true, watched : true },
          { pattern : 'foo/*Spec.js' }
        ]);

      });

      it('should insert bundle file before more-specific preprocessed pattern', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*Spec.js' }
          ],
          preprocessors: {
            'foo/*.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // expect bundle file to be inserted at pos=1
        // since foo/*Spec.js matches the foo/*.js glob
        expect(config.files).to.deep.eql([
          { pattern : 'vendor/external.js' },
          { pattern : bundle.location, served : true, included : true, watched : true },
          { pattern : 'foo/*Spec.js' }
        ]);

      });

      it('should not insert bundle file before less-specific preprocessed pattern', function() {

        // given
        var config = createConfig({
          files: [
            { pattern: 'vendor/external.js' },
            { pattern: 'foo/*.js' }
          ],
          preprocessors: {
            'foo/*Spec.js': [ 'browserify' ]
          }
        });

        // when
        createPlugin(config);

        // then
        expect(config.files[0].pattern).to.eql(bundle.location);

      });

    });

    describe('cleanup', function() {

      it('should remove bundle file on exit', function() {

        // given
        createPlugin();

        // when
        emitter.emit('exit', function() { });

        // then
        expect(bundle.remove).to.have.been.called();
      });

    });

  });

  describe('preprocessing', function() {

    it('should create bundle', function(done) {

      // given
      var plugin = createPlugin();

      var bundleFile = createFile(bundle.location);
      var testFileB = createFile('test/fixtures/b.js');
      var testFileC = createFile('test/fixtures/c.js');

      // when
      plugin.preprocess(bundleFile, [ testFileB, testFileC ], function() {

        // then
        // bundle got created
        expectBundleContainments(bundleFile, [ testFileB, testFileC ]);

        // test file stub got created
        expect(testFileB.bundled).to.eql(expectedBundle('test/fixtures/b.js'));
        expect(testFileC.bundled).to.eql(expectedBundle('test/fixtures/c.js'));

        done();
      });

    });

    it('should pass through on updates', function(done) {

      // given
      var plugin = createPlugin();

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/b.js');

      // initial bundle creation
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // when
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // then

          // bundle got passed through
          expectBundleContainments(bundleFile, [ testFile ]);

          // test file got regenerated
          expect(testFile.bundled).to.eql(expectedBundle('test/fixtures/b.js'));

          done();
        });

      });

    });

    describe('automatic rebuild (autoWatch=true)', function() {

      // remember test files and restore them later
      // because they are going to be updated
      var aFile = new RestorableFile(__dirname + '/../fixtures/a.js');
      var bFile = new RestorableFile(__dirname + '/../fixtures/b.js');

      beforeEach(function() {
        aFile.load();
        bFile.load();
      });

      afterEach(function() {
        aFile.restore();
        bFile.restore();
      });

      it('should update on change', function(done) {

        // given
        var plugin = createPlugin({ autoWatch: true });

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/b.js');

        // initial bundle creation
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // reset spy on bundle
          bundle.update.__spy.calls = [];
          bundle.update.__spy.called = false;

          // when
          // update bundle file
          delay(function() {
            aFile.update('module.exports = "UPDATED";');
          });

          // give watch a chance to trigger
          delay(function() {

            // then
            expect(bundle.update).to.have.been.called();

            done();
          }, BUNDLE_UPDATE_CHECK_DELAY);

        });

      });

      it('should handle bundle error', function(done) {

        // given
        var plugin = createPlugin();

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/error.js');

        // when
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // then
          // bundle reports error
          expect(bundleFile.bundled).to.exist;
          expect(bundleFile.bundled.message).to.eql('Unexpected token');

          // test file stub got created anyway
          expect(testFile.bundled).to.eql(expectedBundle('test/fixtures/error.js'));

          done();
        });
      });

      it('should handle bundle update error', function(done) {

        // given
        var plugin = createPlugin({ autoWatch: true });

        var bundleFile = createFile(bundle.location);
        var testFile = createFile('test/fixtures/b.js');

        // initial bundle creation
        plugin.preprocess(bundleFile, [ testFile ], function() {

          // reset spy on bundle
          bundle.update.__spy.calls = [];
          bundle.update.__spy.called = false;

          // when
          // update bundle file
          delay(function() {
            aFile.update('unpoarsable / {{ code');
          });

          // give watch a chance to trigger
          delay(function() {

            // then
            // no update on parse error
            expect(bundle.update).not.to.have.been.called();

            done();
          }, BUNDLE_UPDATE_CHECK_DELAY);

        });

      });

      // TODO(nikku): Yup, aint gonna work on travis CI :-(
      if (!process.env.TRAVIS) {

        it('should handle file remove', function(done) {

          // given
          var plugin = createPlugin({ autoWatch: true });

          var bundleFile = createFile(bundle.location);
          var testFile = createFile('test/fixtures/b.js');

          // initial bundle creation
          plugin.preprocess(bundleFile, [ testFile ], function() {

            // reset spy on bundle
            bundle.update.__spy.calls = [];
            bundle.update.__spy.called = false;

            // when
            // remove file
            delay(function() {
              bFile.remove();
            });

            // update a bundled file
            delay(function() {
              aFile.update('module.exports = "UPDATED";');
            }, 500);

            // give watch a chance to trigger
            delay(function() {

              // then
              // update with file deleted
              expect(bundle.update).to.have.been.called();

              expect(bundleFile.realContents()).not.to.contain('/b.js');
              done();
            }, BUNDLE_UPDATE_CHECK_DELAY);

          });

        });

      }

    });

  });

  describe('browserify', function() {

    it('should configure transform', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          transform: [ 'brfs' ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle got created
        expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");

        done();
      });
    });

    it('should configure transform with options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          transform: [ ['brfs', { foo: 'bar' }] ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle got created
        expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");

        done();
      });
    });

    it('should support configure hook in the options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          configure: function(bundle) {
            bundle.external('foobar');
          }
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/configure.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then
        // bundle got created
        expect(bundleFile.bundled).to.exist;
        expect(bundleFile.bundled).to.contain('require(\'foobar\')');

        done();
      });
    });

    it('should configure debug with source map support', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          debug: true
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/a.js');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // contains source map
        expect(bundleFile.bundled).to.contain('//# sourceMappingURL');

        // and has the parsed mapping attached
        expect(bundleFile.sourceMap).to.exist;

        done();
      });
    });

    it('should configure plugin with options', function(done) {

      // given
      var plugin = createPlugin({
        browserify: {
          plugin: [ ['tsify', { removeComments: true } ] ]
        }
      });

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/plugin.ts');

      // when
      plugin.preprocess(bundleFile, [ testFile ], function() {

        // then

        // bundle file got processed via plug-in
        expect(bundleFile.bundled).to.contain('module.exports = plugin');
        expect(bundleFile.bundled).not.to.contain('// typescript');

        done();
      });
    });

    it('should persist transforms', function(done) {

      // given
      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/transform.js');

      var plugin = createPlugin({
        browserify: {
          transform: [ 'brfs' ],
          // Hook into bundler/pipeline events for success/error
          configure: function(bundle) {

            // after first bundle
            bundle.once('bundled', function (err) {

              // fail if there was an error
              if (err) {
                return done(err);
              }

              // set up error/success handlers
              bundle.on('bundled', function(err, contents) {
                if (err) {
                  return done(err);
                }

                expect(bundleFile.bundled).to.contain("module.exports.text = '<' + \"HALLO\" + '>'");
                done();
              });

              // rebundle
              plugin.preprocess(bundleFile, [ testFile ], function() {});
            });
          }
        }
      });

      // initial bundle
      plugin.preprocess(bundleFile, [ testFile ], function() {});
    });

    it('should persist plugins', function(done) {

      var bundleFile = createFile(bundle.location);
      var testFile = createFile('test/fixtures/plugin.ts');
      var plugin = createPlugin({
        browserify: {
          plugin: [ ['tsify', { removeComments: true } ] ],
          // Hook into bundler/pipeline events for success/error
          configure: function(bundle) {
            // After first bundle
            bundle.once('bundled', function (err) {
              // Fail if there was an error
              if (err) {
                return done(err);
              }

              // Set up error/success handlers
              bundle.once('bundled', done);

              // Rebundle
              plugin.preprocess(bundleFile, [ testFile ], function() {});
            });
          }
        }
      });

      // Initial bundle
      plugin.preprocess(bundleFile, [ testFile ], function() {});
    });

  });

});
<|endoftext|>


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

var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var util = require('./lib/util');

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

var peg = require('gulp-peg');

var JS_SOURCES = ['gulpfile.js',
                  'lib/*.js',
                  'bin/firebase-bolt',
                  'test/*.js'];

var TEST_FILES = ['test/generator-test.js', 'test/parser-test.js'];

gulp.task('lint', function() {
  return gulp.src(JS_SOURCES.concat(['!lib/rules-parser.js']))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('build', ['build-peg', 'browserify-bolt']);

gulp.task('build-peg', function() {
  return gulp.src('src/rules-parser.pegjs')
    .pipe(peg())
    .pipe(gulp.dest('lib'));
});

gulp.task('browserify-bolt', ['build-peg'], function() {
  return browserifyToDist('lib/bolt.js', { standalone: 'bolt' });
});

// TODO: Use source to pipe glob of test files through browserify.
gulp.task('browserify-parser-test', function() {
  return browserifyToDist('test/parser-test.js', { exclude: 'bolt' });
});

gulp.task('browserify-generator-test', function() {
  return browserifyToDist('test/generator-test.js', { exclude: 'bolt' });
});

gulp.task('browserify-mail-test', function() {
  return browserifyToDist('test/mail-test', { exclude: 'bolt' });
});

gulp.task('browserify', ['browserify-bolt',
                         'browserify-parser-test',
                         'browserify-generator-test',
                         'browserify-mail-test']);

// Runs the Mocha test suite
gulp.task('test', ['lint', 'build'], function() {
  return gulp.src(TEST_FILES)
    .pipe(mocha({ui: 'tdd'}));
});

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

function browserifyToDist(entry, opts) {
  // Browserify options include:
  //   standalone: name of exported module
  //   exclude: Don't include namespace.
  //   debug: Include sourcemap in output.
  opts = util.extend({}, opts, { entries: [entry], debug: true });
  var exclude = opts.exclude;
  delete opts.exclude;
  var b = browserify(opts);
  if (exclude) {
    b.exclude(exclude);
  }
  return b
    .bundle()
    .pipe(source(path.basename(entry)))
    .on('error', gutil.log)
    .pipe(gulp.dest('dist'));
}
<commit_msg>Add missing test files to 'gulp test' default.<commit_after>/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var util = require('./lib/util');

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

var peg = require('gulp-peg');

var JS_SOURCES = ['gulpfile.js',
                  'lib/*.js',
                  'bin/firebase-bolt',
                  'test/*.js'];

var TEST_FILES = ['test/generator-test.js', 'test/parser-test.js',
                  'test/ast-test.js', 'test/util-test.js'];

gulp.task('lint', function() {
  return gulp.src(JS_SOURCES.concat(['!lib/rules-parser.js']))
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('build', ['build-peg', 'browserify-bolt']);

gulp.task('build-peg', function() {
  return gulp.src('src/rules-parser.pegjs')
    .pipe(peg())
    .pipe(gulp.dest('lib'));
});

gulp.task('browserify-bolt', ['build-peg'], function() {
  return browserifyToDist('lib/bolt.js', { standalone: 'bolt' });
});

// TODO: Use source to pipe glob of test files through browserify.
gulp.task('browserify-parser-test', function() {
  return browserifyToDist('test/parser-test.js', { exclude: 'bolt' });
});

gulp.task('browserify-generator-test', function() {
  return browserifyToDist('test/generator-test.js', { exclude: 'bolt' });
});

gulp.task('browserify-mail-test', function() {
  return browserifyToDist('test/mail-test', { exclude: 'bolt' });
});

gulp.task('browserify', ['browserify-bolt',
                         'browserify-parser-test',
                         'browserify-generator-test',
                         'browserify-mail-test']);

// Runs the Mocha test suite
gulp.task('test', ['lint', 'build'], function() {
  return gulp.src(TEST_FILES)
    .pipe(mocha({ui: 'tdd'}));
});

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

function browserifyToDist(entry, opts) {
  // Browserify options include:
  //   standalone: name of exported module
  //   exclude: Don't include namespace.
  //   debug: Include sourcemap in output.
  opts = util.extend({}, opts, { entries: [entry], debug: true });
  var exclude = opts.exclude;
  delete opts.exclude;
  var b = browserify(opts);
  if (exclude) {
    b.exclude(exclude);
  }
  return b
    .bundle()
    .pipe(source(path.basename(entry)))
    .on('error', gutil.log)
    .pipe(gulp.dest('dist'));
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat')
var uglify = require('gulp-uglify')
var ngAnnotate = require('gulp-ng-annotate')
var sourceMaps = require('gulp-sourcemaps')

var fs = require('fs');
fs.readdirSync(__dirname + '/gulp').forEach(function(task) {
    require('./gulp/' + task);
})+
//var developServer = require('gulp-develop-server')

gulp.task('js', function() {
    gulp.src(['src/ng/module.js','src/ng/**/*.js'])
        .pipe(sourceMaps.init())
            .pipe(concat('app.js'))
            .pipe(ngAnnotate())
            .pipe(uglify())
        .pipe(sourceMaps.write())
        .pipe(gulp.dest('server/assets'))
})

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

gulp.task('watch:css', function () {
    gulp.watch('src/css/**/*.styl', ['css'])
})

gulp.task('dev', ['watch:css','watch:js','dev:server']);

/*gulp.task('server:restart', function() {
    gulp.watch(['./app.js'], developServer.restart);
})*/<commit_msg>removed commented code in gulpfile.js<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat')
var uglify = require('gulp-uglify')
var ngAnnotate = require('gulp-ng-annotate')
var sourceMaps = require('gulp-sourcemaps')

var fs = require('fs');
fs.readdirSync(__dirname + '/gulp').forEach(function(task) {
    require('./gulp/' + task);
})+
//var developServer = require('gulp-develop-server')

gulp.task('js', function() {
    gulp.src(['src/ng/module.js','src/ng/**/*.js'])
        .pipe(sourceMaps.init())
            .pipe(concat('app.js'))
            .pipe(ngAnnotate())
            .pipe(uglify())
        .pipe(sourceMaps.write())
        .pipe(gulp.dest('server/assets'))
})

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

gulp.task('watch:css', function () {
    gulp.watch('src/css/**/*.styl', ['css'])
})

gulp.task('dev', ['watch:css','watch:js','dev:server']);
<|endoftext|>