<commit_before>/**
 * Created by Awesome on 1/30/2016.
 */

// use strict
'use strict';

// require dependencies
var glob       = require ('glob');
var path       = require ('path');
var fs         = require ('fs');
var through    = require ('through2');
var browserify = require ('browserify');
var babelify   = require ('babelify');
var source     = require ('vinyl-source-stream');

// require gulp dependencies
var rename     = require ('gulp-rename');
var sass       = require ('gulp-sass');
var sourcemaps = require ('gulp-sourcemaps');
var concat     = require ('gulp-concat');
var riot       = require ('gulp-riot');
var insert     = require ('gulp-insert');
var streamify  = require ('gulp-streamify');
var uglify     = require ('gulp-uglify');
var nodemon    = require ('gulp-nodemon');

// import local dependencies
var configPipe = require ('./bin/util/gulp.config.pipe');

/**
 * build gulp builder class
 */
class gulpBuilder {
    /**
     * construct gulp builder class
     */
    constructor () {
        // bind variables
        this.gulp = require ('gulp');

        // bind methods
        this._tasks = {
            'sass' : [
                'node_modules/bootstrap/scss/bootstrap-flex.scss',
                './bin/bundles/*/resources/scss/bootstrap.scss',
                './app/bundles/*/resources/scss/bootstrap.scss'
            ],
            'daemon' : [
                './bin/bundles/**/*Daemon.js',
                './app/bundles/**/*Daemon.js'
            ],
            'config' : [
                './bin/bundles/**/*Controller.js',
                './app/bundles/**/*Controller.js'
            ],
            'view' : [
                './bin/bundles/*/view/**/*.hbs',
                './app/bundles/*/view/**/*.hbs'
            ],
            'tag' : [
                './bin/bundles/*/view/**/*.tag',
                './app/bundles/*/view/**/*.tag'
            ],
            'js' : [
                './bin/bundles/*/resources/js/bootstrap.js',
                './app/bundles/*/resources/js/bootstrap.js'
            ]
        };

        // set keys array
        var that  = this;
        var keys  = Object.keys(this._tasks);
        var watch = [];

        // bind and add gulp task methods
        for (var i = 0; i < keys.length; i ++) {
            // bind method
            this[keys[i]] = this[keys[i]].bind (this);
            // setup task
            this.gulp.task (keys[i], this[keys[i]]);
            // setup watch task
            this.gulp.task (keys[i] + ':watch', () => {
                that.gulp.watch (that._tasks[keys[i]], [keys[i]]);
            });
            // add watch task to array
            watch.push(keys[i] + ':watch');
        }

        // add install task
        this.gulp.task('install', keys);
        // add watch task
        this.gulp.task('watch', watch);
        // add dev server task
        this.gulp.task('dev', ['watch'], () => {
            // run nodemon on app.js
            nodemon({
                'script' : './app.js',
                'ext'    : 'js hbs json',
                'watch'  : [
                    'cache/'
                ],
                'env'    : {
                    'NODE_ENV': 'development'
                }
            });
        });
        // add default task
        this.gulp.task ('default', ['install', 'dev']);
    }

    /**
     * sass task
     */
    sass () {
        // set variables
        var that = this;
        var all  = '';

        // grab gulp source for sass
        this.gulp.src (
            this._tasks['sass']
        ).pipe (through.obj ((chunk, enc, cb) => {
                // add @import to all
                all += '@import ".' + chunk.path.replace (__dirname, '').split (path.delimiter).join ('/') + '"; ';

                // run through callback
                cb (null, chunk);
            })).on ('end', () => {
                // write temp sass file
                fs.writeFile ('./tmp.scss', all, (err) => {
                    if (err) {
                        console.log (err);
                        return;
                    }

                    // pipe temp sass file for sass function
                    that.gulp.src ('./tmp.scss')
                        .pipe (sourcemaps.init ())
                        .pipe (sass ({
                            outputStyle : 'compressed'
                        })).pipe (rename ('app.min.css'))
                        .pipe (sourcemaps.write ('./'))
                        .pipe (that.gulp.dest ('./www/assets/css'))
                        .on ('end', () => {
                            fs.unlinkSync ('./tmp.scss');
                        });
                });
            });
    }

    /**
     * daemon task
     */
    daemon () {
        // grab daemon controllers
        var daemons = [];
        for (var i = 0; i < this._tasks['daemon'].length; i++) {
            daemons = daemons.concat(glob.sync (this._tasks['daemon'][i]));
        }

        // loop daemons
        for (var key in daemons) {
            daemons[key] = daemons[key].replace ('./', '/');
        }

        // write daemons cache file
        fs.writeFile ('./cache/daemons.json', JSON.stringify (daemons), function (err) {
            if (err) {
                return console.log (err);
            }
        });
    }

    /**
     * route task
     */
    config() {
        // set variables
        var that = this;
        var all  = {};

        // get all routes
        this.gulp
            .src (this._tasks['config'])
            .pipe (through.obj (function (chunk, enc, cb) {
                var pip = this;
                configPipe.pipe(chunk).then(result => {
                    pip.push({
                        'result' : result
                    });
                    cb(null, chunk);
                });
            }))
            .on ('data', (data) => {
                that._merge(all, data.result);
            }).on ('end', function () {
                fs.writeFile ('./cache/config.json', JSON.stringify (all), function (err) {
                    if (err) {
                        return console.log (err);
                    }
                });
            });
    }

    /**
     * view task
     */
    view() {
        // move views into single folder
        // @todo bundle prioroty
        this.gulp.src (
            this._tasks['view']
        )
            .pipe (rename (function (filePath) {
                var amended = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (this.gulp.dest ('cache/view'));
    }

    /**
     * tag task
     */
    tag() {
        // move tags into javascript compiled file (riotjs)
        this.gulp.src (
            this._tasks['tag']
        )
            .pipe (rename (function (filePath) {
                var amended      = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (riot ({
                compact : true
            }))
            .pipe (concat ('tags.min.js'))
            .pipe (insert.prepend ('var riot = require(\'riot\');'))
            .pipe (this.gulp.dest ('./cache/tag'));
    }

    /**
     * javascript task
     */
    js() {
        // create javascript array
        var js = [];
        for (var i = 0; i < this._tasks['js'].length; i++) {
            js = js.concat(glob.sync (this._tasks['js'][i]));
        }

        // browserfiy javascript
        browserify ({
            entries : js
        })
            .transform (babelify)
            .bundle ()
            .pipe (source ('app.min.js'))
            .pipe (insert.prepend (fs.readFileSync ('./node_modules/bootstrap/dist/js/bootstrap.js')))
            .pipe (insert.prepend (fs.readFileSync ('./node_modules/jquery/dist/jquery.min.js')))
            .pipe (streamify (uglify ()))
            .pipe (this.gulp.dest ('./www/assets/js'));

    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge(obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export gulp builder class
 *
 * @type {gulpBuilder}
 */
module.exports = new gulpBuilder ();<commit_msg>complete watcher for nodemon gulp task<commit_after>/**
 * Created by Awesome on 1/30/2016.
 */

// use strict
'use strict';

// require dependencies
var glob       = require ('glob');
var path       = require ('path');
var fs         = require ('fs');
var through    = require ('through2');
var browserify = require ('browserify');
var babelify   = require ('babelify');
var source     = require ('vinyl-source-stream');

// require gulp dependencies
var rename     = require ('gulp-rename');
var sass       = require ('gulp-sass');
var sourcemaps = require ('gulp-sourcemaps');
var concat     = require ('gulp-concat');
var riot       = require ('gulp-riot');
var insert     = require ('gulp-insert');
var streamify  = require ('gulp-streamify');
var uglify     = require ('gulp-uglify');
var nodemon    = require ('gulp-nodemon');

// import local dependencies
var configPipe = require ('./bin/util/gulp.config.pipe');

/**
 * build gulp builder class
 */
class gulpBuilder {
    /**
     * construct gulp builder class
     */
    constructor () {
        // bind variables
        this.gulp = require ('gulp');

        // bind methods
        this._tasks = {
            'sass' : [
                'node_modules/bootstrap/scss/bootstrap-flex.scss',
                './bin/bundles/*/resources/scss/bootstrap.scss',
                './app/bundles/*/resources/scss/bootstrap.scss'
            ],
            'daemon' : [
                './bin/bundles/**/*Daemon.js',
                './app/bundles/**/*Daemon.js'
            ],
            'config' : [
                './bin/bundles/**/*Controller.js',
                './app/bundles/**/*Controller.js'
            ],
            'view' : [
                './bin/bundles/*/view/**/*.hbs',
                './app/bundles/*/view/**/*.hbs'
            ],
            'tag' : [
                './bin/bundles/*/view/**/*.tag',
                './app/bundles/*/view/**/*.tag'
            ],
            'js' : [
                './bin/bundles/*/resources/js/bootstrap.js',
                './app/bundles/*/resources/js/bootstrap.js'
            ]
        };

        // set keys array
        var that  = this;
        var keys  = Object.keys(this._tasks);
        var watch = [];

        // bind and add gulp task methods
        for (var i = 0; i < keys.length; i ++) {
            // bind method
            this[keys[i]] = this[keys[i]].bind (this);
            // setup task
            this.gulp.task (keys[i], this[keys[i]]);
            // setup watch task
            this.gulp.task (keys[i] + ':watch', () => {
                that.gulp.watch (that._tasks[keys[i]], [keys[i]]);
            });
            // add watch task to array
            watch.push(keys[i] + ':watch');
        }

        // add install task
        this.gulp.task('install', keys);
        // add watch task
        this.gulp.task('watch', watch);
        // add dev server task
        this.gulp.task('dev', () => {
            // run nodemon task
            nodemon({
                'script' : './app.js',
                'ext'    : 'js hbs json',
                'watch'  : [
                    'cache/'
                ],
                'env'    : {
                    'NODE_ENV': 'development'
                }
            });

            // loop for watch
            for (var i = 0; i < keys.length; i++) {
                that.gulp.watch (that._tasks[keys[i]], [keys[i]]);
            }
        });
        // add default task
        this.gulp.task('default', ['install', 'dev']);
    }

    /**
     * sass task
     */
    sass () {
        // set variables
        var that = this;
        var all  = '';

        // grab gulp source for sass
        this.gulp.src (
            this._tasks['sass']
        ).pipe (through.obj ((chunk, enc, cb) => {
                // add @import to all
                all += '@import ".' + chunk.path.replace (__dirname, '').split (path.delimiter).join ('/') + '"; ';

                // run through callback
                cb (null, chunk);
            })).on ('end', () => {
                // write temp sass file
                fs.writeFile ('./tmp.scss', all, (err) => {
                    if (err) {
                        console.log (err);
                        return;
                    }

                    // pipe temp sass file for sass function
                    that.gulp.src ('./tmp.scss')
                        .pipe (sourcemaps.init ())
                        .pipe (sass ({
                            outputStyle : 'compressed'
                        })).pipe (rename ('app.min.css'))
                        .pipe (sourcemaps.write ('./'))
                        .pipe (that.gulp.dest ('./www/assets/css'))
                        .on ('end', () => {
                            fs.unlinkSync ('./tmp.scss');
                        });
                });
            });
    }

    /**
     * daemon task
     */
    daemon () {
        // grab daemon controllers
        var daemons = [];
        for (var i = 0; i < this._tasks['daemon'].length; i++) {
            daemons = daemons.concat(glob.sync (this._tasks['daemon'][i]));
        }

        // loop daemons
        for (var key in daemons) {
            daemons[key] = daemons[key].replace ('./', '/');
        }

        // write daemons cache file
        fs.writeFile ('./cache/daemons.json', JSON.stringify (daemons), function (err) {
            if (err) {
                return console.log (err);
            }
        });
    }

    /**
     * route task
     */
    config() {
        // set variables
        var that = this;
        var all  = {};

        // get all routes
        this.gulp
            .src (this._tasks['config'])
            .pipe (through.obj (function (chunk, enc, cb) {
                var pip = this;
                configPipe.pipe(chunk).then(result => {
                    pip.push({
                        'result' : result
                    });
                    cb(null, chunk);
                });
            }))
            .on ('data', (data) => {
                that._merge(all, data.result);
            }).on ('end', function () {
                fs.writeFile ('./cache/config.json', JSON.stringify (all), function (err) {
                    if (err) {
                        return console.log (err);
                    }
                });
            });
    }

    /**
     * view task
     */
    view() {
        // move views into single folder
        // @todo bundle prioroty
        this.gulp.src (
            this._tasks['view']
        )
            .pipe (rename (function (filePath) {
                var amended = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (this.gulp.dest ('cache/view'));
    }

    /**
     * tag task
     */
    tag() {
        // move tags into javascript compiled file (riotjs)
        this.gulp.src (
            this._tasks['tag']
        )
            .pipe (rename (function (filePath) {
                var amended      = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (riot ({
                compact : true
            }))
            .pipe (concat ('tags.min.js'))
            .pipe (insert.prepend ('var riot = require(\'riot\');'))
            .pipe (this.gulp.dest ('./cache/tag'));
    }

    /**
     * javascript task
     */
    js() {
        // create javascript array
        var js = [];
        for (var i = 0; i < this._tasks['js'].length; i++) {
            js = js.concat(glob.sync (this._tasks['js'][i]));
        }

        // browserfiy javascript
        browserify ({
            entries : js
        })
            .transform (babelify)
            .bundle ()
            .pipe (source ('app.min.js'))
            .pipe (insert.prepend (fs.readFileSync ('./node_modules/bootstrap/dist/js/bootstrap.js')))
            .pipe (insert.prepend (fs.readFileSync ('./node_modules/jquery/dist/jquery.min.js')))
            .pipe (streamify (uglify ()))
            .pipe (this.gulp.dest ('./www/assets/js'));

    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge(obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export gulp builder class
 *
 * @type {gulpBuilder}
 */
module.exports = new gulpBuilder ();<|endoftext|>


<commit_before>var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var del         = require('del');
var gulp        = require('gulp');
var rename      = require('gulp-rename');
var pagespeed   = require('psi');
var runSequence = require('run-sequence');
var pkg         = require('./package.json');
var autoprefixerBrowsers = ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'];
var headerBanner = [
'/*!',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link    <%= pkg.homepage %>',
' * @author  <%= pkg.author %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');

module.exports = {
  'browserSync': {
    notify: true,
    https: false,
    server: './_public',
  },
  'uninstall': {
    files: [
      './dist',
      './public',
      './docs/static/css/build',
      './docs/static/vendor',
      './scss/vendor'
    ]
  },
  'sass': {
    src: './scss/sircus.scss',
    dest: './docs/static/css/build',
    autoprefixer: autoprefixerBrowsers,
    pkg: pkg,
    headerBanner: true,
    banner:headerBanner,
    staticGenerator: false,
    staticGeneratorBuild:''
  },
  'csslint': {
    setting:'./.csslintrc',
    src: './docs/static/css/build/sircus.css'
  },
  'cssmin': {
    src: './docs/static/css/build/sircus.css',
    dest: './docs/static/css/build'
  },
  'ghpage' : {
    src : './public/**/*',
    remoteUrl : 'https://github.com/sircus/sircus.github.io.git',
    branch : 'master'
  },
  'hugo' : {
    buildMessages : 'Running: $ hugo'
  },
  'bump': {
    version: pkg.version, // base
    src:  './bower.json', //
    dest: '.'
  },
  'psi': {
    production: 'http://sircus.blivesta.com',
  }
};

gulp.task('bower', require('gulptasks/lib/bower'));
gulp.task('sass', require('gulptasks/lib/sass'));
gulp.task('csslint', require('gulptasks/lib/csslint'));
gulp.task('cssmin', require('gulptasks/lib/cssmin'));
gulp.task('deploy', require('gulptasks/lib/ghpage'));
gulp.task('bump', require('gulptasks/lib/bump'));
gulp.task('hugo', require('gulptasks/lib/hugo'));
gulp.task('uninstall', del.bind(null, module.exports.uninstall.files));
gulp.task('server', function(){ browserSync.init(null, module.exports.browserSync); });

gulp.task('default',['server'],function() {
  gulp.watch(['./scss/**/*.scss'], ['sass']);
  gulp.watch(['./docs/**/*.html', './docs/**/*.md', './docs/**/*.css'], ['hugo',reload]);
});

gulp.task('dist',function() {
  return gulp.src('./docs/static/css/build/**')
    .pipe(gulp.dest('./dist'));
});

gulp.task('bower-html5-reset',function() {
  return gulp.src('./bower_components/HTML5-Reset/assets/css/reset.css')
    .pipe(rename('html5-reset.css'))
    .pipe(gulp.dest('./docs/static/vendor/'))
    .pipe(rename('_html5-reset.scss'))
    .pipe(gulp.dest('./scss/vendor/'));
});

gulp.task('bower-normalize',function() {
  return gulp.src('./bower_components/normalize.css/normalize.css')
    .pipe(rename('normalize.css'))
    .pipe(gulp.dest('./docs/static/vendor/'))
    .pipe(rename('_normalize.scss'))
    .pipe(gulp.dest('./scss/vendor/'));
});

gulp.task('build', function() {
  runSequence(
    'bower','uninstall',
    ['bower-html5-reset','bower-normalize'],
    'sass',
    ['csslint','cssmin'],
    'hugo',
    ['bump','dist','default']
  );
});

gulp.task('psi', function (cb) {
  pagespeed.output(module.exports.psi.production, {
    strategy: 'mobile'
  }, cb);
});
<commit_msg>Fixed path `gulp deploy`<commit_after>var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var del         = require('del');
var gulp        = require('gulp');
var rename      = require('gulp-rename');
var pagespeed   = require('psi');
var runSequence = require('run-sequence');
var pkg         = require('./package.json');
var autoprefixerBrowsers = ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'];
var headerBanner = [
'/*!',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link    <%= pkg.homepage %>',
' * @author  <%= pkg.author %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');

module.exports = {
  'browserSync': {
    notify: true,
    https: false,
    server: './_public',
  },
  'uninstall': {
    files: [
      './dist',
      './public',
      './docs/static/css/build',
      './docs/static/vendor',
      './scss/vendor'
    ]
  },
  'sass': {
    src: './scss/sircus.scss',
    dest: './docs/static/css/build',
    autoprefixer: autoprefixerBrowsers,
    pkg: pkg,
    headerBanner: true,
    banner:headerBanner,
    staticGenerator: false,
    staticGeneratorBuild:''
  },
  'csslint': {
    setting:'./.csslintrc',
    src: './docs/static/css/build/sircus.css'
  },
  'cssmin': {
    src: './docs/static/css/build/sircus.css',
    dest: './docs/static/css/build'
  },
  'ghpage' : {
    src : './_public/**/*',
    remoteUrl : 'https://github.com/sircus/sircus.github.io.git',
    branch : 'master'
  },
  'hugo' : {
    buildMessages : 'Running: $ hugo'
  },
  'bump': {
    version: pkg.version, // base
    src:  './bower.json', //
    dest: '.'
  },
  'psi': {
    production: 'http://sircus.blivesta.com',
  }
};

gulp.task('bower', require('gulptasks/lib/bower'));
gulp.task('sass', require('gulptasks/lib/sass'));
gulp.task('csslint', require('gulptasks/lib/csslint'));
gulp.task('cssmin', require('gulptasks/lib/cssmin'));
gulp.task('deploy', require('gulptasks/lib/ghpage'));
gulp.task('bump', require('gulptasks/lib/bump'));
gulp.task('hugo', require('gulptasks/lib/hugo'));
gulp.task('uninstall', del.bind(null, module.exports.uninstall.files));
gulp.task('server', function(){ browserSync.init(null, module.exports.browserSync); });

gulp.task('default',['server'],function() {
  gulp.watch(['./scss/**/*.scss'], ['sass']);
  gulp.watch(['./docs/**/*.html', './docs/**/*.md', './docs/**/*.css'], ['hugo',reload]);
});

gulp.task('dist',function() {
  return gulp.src('./docs/static/css/build/**')
    .pipe(gulp.dest('./dist'));
});

gulp.task('bower-html5-reset',function() {
  return gulp.src('./bower_components/HTML5-Reset/assets/css/reset.css')
    .pipe(rename('html5-reset.css'))
    .pipe(gulp.dest('./docs/static/vendor/'))
    .pipe(rename('_html5-reset.scss'))
    .pipe(gulp.dest('./scss/vendor/'));
});

gulp.task('bower-normalize',function() {
  return gulp.src('./bower_components/normalize.css/normalize.css')
    .pipe(rename('normalize.css'))
    .pipe(gulp.dest('./docs/static/vendor/'))
    .pipe(rename('_normalize.scss'))
    .pipe(gulp.dest('./scss/vendor/'));
});

gulp.task('build', function() {
  runSequence(
    'bower','uninstall',
    ['bower-html5-reset','bower-normalize'],
    'sass',
    ['csslint','cssmin'],
    'hugo',
    ['bump','dist','default']
  );
});

gulp.task('psi', function (cb) {
  pagespeed.output(module.exports.psi.production, {
    strategy: 'mobile'
  }, cb);
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var Q = require('q');
var debug = require('debug')('testee:runner');
var utils = require('./utils');

function Runner(options) {
  this.configuration = options;
}

_.extend(Runner.prototype, {
  testOne: function(file, browser) {
    browser = typeof browser === 'string' ? { browser: browser } : browser;

    var timeout = this.configuration.timeout;
    var testRuns = this.configuration.runs;
    // We use a token to identify the browser
    var token = utils.generateToken();
    // Add the token to the URL we are going to launch
    var url = this.configuration.tunnel.makeUrl(file, {
      __token: token
    });
    // The title for potential error messages
    var errorTitle = url + ' on ' + JSON.stringify(browser);
    // Returns a Deferred that keeps track of our test run (including timeouts)
    var trackTestRun = function() {
      debug('tracking test run', url, browser);
      var dfd = Q.defer();
      var checkToken = new RegExp(token);
      var checkIfRunIsFinished = function(data) {
        var status = data.status === 'finished' && checkToken.test(data.file);
        debug('checking if run', url, 'is finished', status);
        // The file property contains the token we added to the browser URL
        if(status) {
          testRuns.removeListener('patched', checkIfRunIsFinished);
          dfd.resolve(data);
        }
      };
      var testTimedOut = function() {
        debug('test', url, 'timed out');
        testRuns.removeListener('patched', checkIfRunIsFinished);
        testRuns.removeListener('created', resetTimeout);

        dfd.reject(new utils.TesteeError(new Error('Browser timed out within ' + timeout + ' seconds'),
          errorTitle));
      };
      // Sets the test run timeout
      var timer = setTimeout(testTimedOut, timeout * 1000);
      var resetTimeout = function(data) {
        debug('checking if browser timeout can be reset', url, checkToken.test(data.file));
        // When a test run with our token has been created we can reset the timeout
        if(checkToken.test(data.file)) {
          testRuns.removeListener('created', resetTimeout);
          clearTimeout(timer);
        }
      };

      testRuns.on('patched', checkIfRunIsFinished);
      testRuns.on('created', resetTimeout);

      return dfd.promise;
    };

    debug('running individual test', url, browser);
    return Q.nfcall(this.configuration.launcher, url, browser).then(function(instance) {
      debug('browser instance started', browser);
      if(instance.process && instance.process.stdout) {
        // TODO log process stdout
        instance.process.stdout.on('data', function(data) {
          debug(url, browser, data);
        });
      }

      return trackTestRun().finally(function() {
        debug('stopping browser instance', browser);
        // Shut down the browser instance
        return Q.ninvoke(instance, 'stop');
      });
    }, function(error) {
      throw new utils.TesteeError(error, errorTitle);
    });
  },

  test: function(files, browsers) {
    debug('running tests for', files, browsers);
    files = typeof files === 'string' ? [files] : files;
    browsers = typeof browsers === 'string' ? [browsers] : browsers;

    var self = this;
    var result = Q.defer();
    var delay = this.configuration.delay;
    // Runs each browser in parallel
    var runners = _.toArray(browsers).map(function(browser) {
      debug('initializing sequential test runs for browser', browser);
      var browserRunner = Q();
      var results = [];

      // And each file sequentially for every browser
      _.each(files, function(file, index) {
        var addToResults = function(data) {
          results.push(data);
          // If it is not the last file, we add a delay to make sure the previous
          // browser instance has some time to shut down gracefully
          return index === files.length - 1 ? results : Q.delay(delay);
        };

        browserRunner = browserRunner.then(function() {
            return self.testOne(file, browser);
          })
          // In both, error cases and success we want to
          // have it in the result list
          .then(addToResults, addToResults)
          .thenResolve(results);
      });
      return browserRunner;
    });

    // Normalizes the results from all the test runs
    // By turning them into a single array (including errors)
    Q.allSettled(runners).then(function(results) {
      var collectedResults = [];
      results.forEach(function(current) {
        if(current.value) {
          collectedResults.push.apply(collectedResults, current.value);
        }
      });
      return collectedResults;
    }).then(function(flattened) {
      if(_.some(flattened, function(result) {
        return result instanceof Error || result.failed > 0;
      })) {
        result.reject(flattened);
      } else {
        result.resolve(flattened);
      }
    });

    return result.promise;
  }
});

module.exports = Runner;
<commit_msg>Report browser stdout and stderr in debug mode.<commit_after>var _ = require('lodash');
var Q = require('q');
var debug = require('debug')('testee:runner');
var utils = require('./utils');

function Runner(options) {
  this.configuration = options;
}

_.extend(Runner.prototype, {
  testOne: function(file, browser) {
    browser = typeof browser === 'string' ? { browser: browser } : browser;

    var timeout = this.configuration.timeout;
    var testRuns = this.configuration.runs;
    // We use a token to identify the browser
    var token = utils.generateToken();
    // Add the token to the URL we are going to launch
    var url = this.configuration.tunnel.makeUrl(file, {
      __token: token
    });
    // The title for potential error messages
    var errorTitle = url + ' on ' + JSON.stringify(browser);
    // Returns a Deferred that keeps track of our test run (including timeouts)
    var trackTestRun = function() {
      debug('tracking test run', url, browser);
      var dfd = Q.defer();
      var checkToken = new RegExp(token);
      var checkIfRunIsFinished = function(data) {
        var status = data.status === 'finished' && checkToken.test(data.file);
        debug('checking if run', url, 'is finished', status);
        // The file property contains the token we added to the browser URL
        if(status) {
          testRuns.removeListener('patched', checkIfRunIsFinished);
          dfd.resolve(data);
        }
      };
      var testTimedOut = function() {
        debug('test', url, 'timed out');
        testRuns.removeListener('patched', checkIfRunIsFinished);
        testRuns.removeListener('created', resetTimeout);

        dfd.reject(new utils.TesteeError(new Error('Browser timed out within ' + timeout + ' seconds'),
          errorTitle));
      };
      // Sets the test run timeout
      var timer = setTimeout(testTimedOut, timeout * 1000);
      var resetTimeout = function(data) {
        debug('checking if browser timeout can be reset', url, checkToken.test(data.file));
        // When a test run with our token has been created we can reset the timeout
        if(checkToken.test(data.file)) {
          testRuns.removeListener('created', resetTimeout);
          clearTimeout(timer);
        }
      };

      testRuns.on('patched', checkIfRunIsFinished);
      testRuns.on('created', resetTimeout);

      return dfd.promise;
    };

    debug('running individual test', url, browser);
    return Q.nfcall(this.configuration.launcher, url, browser).then(function(instance) {
      debug('browser instance started', browser);
      var proc = instance.process;
      var debugData = function(data) {
        debug(url, browser, data);
      };

      if(proc) {
        if(proc.stdout) {
          proc.stdout.on('data', debugData);
        }

        if(proc.stderr) {
          proc.stderr.on('data', debugData);
        }
      }

      return trackTestRun().finally(function() {
        debug('stopping browser instance', browser);
        // Shut down the browser instance
        return Q.ninvoke(instance, 'stop');
      });
    }, function(error) {
      throw new utils.TesteeError(error, errorTitle);
    });
  },

  test: function(files, browsers) {
    debug('running tests for', files, browsers);
    files = typeof files === 'string' ? [files] : files;
    browsers = typeof browsers === 'string' ? [browsers] : browsers;

    var self = this;
    var result = Q.defer();
    var delay = this.configuration.delay;
    // Runs each browser in parallel
    var runners = _.toArray(browsers).map(function(browser) {
      debug('initializing sequential test runs for browser', browser);
      var browserRunner = Q();
      var results = [];

      // And each file sequentially for every browser
      _.each(files, function(file, index) {
        var addToResults = function(data) {
          results.push(data);
          // If it is not the last file, we add a delay to make sure the previous
          // browser instance has some time to shut down gracefully
          return index === files.length - 1 ? results : Q.delay(delay);
        };

        browserRunner = browserRunner.then(function() {
            return self.testOne(file, browser);
          })
          // In both, error cases and success we want to
          // have it in the result list
          .then(addToResults, addToResults)
          .thenResolve(results);
      });
      return browserRunner;
    });

    // Normalizes the results from all the test runs
    // By turning them into a single array (including errors)
    Q.allSettled(runners).then(function(results) {
      var collectedResults = [];
      results.forEach(function(current) {
        if(current.value) {
          collectedResults.push.apply(collectedResults, current.value);
        }
      });
      return collectedResults;
    }).then(function(flattened) {
      if(_.some(flattened, function(result) {
        return result instanceof Error || result.failed > 0;
      })) {
        result.reject(flattened);
      } else {
        result.resolve(flattened);
      }
    });

    return result.promise;
  }
});

module.exports = Runner;
<|endoftext|>


<commit_before>var searchMovie = function (eventbus, movieId) {
    console.log(movieId);
    eventbus.send("api_get_movie", movieId.toString(), function (error, reply) {
        var data = reply.body;
        console.log(data);
        $("#search-result").empty().hide();
        $("#movie-result").empty().append(
            $.parseHTML(
                JSON.stringify(data, null, 2)
            )
        ).show();
        $("#search").val(data.original_title);
        $('#movie-title').text(data.original_title);
        $('#movie-title').addClass('movies-heading');
        $('#navbar-background').addClass('transparent');
        $("#movie-poster-card").empty().append(
          $.parseHTML(
              ''
          )
        );
        $("#body").attr("background", 'http://image.tmdb.org/t/p/w1920' + data.backdrop_path);
    });
};

fallback.ready(['jQuery', 'SockJS', 'EventBus'], function () {
    var eventbus = new EventBus("/eventbus");
    eventbus.onopen = function () {
        $("#search").keyup(function (e) {
            if (e.keyCode == 13) {
                $("#search-result").empty();
                eventbus.send("api_get_search", $("#search").val(), function (error, reply) {
                    var data = reply.body.results;
                    console.log(data);
                    $.each(data, function (i) {
                        var movie = data[i];
                        var arrayOfNodes = $.parseHTML(
                            '
' +
                            '' +
                            movie.release_date.split('-')[0] + ' . . . . ' +
                            movie.original_title +
                            '' +
                            '
');
                        arrayOfNodes[0].firstChild.onclick = function () {
                            searchMovie(eventbus, movie.id);
                        };
                        $("#search-result").append(arrayOfNodes).show();
                        if (i === 9) {
                            return false;
                        }
                    });
                    $("#movie-poster-card").empty();
                    $("#movie-result").hide();
                });
            }
        });
    };
});<commit_msg>search movie poster<commit_after>var searchMovie = function (eventbus, movieId) {
    console.log(movieId);
    eventbus.send("api_get_movie", movieId.toString(), function (error, reply) {
        var data = reply.body;
        console.log(data);
        $("#search-result").empty().hide();
        $("#movie-result").empty().append(
            $.parseHTML(
                JSON.stringify(data, null, 2)
            )
        ).show();
        $("#search").val(data.original_title);
        $('#movie-title').text(data.original_title);
        $('#movie-title').addClass('movies-heading');
        $('#navbar-background').addClass('transparent');
        $("#movie-poster-card").empty().append(
          $.parseHTML(
              ''
          )
        );
        $("#body").attr("background", 'http://image.tmdb.org/t/p/w1920' + data.backdrop_path);
    });
};

fallback.ready(['jQuery', 'SockJS', 'EventBus'], function () {
    var eventbus = new EventBus("/eventbus");
    eventbus.onopen = function () {
        $("#search").keyup(function (e) {
            if (e.keyCode == 13) {
                $("#search-result").empty();
                eventbus.send("api_get_search", $("#search").val(), function (error, reply) {
                    var data = reply.body.results;
                    console.log(data);
                    $.each(data, function (i) {
                        var movie = data[i];
                        var arrayOfNodes = $.parseHTML(
                            '
' +
                                '' +
                                    movie.release_date.split('-')[0] + ' . . . . ' +
                                    movie.original_title +
                                '' +
                            '' +
                            '
');
                        arrayOfNodes[0].firstChild.onclick = function () {
                            searchMovie(eventbus, movie.id);
                        };
                        $("#search-result").append(arrayOfNodes).show();
                        if (i === 9) {
                            return false;
                        }
                    });
                    $("#movie-poster-card").empty();
                    $("#movie-result").hide();
                });
            }
        });
    };
});<|endoftext|>


<commit_before>var bump = require('gulp-bump');
var exec = require('child_process').exec;
var fs = require('fs-extra');
var git = require('gulp-git');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var tagVersion = require('gulp-tag-version');
var template = require('gulp-template');
var util = require('util');
var yaml = require('js-yaml');
var resource = require('./src/resource');
var helpers = require('./src/helpers');

/**
 * Paths
 */
var test = 'test/**/*';

/**
 * Environment
 */
var languages = {
  js: {
    repo: 'Asana/node-asana',
    branch: 'api-meta-incoming',
    templatePath: 'src/templates',
    outputPath: 'lib/resources/gen',
    updatePackage: function(version, cb) {
      var repoRoot = paths.repo('js');
      var destPackage = readPackage(repoRoot + '/package.json');
      destPackage.version = version;
      writePackage(repoRoot + '/package.json', destPackage);
      exec('git add package.json', {cwd: repoRoot}, cb);
    }
  }
};

var paths = {
  dist: function(lang) {
    return 'dist/' + lang;
  },
  repo: function(lang) {
    return 'dist/git/' + lang;
  },
  repoOutput: function(lang) {
    return paths.repo(lang) + '/' + paths.repoOutputRelative(lang);
  },
  repoOutputRelative: function(lang) {
    return languages[lang].outputPath;
  }
};

function readPackage(filename) {
  return fs.readJSONSync(filename || 'package.json');
}

function writePackage(filename, data) {
  return fs.writeJSONSync(filename || 'package.json', data);
}

/**
 * High-level tasks
 */

// Build all languages
gulp.task('build', ['test'].concat(Object.keys(languages).map(function(lang) {
  return 'build-' + lang;
})));

// Deploy languages
gulp.task('deploy', ['ensure-git-clean', 'build'].concat(Object.keys(languages).map(function(lang) {
  return 'deploy-' + lang;
})));

/**
 * Generate build and deploy rules for each language
 */
var resourceNames = resource.names();
Object.keys(languages).forEach(function(lang) {
  var config = languages[lang];
  var outputPath = paths.repoOutput(lang);
  var repoRoot = paths.repo(lang);
  var token = process.env.ASANA_GITHUB_TOKEN || null;

  function echoAndExec() {
    if (process.env.GULP_DEBUG) {
      console.log('+ ' + arguments[0]);
    }
    return exec.apply(null, arguments);
  }

  function resTaskName(resourceName) {
    return 'build-' + lang + '-' + resourceName;
  }

  /**
   * Clean work area for target repo
   */
  Object.keys(languages).forEach(function(lang) {
    gulp.task('clean-' + lang, function() {
      fs.removeSync(paths.dist(lang));
    });
  });

  /**
   * Checkout target repo, for build and deploy
   */
  gulp.task('checkout-' + lang, ['clean-', lang], function(cb) {

    cloneRepo(cb);

    function cloneRepo(cb) {
      fs.removeSync(repoRoot);
      var url = (token !== null)
          ? util.format('https://github.com/%s', config.repo)
          : util.format('git@github.com:%s', config.repo);
      echoAndExec(
          util.format('git clone %s %s', url, repoRoot),
          switchToBranch);
    }

    function switchToBranch(err, stdout, stderr) {
      if (err) { cb(err); return; }
      var branch = config.branch;
      echoAndExec(
          util.format('git checkout --track -b %s origin/%s', branch, branch),
          {cwd: repoRoot},
          done);
    }

    function done(err, stdout, stderr) {
      if (err) { cb(err); return; }
      cb();
    }
  });

  /**
   * Build rules, per resource.
   */
  resourceNames.forEach(function(resourceName) {
    gulp.task(resTaskName(resourceName), function() {
      // Support templates existing either locally or in target repo.
      var templatePath = config.templatePath ?
          (paths.repo(lang) + '/' + config.templatePath):
          ('src/templates/' + lang);
      var resourceTemplateInfo = require(templatePath).resource;

      // Find the template info for resources
      var resource = resource.load(resourceName);
      var templateHelpers = helpers(lang);
      return gulp.src(templatePath + '/' + resourceTemplateInfo.template)
          .pipe(
              template(resource, {
                imports: templateHelpers,
                variable: 'resource'
              }))
          .pipe(
              rename(resourceTemplateInfo.filename(resource, templateHelpers)))
          .pipe(
              gulp.dest(paths.dist(lang)));
    });
  });
  gulp.task(
      'build-' + lang,
      ['checkout-' + lang].concat(resourceNames.map(resTaskName)));

  /**
   * Deploy
   */
  gulp.task('deploy-' + lang, ['build-' + lang], function(cb) {
    var version;

    // We depend on the build step which checks out the repo, so we start by
    // setting our credentials so we can push to it.
    configureCredentials();

    // TODO: use some kind of promisify libraries to clean all this async code

    function configureCredentials(err, stdout, stderr) {
      if (err) { cb(err); return; }
      if (token !== null) {
        echoAndExec(
            'git config credential.helper "store --file=.git/credentials"',
            {cwd: repoRoot},
            writeCredentials);
      } else {
        copyToRepo();
      }
    }

    function writeCredentials(err, stdout, stderr) {
      if (err) { cb(err); return; }
      fs.writeFileSync(
          util.format('%s/.git/credentials', repoRoot),
          util.format('https://%s:@github.com', token));
      copyToRepo();
    }

    function copyToRepo(err, stdout, stderr) {
      if (err) { cb(err); return; }
      fs.mkdirpSync(outputPath);
      fs.copy(paths.dist(lang), outputPath, function(err) {
        version = readPackage().version;
        config.updatePackage(version, gitAdd);
      });
    }

    function gitAdd(err) {
      if (err) { cb(err); return; }
      echoAndExec('git add ' + paths.repoOutputRelative(lang), {cwd: repoRoot}, gitCommit);
    }

    function gitCommit(err) {
      if (err) { cb(err); return; }
      echoAndExec(util.format('git commit --allow-empty -a -m "Deploy from asana-api-meta v%s"', version), {cwd: repoRoot}, gitTag);
    }

    function gitTag(err, stdout, stderr) {
      if (err) { cb(err); return; }
      echoAndExec(util.format('git tag -f "v%s"', version), {cwd: repoRoot}, gitPush);
    }

    function gitPush(err) {
      if (err) { cb(err); return; }
      echoAndExec(
          util.format('git push --tags origin %s', config.branch),
          {cwd: repoRoot},
          done);
    }

    function done(err, stdout, stderr) {
      if (err) { cb(err); return; }
      cb();
    }
  });
});

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp bump-patch     # makes v0.1.0 → v0.1.1
 *     gulp bump-feature   # makes v0.1.1 → v0.2.0
 *     gulp bump-release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */
function bumpVersion(importance) {
  return gulp.src(['./package.json'])
      .pipe(bump({type: importance}))
      .pipe(gulp.dest('./'))
      .pipe(git.commit('bump package version'))
      .pipe(tagVersion());
}
gulp.task('bump-patch', ['ensure-git-clean'], function() {
  return bumpVersion('patch');
});
gulp.task('bump-feature', ['ensure-git-clean'], function() {
  return bumpVersion('minor');
});
gulp.task('bump-release', ['ensure-git-clean'], function() {
  return bumpVersion('major');
});

/**
 * Ensure that the git working directory is clean.
 */
gulp.task('ensure-git-clean', function() {
  git.status(function(err, out) {
    if (err) { throw err; }
    if (!/working directory clean/.exec(out)) {
      throw new Error('Git working directory not clean, will not bump version');
    }
  });
});

/**
 * Tests the code with mocha.
 */
gulp.task('test', function(callback) {
  gulp.src(test)
      .pipe(mocha({
        reporter: process.env.TRAVIS ? 'spec' : 'nyan'
      }));
});

<commit_msg>fix some problems<commit_after>var bump = require('gulp-bump');
var exec = require('child_process').exec;
var fs = require('fs-extra');
var git = require('gulp-git');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var tagVersion = require('gulp-tag-version');
var template = require('gulp-template');
var util = require('util');
var yaml = require('js-yaml');
var resource = require('./src/resource');
var helpers = require('./src/helpers');

/**
 * Paths
 */
var test = 'test/**/*';

/**
 * Environment
 */
var languages = {
  js: {
    repo: 'Asana/node-asana',
    branch: 'api-meta-incoming',
    templatePath: 'src/templates',
    outputPath: 'lib/resources/gen',
    updatePackage: function(version, cb) {
      var repoRoot = paths.repo('js');
      var destPackage = readPackage(repoRoot + '/package.json');
      destPackage.version = version;
      writePackage(repoRoot + '/package.json', destPackage);
      exec('git add package.json', {cwd: repoRoot}, cb);
    }
  }
};

var paths = {
  dist: function(lang) {
    return 'dist/' + lang;
  },
  repo: function(lang) {
    return 'dist/git/' + lang;
  },
  repoOutput: function(lang) {
    return paths.repo(lang) + '/' + paths.repoOutputRelative(lang);
  },
  repoOutputRelative: function(lang) {
    return languages[lang].outputPath;
  }
};

function readPackage(filename) {
  return fs.readJSONSync(filename || 'package.json');
}

function writePackage(filename, data) {
  return fs.writeJSONSync(filename || 'package.json', data);
}

/**
 * High-level tasks
 */

// Build all languages
gulp.task('build', ['test'].concat(Object.keys(languages).map(function(lang) {
  return 'build-' + lang;
})));

// Deploy languages
gulp.task('deploy', ['ensure-git-clean', 'build'].concat(Object.keys(languages).map(function(lang) {
  return 'deploy-' + lang;
})));

/**
 * Generate build and deploy rules for each language
 */
var resourceNames = resource.names();
Object.keys(languages).forEach(function(lang) {
  var config = languages[lang];
  var outputPath = paths.repoOutput(lang);
  var repoRoot = paths.repo(lang);
  var token = process.env.ASANA_GITHUB_TOKEN || null;

  function echoAndExec() {
    if (process.env.GULP_DEBUG) {
      console.log('+ ' + arguments[0]);
    }
    return exec.apply(null, arguments);
  }

  function resTaskName(resourceName) {
    return 'build-' + lang + '-' + resourceName;
  }

  /**
   * Clean work area for target repo
   */
  Object.keys(languages).forEach(function(lang) {
    gulp.task('clean-' + lang, function() {
      fs.removeSync(paths.dist(lang));
    });
  });

  /**
   * Checkout target repo, for build and deploy
   */
  gulp.task('checkout-' + lang, ['clean-' + lang], function(cb) {

    cloneRepo(cb);

    function cloneRepo(cb) {
      fs.removeSync(repoRoot);
      var url = (token !== null)
          ? util.format('https://github.com/%s', config.repo)
          : util.format('git@github.com:%s', config.repo);
      echoAndExec(
          util.format('git clone %s %s', url, repoRoot),
          switchToBranch);
    }

    function switchToBranch(err, stdout, stderr) {
      if (err) { cb(err); return; }
      var branch = config.branch;
      echoAndExec(
          util.format('git checkout --track -b %s origin/%s', branch, branch),
          {cwd: repoRoot},
          done);
    }

    function done(err, stdout, stderr) {
      if (err) { cb(err); return; }
      cb();
    }
  });

  /**
   * Build rules, per resource.
   */
  resourceNames.forEach(function(resourceName) {
    gulp.task(resTaskName(resourceName), ['checkout-' + lang], function() {
      // Support templates existing either locally or in target repo.
      var templatePath = config.templatePath ?
          (paths.repo(lang) + '/' + config.templatePath):
          ('src/templates/' + lang);
      var resourceTemplateInfo = require('./' + templatePath).resource;

      // Find the template info for resources
      var resourceInstance = resource.load(resourceName);
      var templateHelpers = helpers(lang);
      return gulp.src(templatePath + '/' + resourceTemplateInfo.template)
          .pipe(
              template(resourceInstance, {
                imports: templateHelpers,
                variable: 'resource'
              }))
          .pipe(
              rename(resourceTemplateInfo.filename(resourceInstance, templateHelpers)))
          .pipe(
              gulp.dest(paths.dist(lang)));
    });
  });
  gulp.task(
      'build-' + lang,
      resourceNames.map(resTaskName));

  /**
   * Deploy
   */
  gulp.task('deploy-' + lang, ['build-' + lang], function(cb) {
    var version;

    // We depend on the build step which checks out the repo, so we start by
    // setting our credentials so we can push to it.
    configureCredentials();

    // TODO: use some kind of promisify libraries to clean all this async code

    function configureCredentials(err, stdout, stderr) {
      if (err) { cb(err); return; }
      if (token !== null) {
        echoAndExec(
            'git config credential.helper "store --file=.git/credentials"',
            {cwd: repoRoot},
            writeCredentials);
      } else {
        copyToRepo();
      }
    }

    function writeCredentials(err, stdout, stderr) {
      if (err) { cb(err); return; }
      fs.writeFileSync(
          util.format('%s/.git/credentials', repoRoot),
          util.format('https://%s:@github.com', token));
      copyToRepo();
    }

    function copyToRepo(err, stdout, stderr) {
      if (err) { cb(err); return; }
      fs.mkdirpSync(outputPath);
      fs.copy(paths.dist(lang), outputPath, function(err) {
        version = readPackage().version;
        config.updatePackage(version, gitAdd);
      });
    }

    function gitAdd(err) {
      if (err) { cb(err); return; }
      echoAndExec('git add ' + paths.repoOutputRelative(lang), {cwd: repoRoot}, gitCommit);
    }

    function gitCommit(err) {
      if (err) { cb(err); return; }
      echoAndExec(util.format('git commit --allow-empty -a -m "Deploy from asana-api-meta v%s"', version), {cwd: repoRoot}, gitTag);
    }

    function gitTag(err, stdout, stderr) {
      if (err) { cb(err); return; }
      echoAndExec(util.format('git tag -f "v%s"', version), {cwd: repoRoot}, gitPush);
    }

    function gitPush(err) {
      if (err) { cb(err); return; }
      echoAndExec(
          util.format('git push --tags origin %s', config.branch),
          {cwd: repoRoot},
          done);
    }

    function done(err, stdout, stderr) {
      if (err) { cb(err); return; }
      cb();
    }
  });
});

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp bump-patch     # makes v0.1.0 → v0.1.1
 *     gulp bump-feature   # makes v0.1.1 → v0.2.0
 *     gulp bump-release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */
function bumpVersion(importance) {
  return gulp.src(['./package.json'])
      .pipe(bump({type: importance}))
      .pipe(gulp.dest('./'))
      .pipe(git.commit('bump package version'))
      .pipe(tagVersion());
}
gulp.task('bump-patch', ['ensure-git-clean'], function() {
  return bumpVersion('patch');
});
gulp.task('bump-feature', ['ensure-git-clean'], function() {
  return bumpVersion('minor');
});
gulp.task('bump-release', ['ensure-git-clean'], function() {
  return bumpVersion('major');
});

/**
 * Ensure that the git working directory is clean.
 */
gulp.task('ensure-git-clean', function() {
  git.status(function(err, out) {
    if (err) { throw err; }
    if (!/working directory clean/.exec(out)) {
      throw new Error('Git working directory not clean, will not bump version');
    }
  });
});

/**
 * Tests the code with mocha.
 */
gulp.task('test', function(callback) {
  gulp.src(test)
      .pipe(mocha({
        reporter: process.env.TRAVIS ? 'spec' : 'nyan'
      }));
});

<|endoftext|>


<commit_before>//require('nw.gui').Window.get().showDevTools();
(function () {

    var Mocha = require('mocha');
    var chai = require('chai');
    var path = require('path');
    var gui = require('nw.gui');
    var istanbul = require('istanbul');

    var fs = require('fs'),
        q = require('q');
    var path = require('path');
    //Get the command line params
    var port = gui.App.argv[0];

    //Switch to dir where the tests are executed
    process.chdir('../../../');

    startClient(port).then(function (data) {
        var client = data.obj;
        var test = data.testData;

        logErrHandler(client);

        var mocha = new Mocha({
            ui: 'bdd',
            reporter: 'xunit',
            reporterOptions: {
                output: path.resolve(path.join(test.outputFolder, test.outputFileName))
            }
        });

        //Make mocha and chai available globally
        window.mocha = mocha;
        window.expect = chai.expect;
        window.assert = chai.assert;

        // pass the browser context
        mocha.suite.emit('pre-require', window, null, mocha);

        if (test.files) {
            test.files.forEach(function (f) {
                appendScript(f);
            })
        }

        if (test.mock) {
            test.mock.forEach(function (f) {
                appendScript(f);
            })
        }

        if (test.deps) {
            test.deps.forEach(function (f) {
                appendScript(f);
            })
        }
        if (test.src) {
            var codeToInstrument = "";
            var instrumenter = new istanbul.Instrumenter({});
            test.src.forEach(function (file) {
                codeToInstrument += fs.readFileSync(file, 'utf8');
            });
            var basename = "";
            basename = test.src[0];
            var cov = instrumenter.instrumentSync(codeToInstrument, basename);
            try {
                appendScript(cov, true);
            } catch (exp) {
                //IGNORE- SCRIPT EXEC FAILED
            }
        }
        if (test.test) {
            test.test.forEach(function (f) {
                appendScript(f);
            })

            mocha.run(function (failures) {

                fs.writeFileSync('temp.json', JSON.stringify(window.__coverage__));
                client.write(JSON.stringify({
                    fail: failures
                }));

                client.destroy();

                require('nw.gui').Window.get().close(); //Close the app
            });
        } else {

            if (window.__coverage__)
                fs.writeFileSync('temp.json', JSON.stringify(window.__coverage__));
            client.write(JSON.stringify({
                fail: 0
            }));
            client.destroy();
            process.exit(0) //Close the app
        }

    });

    function startClient(port) {
        var defered = q.defer();
        var net = require('net');

        var HOST = '127.0.0.1';
        var PORT = port;

        var client = new net.Socket();
        client.connect(PORT, HOST, function () {
            console.log("connected with port");
        });
        client.on('data', function (data) {
            defered.resolve({
                obj: client,
                testData: JSON.parse(data)
            });
        })

        return defered.promise;
    };

    function appendScript(include, isInstrumented) {
        if (isInstrumented) {
            $('head').append('<script>' + include + '</script>');
        } else {
            $('head').append('<script src="' + include + '"></script>');
        }
    }

    function logErrHandler(client) {
        //Pass the console logs to runner
        console.log = function (str) {
            client.write(JSON.stringify({
                log: str
            }));
        };

        //Watch for exceptions and handle
        process.on('uncaughtException', function (err) {
            console.log('Uncaught Exception: ' + err);
            process.exit(-1);
        });

        window.on('error', function (err) {
            console.log('Uncaught error: ' + err);
            process.exit(-1);
        });

    }

})();
<commit_msg>Commented - Client side error handling<commit_after>//require('nw.gui').Window.get().showDevTools();
(function () {

    var Mocha = require('mocha');
    var chai = require('chai');
    var path = require('path');
    var gui = require('nw.gui');
    var istanbul = require('istanbul');

    var fs = require('fs'),
        q = require('q');
    var path = require('path');
    //Get the command line params
    var port = gui.App.argv[0];

    //Switch to dir where the tests are executed
    process.chdir('../../../');

    startClient(port).then(function (data) {
        var client = data.obj;
        var test = data.testData;

        //logErrHandler(client);

        var mocha = new Mocha({
            ui: 'bdd',
            reporter: 'xunit',
            reporterOptions: {
                output: path.resolve(path.join(test.outputFolder, test.outputFileName))
            }
        });

        //Make mocha and chai available globally
        window.mocha = mocha;
        window.expect = chai.expect;
        window.assert = chai.assert;

        // pass the browser context
        mocha.suite.emit('pre-require', window, null, mocha);

        if (test.files) {
            test.files.forEach(function (f) {
                appendScript(f);
            })
        }

        if (test.mock) {
            test.mock.forEach(function (f) {
                appendScript(f);
            })
        }

        if (test.deps) {
            test.deps.forEach(function (f) {
                appendScript(f);
            })
        }
        if (test.src) {
            var codeToInstrument = "";
            var instrumenter = new istanbul.Instrumenter({});
            test.src.forEach(function (file) {
                codeToInstrument += fs.readFileSync(file, 'utf8');
            });
            var basename = "";
            basename = test.src[0];
            var cov = instrumenter.instrumentSync(codeToInstrument, basename);
            try {
                appendScript(cov, true);
            } catch (exp) {
                //IGNORE- SCRIPT EXEC FAILED
            }
        }
        if (test.test) {
            test.test.forEach(function (f) {
                appendScript(f);
            })

            mocha.run(function (failures) {

                fs.writeFileSync('temp.json', JSON.stringify(window.__coverage__));
                client.write(JSON.stringify({
                    fail: failures
                }));

                client.destroy();

                require('nw.gui').Window.get().close(); //Close the app
            });
        } else {

            if (window.__coverage__)
                fs.writeFileSync('temp.json', JSON.stringify(window.__coverage__));
            client.write(JSON.stringify({
                fail: 0
            }));
            client.destroy();
            process.exit(0) //Close the app
        }

    });

    function startClient(port) {
        var defered = q.defer();
        var net = require('net');

        var HOST = '127.0.0.1';
        var PORT = port;

        var client = new net.Socket();
        client.connect(PORT, HOST, function () {
            console.log("connected with port");
        });
        client.on('data', function (data) {
            defered.resolve({
                obj: client,
                testData: JSON.parse(data)
            });
        })

        return defered.promise;
    };

    function appendScript(include, isInstrumented) {
        if (isInstrumented) {
            $('head').append('<script>' + include + '</script>');
        } else {
            $('head').append('<script src="' + include + '"></script>');
        }
    }

    function logErrHandler(client) {
        //Pass the console logs to runner
        console.log = function (str) {
            client.write(JSON.stringify({
                log: str
            }));
        };

        //Watch for exceptions and handle
        process.on('uncaughtException', function (err) {
            console.log('Uncaught Exception: ' + err);
            process.exit(-1);
        });

        window.on('error', function (err) {
            console.log('Uncaught error: ' + err);
            process.exit(-1);
        });

    }

})();
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var MongoClient = require('mongodb').MongoClient, restify = require('restify'), assert = require('assert');//, ObjectId = require('mongodb').ObjectID;

    //Needs to impliment aggregate stuff (https://docs.mongodb.com/manual/reference/operator/aggregation/)
    //Need to impliment mapreduce stuff
    //Need to impliment projection stuff

    //Good source for operators:
    // https://docs.mongodb.com/manual/reference/operator/
    //I am making sure to not allow any operators that can change the documents
    // this is to ensure that this remains a query only server

    var acceptedRegex = "", sanatize, j, grabDbName, grabDocument,
            accepted$ = [
        "all", "and", "bitsAllClear", "bitsAllSet", "bitsAnyClear",
        "bitsAnySet", "collStats", "comment", "elemMatch",
        "eq", "exists", "explain", "geoIntersects", "geoWithin", "gt",
        "gte", "hint", "in", "limit", "lte", "match", "max", "maxScan",
        "maxTimeMS", "meta", "min", "mod", "natural", "ne", "near",
        "nearShpere", "nin", "nor", "not", "or", "orderby", "query",
        "regex", "returnKey", "showDiskLoc", "size", "skip", "slice",
        "snapshot", "text", "type", "where"
    ];

    for (j = 0; j < accepted$.length; j += 1) {
        acceptedRegex += "^\\$" + accepted$[j] + "$|";
    }
    acceptedRegex = acceptedRegex.replace(/\|$/, "");
    acceptedRegex = new RegExp(acceptedRegex, 'i');

    //define the query sanatize function
    //sanatize the query
    sanatize = function (query) {
        var keys, i;
        if (typeof query === "object") {
            keys = Object.keys(query);
            for (i = 0; i < keys.length; i += 1) {
                if (keys[i].match(/^\s*\$/)) {
                    //straight up kill it if it is not an accepted type
                    if (!keys[i].match(acceptedRegex)) {
                        delete query[keys[i]];
                    }
                } else if (typeof query[keys[i]] === "object") {
                    query[keys[i]] = sanatize(query[keys[i]]);
                }
            }
        } else {
            //If it is not an object then just query it all
            // should probably generate an error message
            query = {};
        }
        return query;
    };

    grabDbName = function (request, response) {
        var myDbName = request.params.db_name, query, fields, sort,
                collectionName = request.params.collection_name, url;

        //Deal with the objects
        // myDbName = myDbName || 'kinome';
        url = 'mongodb://localhost:27017/' + myDbName;
        console.log('db name:', myDbName);
        request.query.find = request.query.find || "{}";
        request.query.fields = request.query.fields || "-1";
        request.query.sort = request.query.sort || "[]";

        request.query.find = decodeURIComponent(request.query.find);
        request.query.fields = decodeURIComponent(request.query.fields);
        request.query.sort = decodeURIComponent(request.query.sort);

        //Objectify them
        query = JSON.parse(request.query.find);
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);
        sort = JSON.parse(request.query.sort);

        //if there is a sort option, sanatize it
        if (sort.length > 0) {
            sanatize(sort);
        }

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var limit = request.query.limit * 1 || 9000000; //9 mil more than enough
            var skip = request.query.skip * 1 || 0;
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields, sort);
            if (fields === -1) {
                spec = collection.find(query, {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find(query, sanatize(fields), {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.sort(sort).toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
               // console.log("Found the following records", docs);
                response.send(docs);
            });
        });
    };

    grabDocument = function (request, response) {
        var myDbName = request.params.db_name, fields,
                collectionName = request.params.collection_name,
                query = {id: decodeURIComponent(request.params.doc_id)}, url;

        //Deal with the objects
        // myDbName = myDbName || 'kinome';
        url = 'mongodb://localhost:27017/' + myDbName;
        request.query.fields = request.query.fields || "-1";
        request.query.fields = decodeURIComponent(request.query.fields);

        //Objectify them
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, myDbName, collectionName);
            if (fields === -1) {
                spec = collection.find({"_id": query.id}, {
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find({"_id": query.id}, sanatize(fields), {
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
                //console.log("Found the following records", docs);
                //Only return the first object
                if (docs[0]) {
                    response.send(docs[0]);
                } else {
                    response.send(undefined);
                }
            });
        });
    };

    //sets up the server stuff
    var server1 = restify.createServer({
        accept: ['application/json', 'image/tif', 'image/png', 'text/plain']
    });
    server1.use(restify.queryParser());
    server1.use(restify.CORS({}));

    server1.get(/\/img\/kinome\/?.*/, restify.serveStatic({
        directory: "/var/www"
    }));
    server1.get(/\/file\/?.*/, restify.serveStatic({
        directory: "/var/www/global_files"
    }));

    //http://138.26.31.155:8000/img/kinome/631308613_W1_F1_T200_P154_I1313_A30.tif

    /*the following is for the internal db (accesible as a registered UAB user only)*/
    server1.get("/db/:db_name/:collection_name", grabDbName);
    server1.get("/db/:db_name/:collection_name/:doc_id", grabDocument);
    server1.listen(8000, function () {
        console.log('%s listening at %s', server1.name, server1.url);
    });

    // var server2 = restify.createServer({
    //     accept: ['application/json', 'image/tif', 'image/png']
    // });
    // server2.use(restify.queryParser());
    // server2.use(restify.CORS({}));

    // server2.get(/\/img\/kinome\/?.*/, restify.serveStatic({
    //     directory: "./server_imgs"
    // }));

    // /*The following is for the external db*/
    // server2.get("/1.0.0/:collection_name", grabDbName);
    // server2.get("/1.0.0/:collection_name/:doc_id", grabDocument);
    // server2.listen(8080, function () {
    //     console.log('%s listening at %s', server2.name, server2.url);
    // });

}());
<commit_msg>take 2 at doc folder<commit_after>(function () {
    'use strict';

    var MongoClient = require('mongodb').MongoClient, restify = require('restify'), assert = require('assert');//, ObjectId = require('mongodb').ObjectID;

    //Needs to impliment aggregate stuff (https://docs.mongodb.com/manual/reference/operator/aggregation/)
    //Need to impliment mapreduce stuff
    //Need to impliment projection stuff

    //Good source for operators:
    // https://docs.mongodb.com/manual/reference/operator/
    //I am making sure to not allow any operators that can change the documents
    // this is to ensure that this remains a query only server

    var acceptedRegex = "", sanatize, j, grabDbName, grabDocument,
            accepted$ = [
        "all", "and", "bitsAllClear", "bitsAllSet", "bitsAnyClear",
        "bitsAnySet", "collStats", "comment", "elemMatch",
        "eq", "exists", "explain", "geoIntersects", "geoWithin", "gt",
        "gte", "hint", "in", "limit", "lte", "match", "max", "maxScan",
        "maxTimeMS", "meta", "min", "mod", "natural", "ne", "near",
        "nearShpere", "nin", "nor", "not", "or", "orderby", "query",
        "regex", "returnKey", "showDiskLoc", "size", "skip", "slice",
        "snapshot", "text", "type", "where"
    ];

    for (j = 0; j < accepted$.length; j += 1) {
        acceptedRegex += "^\\$" + accepted$[j] + "$|";
    }
    acceptedRegex = acceptedRegex.replace(/\|$/, "");
    acceptedRegex = new RegExp(acceptedRegex, 'i');

    //define the query sanatize function
    //sanatize the query
    sanatize = function (query) {
        var keys, i;
        if (typeof query === "object") {
            keys = Object.keys(query);
            for (i = 0; i < keys.length; i += 1) {
                if (keys[i].match(/^\s*\$/)) {
                    //straight up kill it if it is not an accepted type
                    if (!keys[i].match(acceptedRegex)) {
                        delete query[keys[i]];
                    }
                } else if (typeof query[keys[i]] === "object") {
                    query[keys[i]] = sanatize(query[keys[i]]);
                }
            }
        } else {
            //If it is not an object then just query it all
            // should probably generate an error message
            query = {};
        }
        return query;
    };

    grabDbName = function (request, response) {
        var myDbName = request.params.db_name, query, fields, sort,
                collectionName = request.params.collection_name, url;

        //Deal with the objects
        // myDbName = myDbName || 'kinome';
        url = 'mongodb://localhost:27017/' + myDbName;
        console.log('db name:', myDbName);
        request.query.find = request.query.find || "{}";
        request.query.fields = request.query.fields || "-1";
        request.query.sort = request.query.sort || "[]";

        request.query.find = decodeURIComponent(request.query.find);
        request.query.fields = decodeURIComponent(request.query.fields);
        request.query.sort = decodeURIComponent(request.query.sort);

        //Objectify them
        query = JSON.parse(request.query.find);
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);
        sort = JSON.parse(request.query.sort);

        //if there is a sort option, sanatize it
        if (sort.length > 0) {
            sanatize(sort);
        }

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var limit = request.query.limit * 1 || 9000000; //9 mil more than enough
            var skip = request.query.skip * 1 || 0;
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields, sort);
            if (fields === -1) {
                spec = collection.find(query, {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find(query, sanatize(fields), {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.sort(sort).toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
               // console.log("Found the following records", docs);
                response.send(docs);
            });
        });
    };

    grabDocument = function (request, response) {
        var myDbName = request.params.db_name, fields,
                collectionName = request.params.collection_name,
                query = {id: decodeURIComponent(request.params.doc_id)}, url;

        //Deal with the objects
        // myDbName = myDbName || 'kinome';
        url = 'mongodb://localhost:27017/' + myDbName;
        request.query.fields = request.query.fields || "-1";
        request.query.fields = decodeURIComponent(request.query.fields);

        //Objectify them
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, myDbName, collectionName);
            if (fields === -1) {
                spec = collection.find({"_id": query.id}, {
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find({"_id": query.id}, sanatize(fields), {
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
                //console.log("Found the following records", docs);
                //Only return the first object
                if (docs[0]) {
                    response.send(docs[0]);
                } else {
                    response.send(undefined);
                }
            });
        });
    };

    //sets up the server stuff
    var server1 = restify.createServer({
        accept: ['application/json', 'image/tif', 'image/png', 'text/plain']
    });
    server1.use(restify.queryParser());
    server1.use(restify.CORS({}));

    server1.get(/\/img\/kinome\/?.*/, restify.serveStatic({
        directory: "/var/www"
    }));
    server1.get(/\/file\/affymetrix\/?.*/, restify.serveStatic({
        directory: "/var/www/global_files"
    }));

    //http://138.26.31.155:8000/img/kinome/631308613_W1_F1_T200_P154_I1313_A30.tif

    /*the following is for the internal db (accesible as a registered UAB user only)*/
    server1.get("/db/:db_name/:collection_name", grabDbName);
    server1.get("/db/:db_name/:collection_name/:doc_id", grabDocument);
    server1.listen(8000, function () {
        console.log('%s listening at %s', server1.name, server1.url);
    });

    // var server2 = restify.createServer({
    //     accept: ['application/json', 'image/tif', 'image/png']
    // });
    // server2.use(restify.queryParser());
    // server2.use(restify.CORS({}));

    // server2.get(/\/img\/kinome\/?.*/, restify.serveStatic({
    //     directory: "./server_imgs"
    // }));

    // /*The following is for the external db*/
    // server2.get("/1.0.0/:collection_name", grabDbName);
    // server2.get("/1.0.0/:collection_name/:doc_id", grabDocument);
    // server2.listen(8080, function () {
    //     console.log('%s listening at %s', server2.name, server2.url);
    // });

}());
<|endoftext|>


<commit_before>// jshint node: true
'use strict';

// #####################################################################################################################
// #IMPORTS#
var autoprefixer = require('gulp-autoprefixer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var minifyCss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var KarmaServer = require('karma').Server;
var spawn = require('child_process').spawn;

var argv = require('minimist')(process.argv.slice(2));

// #####################################################################################################################
// #SETTINGS#
var options = {
    debug: argv.debug
};
var PROJECT_ROOT = __dirname + '/cms/static/cms';
var PROJECT_PATH = {
    js: PROJECT_ROOT + '/js',
    sass: PROJECT_ROOT + '/sass',
    css: PROJECT_ROOT + '/css',
    icons: PROJECT_ROOT + '/fonts',
    tests: __dirname + '/cms/tests/frontend'
};

var PROJECT_PATTERNS = {
    js: [
        PROJECT_PATH.js + '/modules/*.js',
        PROJECT_PATH.js + '/widgets/*.js',
        PROJECT_PATH.js + '/gulpfile.js',
        PROJECT_PATH.tests + '/**/*.js',
        '!' + PROJECT_PATH.tests + '/unit/helpers/**/*.js',
        '!' + PROJECT_PATH.tests + '/coverage/**/*.js',
        '!' + PROJECT_PATH.js + '/modules/jquery.ui.*.js',
        '!' + PROJECT_PATH.js + '/dist/*.js'
    ],
    sass: [
        PROJECT_PATH.sass + '/**/*.{scss,sass}'
    ],
    icons: [
        PROJECT_PATH.icons + '/src/*.svg'
    ]
};

/*
 * Object keys are filenames of bundles that will be compiled
 * from array of paths that are the value.
 */
var JS_BUNDLES = {
    'bundle.admin.base.min.js': [
        PROJECT_PATH.js + '/polyfills/bind.js',
        PROJECT_PATH.js + '/libs/jquery.min.js',
        PROJECT_PATH.js + '/libs/pep.js',
        PROJECT_PATH.js + '/libs/class.min.js',
        PROJECT_PATH.js + '/modules/cms.base.js'
    ],
    'bundle.admin.changeform.min.js': [
        PROJECT_PATH.js + '/modules/cms.changeform.js'
    ],
    'bundle.admin.changelist.min.js': [
        PROJECT_PATH.js + '/modules/jquery.ui.custom.js',
        PROJECT_PATH.js + '/modules/cms.changelist.js',
        PROJECT_PATH.js + '/jstree/_lib/_all.js',
        PROJECT_PATH.js + '/jstree/tree_component.js'
    ],
    'bundle.toolbar.min.js': [
        PROJECT_PATH.js + '/polyfills/bind.js',
        PROJECT_PATH.js + '/libs/jquery.min.js',
        PROJECT_PATH.js + '/libs/class.min.js',
        PROJECT_PATH.js + '/libs/pep.js',
        PROJECT_PATH.js + '/modules/jquery.ui.custom.js',
        PROJECT_PATH.js + '/modules/jquery.ui.touchpunch.js',
        PROJECT_PATH.js + '/modules/jquery.ui.nestedsortable.js',
        PROJECT_PATH.js + '/modules/cms.base.js',
        PROJECT_PATH.js + '/modules/jquery.transition.js',
        PROJECT_PATH.js + '/modules/cms.messages.js',
        PROJECT_PATH.js + '/modules/cms.modal.js',
        PROJECT_PATH.js + '/modules/cms.sideframe.js',
        PROJECT_PATH.js + '/modules/cms.clipboard.js',
        PROJECT_PATH.js + '/modules/cms.plugins.js',
        PROJECT_PATH.js + '/modules/cms.structureboard.js',
        PROJECT_PATH.js + '/modules/cms.navigation.js',
        PROJECT_PATH.js + '/modules/cms.toolbar.js',
        PROJECT_PATH.js + '/modules/cms.tooltip.js'
    ]
};

// #####################################################################################################################
// #TASKS#
gulp.task('sass', function () {
    gulp.src(PROJECT_PATTERNS.sass)
        .pipe(gulpif(options.debug, sourcemaps.init()))
        .pipe(sass())
        .on('error', function (error) {
            gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.messageFormatted));
        })
        .pipe(autoprefixer({
            browsers: ['last 3 versions'],
            cascade: false
        }))
        .pipe(minifyCss({
            rebase: false
        }))
        .pipe(gulpif(options.debug, sourcemaps.write()))
        .pipe(gulp.dest(PROJECT_PATH.css));
});

gulp.task('icons', function () {
    gulp.src(PROJECT_PATTERNS.icons)
    .pipe(iconfontCss({
        fontName: 'django-cms-iconfont',
        fontPath: '../fonts/',
        path: PROJECT_PATH.sass + '/libs/_iconfont.scss',
        targetPath: '../sass/components/_iconography.scss'
    }))
    .pipe(iconfont({
        fontName: 'django-cms-iconfont',
        normalize: true
    }))
    .on('glyphs', function (glyphs, options) {
        gutil.log.bind(glyphs, options);
    })
    .pipe(gulp.dest(PROJECT_PATH.icons));
});

gulp.task('lint', ['lint:javascript']);
gulp.task('lint:javascript', function () {
    // DOCS: http://jshint.com/docs/
    return gulp.src(PROJECT_PATTERNS.js)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('tests', ['tests:unit', 'tests:integration']);

// gulp tests:unit --tests=cms.base,cms.modal
gulp.task('tests:unit', function (done) {
    var server = new KarmaServer({
        configFile: PROJECT_PATH.tests + '/karma.conf.js',
        singleRun: true
    }, done);
    server.start();
});

gulp.task('tests:unit:watch', function () {
    var server = new KarmaServer({
        configFile: PROJECT_PATH.tests + '/karma.conf.js'
    });
    server.start();
});

// gulp tests:integration --tests=loginAdmin,toolbar
gulp.task('tests:integration', function (done) {
    process.env.PHANTOMJS_EXECUTABLE = './node_modules/.bin/phantomjs';

    var files = [
        'loginAdmin',
        'toolbar',
        'addFirstPage',
        'editMode',
        'sideframe',
        'createContent',
        'users',
        'newPage',
        'switchLanguage',
        'editContent',
        'editContentTools',
        'publish',
        'logout',
        'loginToolbar'
    ];
    var pre = ['setup'];

    if (argv && argv.tests) {
        files = argv.tests.split(',');
        gutil.log('Running tests for ' + files.join(', '));
    }

    var tests = pre.concat(files).map(function (file) {
        return PROJECT_PATH.tests + '/integration/' + file + '.js';
    });

    var casperChild = spawn('./node_modules/.bin/casperjs', ['test', '--web-security=no'].concat(tests));

    casperChild.stdout.on('data', function (data) {
        gutil.log('CasperJS:', data.toString().slice(0, -1));
    });

    casperChild.on('close', function (code) {
        done(code);
    });
});

Object.keys(JS_BUNDLES).forEach(function (bundleName) {
    var bundleFiles = JS_BUNDLES[bundleName];

    gulp.task('bundle:' + bundleName, function () {
        return gulp.src(bundleFiles)
            .pipe(gulpif(options.debug, sourcemaps.init()))
            .pipe(gulpif(!options.debug, uglify({
                preserveComments: 'some'
            })))
            .pipe(concat(bundleName, {
                newLine: '\n'
            }))
            .pipe(gulpif(options.debug, sourcemaps.write()))
            .pipe(gulp.dest(PROJECT_PATH.js + '/dist/'));
    });
});
gulp.task('bundle', Object.keys(JS_BUNDLES).map(function (bundleName) {
    return 'bundle:' + bundleName;
}));

gulp.task('watch', function () {
    gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
    gulp.watch(PROJECT_PATTERNS.js, ['lint']);
    Object.keys(JS_BUNDLES).forEach(function (bundleName) {
        var bundleFiles = JS_BUNDLES[bundleName];
        gulp.watch(bundleFiles, ['bundle:' + bundleName]);
    });
});

gulp.task('default', ['sass', 'lint', 'bundle', 'watch']);
<commit_msg>oops forgot this one<commit_after>// jshint node: true
'use strict';

// #####################################################################################################################
// #IMPORTS#
var autoprefixer = require('gulp-autoprefixer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var minifyCss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var KarmaServer = require('karma').Server;
var spawn = require('child_process').spawn;

var argv = require('minimist')(process.argv.slice(2));

// #####################################################################################################################
// #SETTINGS#
var options = {
    debug: argv.debug
};
var PROJECT_ROOT = __dirname + '/cms/static/cms';
var PROJECT_PATH = {
    js: PROJECT_ROOT + '/js',
    sass: PROJECT_ROOT + '/sass',
    css: PROJECT_ROOT + '/css',
    icons: PROJECT_ROOT + '/fonts',
    tests: __dirname + '/cms/tests/frontend'
};

var PROJECT_PATTERNS = {
    js: [
        PROJECT_PATH.js + '/modules/*.js',
        PROJECT_PATH.js + '/widgets/*.js',
        PROJECT_PATH.js + '/gulpfile.js',
        PROJECT_PATH.tests + '/**/*.js',
        '!' + PROJECT_PATH.tests + '/unit/helpers/**/*.js',
        '!' + PROJECT_PATH.tests + '/coverage/**/*.js',
        '!' + PROJECT_PATH.js + '/modules/jquery.ui.*.js',
        '!' + PROJECT_PATH.js + '/dist/*.js'
    ],
    sass: [
        PROJECT_PATH.sass + '/**/*.{scss,sass}'
    ],
    icons: [
        PROJECT_PATH.icons + '/src/*.svg'
    ]
};

/*
 * Object keys are filenames of bundles that will be compiled
 * from array of paths that are the value.
 */
var JS_BUNDLES = {
    'bundle.admin.base.min.js': [
        PROJECT_PATH.js + '/polyfills/bind.js',
        PROJECT_PATH.js + '/libs/jquery.min.js',
        PROJECT_PATH.js + '/libs/pep.js',
        PROJECT_PATH.js + '/libs/class.min.js',
        PROJECT_PATH.js + '/modules/cms.base.js'
    ],
    'bundle.admin.changeform.min.js': [
        PROJECT_PATH.js + '/modules/cms.changeform.js'
    ],
    'bundle.admin.changelist.min.js': [
        PROJECT_PATH.js + '/modules/jquery.ui.custom.js',
        PROJECT_PATH.js + '/modules/cms.changelist.js',
        PROJECT_PATH.js + '/jstree/_lib/_all.js',
        PROJECT_PATH.js + '/jstree/tree_component.js'
    ],
    'bundle.toolbar.min.js': [
        PROJECT_PATH.js + '/polyfills/bind.js',
        PROJECT_PATH.js + '/libs/jquery.min.js',
        PROJECT_PATH.js + '/libs/class.min.js',
        PROJECT_PATH.js + '/libs/pep.js',
        PROJECT_PATH.js + '/modules/jquery.ui.custom.js',
        PROJECT_PATH.js + '/modules/jquery.ui.touchpunch.js',
        PROJECT_PATH.js + '/modules/jquery.ui.nestedsortable.js',
        PROJECT_PATH.js + '/modules/cms.base.js',
        PROJECT_PATH.js + '/modules/jquery.transition.js',
        PROJECT_PATH.js + '/modules/cms.messages.js',
        PROJECT_PATH.js + '/modules/cms.modal.js',
        PROJECT_PATH.js + '/modules/cms.sideframe.js',
        PROJECT_PATH.js + '/modules/cms.clipboard.js',
        PROJECT_PATH.js + '/modules/cms.plugins.js',
        PROJECT_PATH.js + '/modules/cms.structureboard.js',
        PROJECT_PATH.js + '/modules/cms.navigation.js',
        PROJECT_PATH.js + '/modules/cms.toolbar.js',
        PROJECT_PATH.js + '/modules/cms.tooltip.js'
    ]
};

// #####################################################################################################################
// #TASKS#
gulp.task('sass', function () {
    gulp.src(PROJECT_PATTERNS.sass)
        .pipe(gulpif(options.debug, sourcemaps.init()))
        .pipe(sass())
        .on('error', function (error) {
            gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.messageFormatted));
        })
        .pipe(autoprefixer({
            browsers: ['last 3 versions'],
            cascade: false
        }))
        .pipe(minifyCss({
            rebase: false
        }))
        .pipe(gulpif(options.debug, sourcemaps.write()))
        .pipe(gulp.dest(PROJECT_PATH.css));
});

gulp.task('icons', function () {
    gulp.src(PROJECT_PATTERNS.icons)
    .pipe(iconfontCss({
        fontName: 'django-cms-iconfont',
        fontPath: '../fonts/',
        path: PROJECT_PATH.sass + '/libs/_iconfont.scss',
        targetPath: '../sass/components/_iconography.scss'
    }))
    .pipe(iconfont({
        fontName: 'django-cms-iconfont',
        normalize: true
    }))
    .on('glyphs', function (glyphs, options) {
        gutil.log.bind(glyphs, options);
    })
    .pipe(gulp.dest(PROJECT_PATH.icons));
});

gulp.task('lint', ['lint:javascript']);
gulp.task('lint:javascript', function () {
    // DOCS: http://jshint.com/docs/
    return gulp.src(PROJECT_PATTERNS.js)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('tests', ['tests:unit', 'tests:integration']);

// gulp tests:unit --tests=cms.base,cms.modal
gulp.task('tests:unit', function (done) {
    var server = new KarmaServer({
        configFile: PROJECT_PATH.tests + '/karma.conf.js',
        singleRun: true
    }, done);
    server.start();
});

gulp.task('tests:unit:watch', function () {
    var server = new KarmaServer({
        configFile: PROJECT_PATH.tests + '/karma.conf.js'
    });
    server.start();
});

// gulp tests:integration --tests=loginAdmin,toolbar
gulp.task('tests:integration', function (done) {
    process.env.PHANTOMJS_EXECUTABLE = './node_modules/.bin/phantomjs';

    var files = [
        'loginAdmin',
        'toolbar',
        'addFirstPage',
        'editMode',
        'sideframe',
        'createContent',
        'users',
        'newPage',
        'switchLanguage',
        'editContent',
        'editContentTools',
        'publish',
        'logout',
        'loginToolbar',
        'dragndrop'
    ];
    var pre = ['setup'];

    if (argv && argv.tests) {
        files = argv.tests.split(',');
        gutil.log('Running tests for ' + files.join(', '));
    }

    var tests = pre.concat(files).map(function (file) {
        return PROJECT_PATH.tests + '/integration/' + file + '.js';
    });

    var casperChild = spawn('./node_modules/.bin/casperjs', ['test', '--web-security=no'].concat(tests));

    casperChild.stdout.on('data', function (data) {
        gutil.log('CasperJS:', data.toString().slice(0, -1));
    });

    casperChild.on('close', function (code) {
        done(code);
    });
});

Object.keys(JS_BUNDLES).forEach(function (bundleName) {
    var bundleFiles = JS_BUNDLES[bundleName];

    gulp.task('bundle:' + bundleName, function () {
        return gulp.src(bundleFiles)
            .pipe(gulpif(options.debug, sourcemaps.init()))
            .pipe(gulpif(!options.debug, uglify({
                preserveComments: 'some'
            })))
            .pipe(concat(bundleName, {
                newLine: '\n'
            }))
            .pipe(gulpif(options.debug, sourcemaps.write()))
            .pipe(gulp.dest(PROJECT_PATH.js + '/dist/'));
    });
});
gulp.task('bundle', Object.keys(JS_BUNDLES).map(function (bundleName) {
    return 'bundle:' + bundleName;
}));

gulp.task('watch', function () {
    gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
    gulp.watch(PROJECT_PATTERNS.js, ['lint']);
    Object.keys(JS_BUNDLES).forEach(function (bundleName) {
        var bundleFiles = JS_BUNDLES[bundleName];
        gulp.watch(bundleFiles, ['bundle:' + bundleName]);
    });
});

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