<commit_before>const GuildEmoji = require('./GuildEmoji');
const Util = require('../util/Util');
const ReactionEmoji = require('./ReactionEmoji');
const ReactionUserStore = require('../stores/ReactionUserStore');

/**
 * Represents a reaction to a message.
 */
class MessageReaction {
  constructor(client, data, message) {
    /**
     * The message that this reaction refers to
     * @type {Message}
     */
    this.message = message;

    /**
     * Whether the client has given this reaction
     * @type {boolean}
     */
    this.me = data.me;

    /**
     * The number of people that have given the same reaction
     * @type {number}
     */
    this.count = data.count || 0;

    /**
     * The users that have given this reaction, mapped by their ID
     * @type {ReactionUserStore<Snowflake, User>}
     */
    this.users = new ReactionUserStore(client, undefined, this);

    this._emoji = new ReactionEmoji(this, data.emoji);
  }

  /**
   * The emoji of this reaction, either an GuildEmoji object for known custom emojis, or a ReactionEmoji
   * object which has fewer properties. Whatever the prototype of the emoji, it will still have
   * `name`, `id`, `identifier` and `toString()`
   * @type {GuildEmoji|ReactionEmoji}
   * @readonly
   */
  get emoji() {
    if (this._emoji instanceof GuildEmoji) return this._emoji;
    // Check to see if the emoji has become known to the client
    if (this._emoji.id) {
      const emojis = this.message.client.emojis;
      if (emojis.has(this._emoji.id)) {
        const emoji = emojis.get(this._emoji.id);
        this._emoji = emoji;
        return emoji;
      }
    }
    return this._emoji;
  }

  toJSON() {
    return Util.flatten(this, { emoji: 'emojiID', message: 'messageID' });
  }

  _add(user) {
    if (!this.users.has(user.id)) {
      this.users.set(user.id, user);
      this.count++;
    }
    if (!this.me) this.me = user.id === this.message.client.user.id;
  }

  _remove(user) {
    if (this.users.has(user.id)) {
      this.users.delete(user.id);
      this.count--;
      if (user.id === this.message.client.user.id) this.me = false;
      if (this.count <= 0) {
        this.message.reactions.remove(this.emoji.id || this.emoji.name);
      }
    }
  }
}

module.exports = MessageReaction;
<commit_msg>fix(MessageReaction): do not increment count twice for own user<commit_after>const GuildEmoji = require('./GuildEmoji');
const Util = require('../util/Util');
const ReactionEmoji = require('./ReactionEmoji');
const ReactionUserStore = require('../stores/ReactionUserStore');

/**
 * Represents a reaction to a message.
 */
class MessageReaction {
  constructor(client, data, message) {
    /**
     * The message that this reaction refers to
     * @type {Message}
     */
    this.message = message;

    /**
     * Whether the client has given this reaction
     * @type {boolean}
     */
    this.me = data.me;

    /**
     * The number of people that have given the same reaction
     * @type {number}
     */
    this.count = data.count || 0;

    /**
     * The users that have given this reaction, mapped by their ID
     * @type {ReactionUserStore<Snowflake, User>}
     */
    this.users = new ReactionUserStore(client, undefined, this);

    this._emoji = new ReactionEmoji(this, data.emoji);
  }

  /**
   * The emoji of this reaction, either an GuildEmoji object for known custom emojis, or a ReactionEmoji
   * object which has fewer properties. Whatever the prototype of the emoji, it will still have
   * `name`, `id`, `identifier` and `toString()`
   * @type {GuildEmoji|ReactionEmoji}
   * @readonly
   */
  get emoji() {
    if (this._emoji instanceof GuildEmoji) return this._emoji;
    // Check to see if the emoji has become known to the client
    if (this._emoji.id) {
      const emojis = this.message.client.emojis;
      if (emojis.has(this._emoji.id)) {
        const emoji = emojis.get(this._emoji.id);
        this._emoji = emoji;
        return emoji;
      }
    }
    return this._emoji;
  }

  toJSON() {
    return Util.flatten(this, { emoji: 'emojiID', message: 'messageID' });
  }

  _add(user) {
    if (!this.users.has(user.id)) {
      this.users.set(user.id, user);
      if (!this.me || user.id !== this.message.client.user.id) this.count++;
    }
    if (!this.me) this.me = user.id === this.message.client.user.id;
  }

  _remove(user) {
    if (this.users.has(user.id)) {
      this.users.delete(user.id);
      this.count--;
      if (user.id === this.message.client.user.id) this.me = false;
      if (this.count <= 0) {
        this.message.reactions.remove(this.emoji.id || this.emoji.name);
      }
    }
  }
}

module.exports = MessageReaction;
<|endoftext|>


<commit_before>var gulp   = require('gulp');
var stylus = require('gulp-stylus');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var clean  = require('gulp-clean');
var browserify = require('gulp-browserify');
var refresh    = require('gulp-livereload');
var livereload = require('tiny-lr');

var server = livereload();
var paths  = require('./config/path.json');

gulp.task('scripts', function(cb) {
  return gulp.task(['client/**/*.js'])
    .pipe(browserify())
    .pipe(concat('dest.js'))
    .pipe(gulp.dest('build'))
    .pipe(refresh(server));
});

gulp.task('uglify', function(cb) {
  return gulp.src(['client/**/*.js'])
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'));
});

gulp.task('styles', function(cb) {
  return gulp.src(paths.stylus.src)
    .pipe(stylus())
    .pide(gulp.dest(paths.stylus.dest));
});

gulp.task('lr-server', function() {
  server.listen(35729, function(err) {
    if (err) return console.log(err);
  });
});

gulp.task('clean', function(cb) {
  gulp.src('build', {read: false})
    .pipe(clean({force: true}));
});

gulp.task('default', function(cb) {
  gulp.run('clean', 'lr-server', 'scripts', 'styles');

  gulp.watch('dist/js/**', function(event) {
    gulp.run('scripts');
  });

  gulp.watch('dist/css**', function(event) {
    gulp.run('styles');
  });
});

<commit_msg>fix styles task<commit_after>var gulp   = require('gulp');
var stylus = require('gulp-stylus');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var clean  = require('gulp-clean');
var browserify = require('gulp-browserify');
var refresh    = require('gulp-livereload');
var livereload = require('tiny-lr');

var server = livereload();
var paths  = require('./config/path.json');

gulp.task('scripts', function(cb) {
  return gulp.src(config.paths.scripts.src)
    .pipe(browserify())
    .pipe(concat(config.build.scripts))
    .pipe(gulp.dest(config.paths.scripts.dest))
    .pipe(refresh(server));
});

gulp.task('uglify', function(cb) {
  return gulp.src(['client/**/*.js'])
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'));
});

gulp.task('styles', function(cb) {
  return gulp.src(paths.stylus.src)
    .pipe(stylus())
    .pide(gulp.dest(paths.stylus.dest));
});

gulp.task('lr-server', function() {
  server.listen(35729, function(err) {
    if (err) return console.log(err);
  });
});

gulp.task('clean', function(cb) {
  gulp.src('build', {read: false})
    .pipe(clean({force: true}));
});

gulp.task('default', function(cb) {
  gulp.run('clean', 'lr-server', 'scripts', 'styles');

  gulp.watch('dist/js/**', function(event) {
    gulp.run('scripts');
  });

  gulp.watch('dist/css**', function(event) {
    gulp.run('styles');
  });
});

<|endoftext|>


<commit_before>//-----------------
// GULPFILE EXAMPLE
//-----------------

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var del = require('del');

// Compile Sass and create the relative sourcemap
gulp.task('sass', function() {
    gulp.src('./src/assets/sass/main.sass')
    .pipe(sourcemaps.init())
    .pipe($.changed('./src/assets/sass/**/*.sass'))
    .pipe($.sass()).on('error', $.util.log)
    .pipe($.autoprefixer('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1', { cascade: true }))
    .pipe(sourcemaps.write('../sourcemaps'))
    .pipe(gulp.dest('./development/css'))
    .pipe(browserSync.reload({stream:true}));
});

// Compile Jade
gulp.task('jade', function() {
  gulp.src('./src/assets/jade/*.jade')
  .pipe($.changed('./src/assets/jade/**/*.jade'))
  .pipe($.jade({ pretty: true }))
  .pipe(gulp.dest('./development/'))
  .pipe(browserSync.reload({stream: true}))
});

// Typescript
gulp.task('typescript', function () {
  var tsResult = gulp.src('./src/assets/ts/**/*.ts')
    .pipe($.typescript({
        module: 'amd',
        verbose: false,
        target: 'es5',
        fast: 'never',
        sourceMap: false,
        allowImportModule : true,
        out: 'main.js'
      }));
  return tsResult.js.pipe(gulp.dest('./development/js'));
});

// Clean the dist folder
gulp.task('clean', function(cb) {
   return del(['./dist/*'], cb);
});

// Minify and Uglify
gulp.task('minify', ['move'], function() {
  gulp.src('./development/css/main.css')
  .pipe($.minifyCss())
  .pipe(gulp.dest('./development/css/'));
  gulp.src('./development/js/main.js')
  .pipe($.uglify())
  .pipe(gulp.dest('./development/js/'))
});

// Move the needed files and folders into a dist folder which can be deployed to the webserver
gulp.task('move', ['clean'], function() {
  gulp.src(['./development/**/*.*', '!./development/sourcemaps/**/*'], { base: './development' })
  .pipe(gulp.dest('./dist'));
});

// browser-sync serve the work to
// your browser of choice
gulp.task('browser-sync', ['sass', 'jade'], function() {
  browserSync.init(['./src/jade/**/*.jade'], {
    server: {
      baseDir: "./development"
    },
    ghostMode: {
      clicks: false,
      location: false,
      forms: false,
      scroll: false
    }
  });
});

// FINAL TASKS
gulp.task('dist', ['minify']);

gulp.task('default', ['browser-sync'], function() {
  gulp.watch('./src/assets/sass/**/*.sass', ['sass']);
  gulp.watch('./src/assets/jade/**/*.jade', ['jade']);
});
<commit_msg>Fixes to gulpfile<commit_after>//***********
// GULPFILE *
//***********

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var del = require('del');

// Compile Sass and create the relative sourcemap
gulp.task('sass', function() {
    gulp.src('./src/assets/sass/main.sass')
    .pipe(sourcemaps.init())
    .pipe($.changed('./src/assets/sass/**/*.sass'))
    .pipe($.sass()).on('error', $.util.log)
    .pipe($.autoprefixer('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1', { cascade: true }))
    .pipe(sourcemaps.write('../sourcemaps'))
    .pipe(gulp.dest('./development/css'))
    .pipe(browserSync.reload({stream:true}));
});

// Compile Jade
gulp.task('jade', function() {
  gulp.src('./src/assets/jade/*.jade')
  .pipe($.changed('./src/assets/jade/**/*.jade'))
  .pipe($.jade({ pretty: true }))
  .pipe(gulp.dest('./development/'))
  .pipe(browserSync.reload({stream: true}))
});

// Typescript
gulp.task('typescript', function () {
  var tsResult = gulp.src('./src/assets/ts/**/*.ts')
    .pipe($.typescript({
        module: 'amd',
        verbose: false,
        target: 'es5',
        fast: 'never',
        sourceMap: false,
        allowImportModule : true,
        out: 'main.js'
      }));
  return tsResult.js.pipe(gulp.dest('./development/js'));
});

// Clean the dist folder
gulp.task('clean', function(cb) {
   return del(['./dist/*'], cb);
});

// Minify and Uglify the dist folder files
gulp.task('minify', ['move'], function() {
  gulp.src('./dist/css/main.css')
  .pipe($.minifyCss())
  .pipe(gulp.dest('./dist/css/'));
  gulp.src('./dist/js/main.js')
  .pipe($.uglify())
  .pipe(gulp.dest('./dist/js/'))
});

// Move the needed files and folders
// into a dist folder which can be deployed
gulp.task('move', ['clean'], function() {
  gulp.src(['./development/**/*', '!./development/sourcemaps/**/*'], { base: './development' })
  .pipe(gulp.dest('./dist'));
});

// browser-sync serve the work to
// your browser of choice
gulp.task('browser-sync', ['sass', 'jade'], function() {
  browserSync.init(['./src/jade/**/*.jade'], {
    server: {
      baseDir: "./development"
    },
    ghostMode: {
      clicks: false,
      location: false,
      forms: false,
      scroll: false
    }
  });
});

//**************
// FINAL TASKS *
//**************

gulp.task('dist', ['minify']);

gulp.task('default', ['browser-sync'], function() {
  gulp.watch('./src/assets/sass/**/*.sass', ['sass']);
  gulp.watch('./src/assets/jade/**/*.jade', ['jade']);
  gulp.watch('./src/assets/ts/**/*.ts', ['typescript']);
});
<|endoftext|>


<commit_before>'use strict'

/* jshint node: true */

let gulp = require('gulp'),
    path = require('path'),
    paths = require('./electron/lib/paths'),
    env = require('./electron/lib/env'),
    packaging = require('./electron/lib/packaging'),
    Q = require('q'),
    $ = require('gulp-load-plugins')({ lazy: true }),
    proc = require('child_process'),
    poststylus = require('poststylus'),
    electron = require('electron-prebuilt'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    browserify = require('browserify'),
    watchify = require('watchify'),
    babelify = require('babelify'),
    publish = require('gh-publish'),
    hbsfy = require('hbsfy'),
    nib = require('nib'),
    fs = require('fs'),
    del = require('del')

const pkg = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
const logger = (logFn, color) => (head, ...tail) => logFn.apply(logFn, [$.util.colors[color](head)].concat(tail))
const yellowLog = logger(console.log, 'yellow')

env.set($.util.env.env || 'development')

yellowLog(fs.readFileSync('./greeting', 'utf8'))
yellowLog(`
     App name    : ${pkg.title}
     App version : ${pkg.version}
     Platform    : ${process.platform}
     Env         : ${env.get()}
`)

const bundler = browserify({
    debug: env.dev(),
    entries: ['./app/scripts/app.js'],
    cache: {},
    packageCache: {},
    plugin: env.dev() ? [watchify] : []
})
    .transform(hbsfy)
    .transform(babelify.configure({ presets: ['es2015'] }))

gulp.task('styles', () => {
    return gulp.src(paths.styles('*.styl'))
        .pipe($.stylus({ use: [poststylus('lost'), nib()], 'include css': true }))
        .on('error', function (e) {
            $.util.log(e.message)
            this.emit('end')
        })
        .pipe(gulp.dest(paths.build('styles/')))
        .pipe($.livereload())
})

gulp.task('watch', () => {
    $.livereload.listen()
    return Q.all([
        gulp.watch(paths.styles('**/*.styl'), gulp.series('styles')),
        watchify(bundler).on('update', () =>
            makeBundle(bundler, { sourceMap: true }).pipe(gulp.dest(paths.build())).pipe($.livereload()))
    ])
})

gulp.task('clean', () => {
    return del([
        paths.build(),
        paths.pkg('node_modules')
    ], { force: true })
})

gulp.task('template', () => {
    return gulp.src(paths.app('index.hbs'))
        .pipe($.compileHandlebars({ assets: paths.assets, title: pkg.title }))
        .pipe($.rename('index.html'))
        .pipe(gulp.dest(paths.build()))
})

gulp.task('svg', () => {
    return gulp.src(paths.app('svg/*.svg'))
        .pipe($.svgstore())
        .pipe($.rename('sprite.svg'))
        .pipe(gulp.dest(paths.build('images')))
})

gulp.task('lint', () => {
    return gulp.src([
        paths.app('*/**.js'),
        paths.electron('*/**.js'),
        '!' + paths.build('**')
    ])
        .pipe($.eslint())
        .pipe($.eslint.format())
})

// Build task
gulp.task('build', gulp.series('lint', 'clean', gulp.parallel('template', 'styles', 'svg'), () => {
    gulp.src(paths.app('images/**'))
        .pipe(gulp.dest(paths.build('images')))

    gulp.src(paths.cwd('package.json'))
        .pipe(gulp.dest(paths.pkg()))

    gulp.src(paths.app('fonts/**'))
        .pipe(gulp.dest(paths.build('fonts')))

    gulp.src(paths.app('bootstrap.js'))
        .pipe(gulp.dest(paths.build()))

    return makeBundle(bundler, { sourceMap: env.dev(), uglify: env.prod()})
        .pipe(gulp.dest(paths.build()))
}))

gulp.task('pkg-build', () => {
    return gulp.src($.npmFiles(), { base: './' })
        .pipe(gulp.dest(paths.pkg()))
})

gulp.task('pkg', gulp.series('build', 'pkg-build', (done) => {
    let log = (s) => $.util.log($.util.colors.magenta('[Packaging] -> ' + s))
    return packaging(log, {
        type: $.util.env.type,
        platform: $.util.env.platform || process.platform,
        arch: '64'
    }, done)
}))

gulp.task('publish', (done) => {
    const githubToken = $.util.env.token
    if (!githubToken) throw new Error('GitHub token must be set!')

    return publish({
        repo: pkg.name,
        owner: 'roman0x58',
        auth: {
            token: githubToken
        },
        assets: fs.readdirSync(paths.release('installers'))
            .filter((p) => !p.startsWith('.'))
            .map((p) => path.join('release/installers/', p))
    }, done)
})

let makeBundle = function (bundle, { sourceMap = false, uglify = false, fileName = 'build.js' }) {
    let lo = (s) => {
        $.util.log($.util.colors.blue(s))
    }

    lo('[Bundle] -> Bundling es6 application...')

    let stream = bundle.bundle()
        .on('error', $.util.log)
        .pipe(source(fileName))
        .pipe(buffer())

    if (uglify === true) {
        lo('[Bundle] -> Uglifiyng bundle')
        stream.pipe($.uglify({ compress: { drop_console: true }}))
    }

    if (sourceMap === true) {
        lo('[Bundle] -> Creating source map')
        return stream
            .pipe($.sourcemaps.init({ loadMaps: true }))
            .pipe($.sourcemaps.write('./'))
    }
    return stream
}

gulp.task('start', gulp.series('build', gulp.parallel('watch', () => {
    return proc.spawn(electron, ['--js-flags=--harmony-async-await', './electron/main.js'], { stdio: 'inherit' }).on('close', process.exit)
})))<commit_msg>Rename electron-prebuild to electron<commit_after>'use strict'

/* jshint node: true */

let gulp = require('gulp'),
    path = require('path'),
    paths = require('./electron/lib/paths'),
    env = require('./electron/lib/env'),
    packaging = require('./electron/lib/packaging'),
    Q = require('q'),
    $ = require('gulp-load-plugins')({ lazy: true }),
    proc = require('child_process'),
    poststylus = require('poststylus'),
    electron = require('electron'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    browserify = require('browserify'),
    watchify = require('watchify'),
    babelify = require('babelify'),
    publish = require('gh-publish'),
    hbsfy = require('hbsfy'),
    nib = require('nib'),
    fs = require('fs'),
    del = require('del')

const pkg = JSON.parse(fs.readFileSync('package.json', 'utf-8'))
const logger = (logFn, color) => (head, ...tail) => logFn.apply(logFn, [$.util.colors[color](head)].concat(tail))
const yellowLog = logger(console.log, 'yellow')

env.set($.util.env.env || 'development')

yellowLog(fs.readFileSync('./greeting', 'utf8'))
yellowLog(`
     App name    : ${pkg.title}
     App version : ${pkg.version}
     Platform    : ${process.platform}
     Env         : ${env.get()}
`)

const bundler = browserify({
    debug: env.dev(),
    entries: ['./app/scripts/app.js'],
    cache: {},
    packageCache: {},
    plugin: env.dev() ? [watchify] : []
})
    .transform(hbsfy)
    .transform(babelify.configure({ presets: ['es2015'] }))

gulp.task('styles', () => {
    return gulp.src(paths.styles('*.styl'))
        .pipe($.stylus({ use: [poststylus('lost'), nib()], 'include css': true }))
        .on('error', function (e) {
            $.util.log(e.message)
            this.emit('end')
        })
        .pipe(gulp.dest(paths.build('styles/')))
        .pipe($.livereload())
})

gulp.task('watch', () => {
    $.livereload.listen()
    return Q.all([
        gulp.watch(paths.styles('**/*.styl'), gulp.series('styles')),
        watchify(bundler).on('update', () =>
            makeBundle(bundler, { sourceMap: true }).pipe(gulp.dest(paths.build())).pipe($.livereload()))
    ])
})

gulp.task('clean', () => {
    return del([
        paths.build(),
        paths.pkg('node_modules')
    ], { force: true })
})

gulp.task('template', () => {
    return gulp.src(paths.app('index.hbs'))
        .pipe($.compileHandlebars({ assets: paths.assets, title: pkg.title }))
        .pipe($.rename('index.html'))
        .pipe(gulp.dest(paths.build()))
})

gulp.task('svg', () => {
    return gulp.src(paths.app('svg/*.svg'))
        .pipe($.svgstore())
        .pipe($.rename('sprite.svg'))
        .pipe(gulp.dest(paths.build('images')))
})

gulp.task('lint', () => {
    return gulp.src([
        paths.app('*/**.js'),
        paths.electron('*/**.js'),
        '!' + paths.build('**')
    ])
        .pipe($.eslint())
        .pipe($.eslint.format())
})

// Build task
gulp.task('build', gulp.series('lint', 'clean', gulp.parallel('template', 'styles', 'svg'), () => {
    gulp.src(paths.app('images/**'))
        .pipe(gulp.dest(paths.build('images')))

    gulp.src(paths.cwd('package.json'))
        .pipe(gulp.dest(paths.pkg()))

    gulp.src(paths.app('fonts/**'))
        .pipe(gulp.dest(paths.build('fonts')))

    gulp.src(paths.app('bootstrap.js'))
        .pipe(gulp.dest(paths.build()))

    return makeBundle(bundler, { sourceMap: env.dev(), uglify: env.prod()})
        .pipe(gulp.dest(paths.build()))
}))

gulp.task('pkg-build', () => {
    return gulp.src($.npmFiles(), { base: './' })
        .pipe(gulp.dest(paths.pkg()))
})

gulp.task('pkg', gulp.series('build', 'pkg-build', (done) => {
    let log = (s) => $.util.log($.util.colors.magenta('[Packaging] -> ' + s))
    return packaging(log, {
        type: $.util.env.type,
        platform: $.util.env.platform || process.platform,
        arch: '64'
    }, done)
}))

gulp.task('publish', (done) => {
    const githubToken = $.util.env.token
    if (!githubToken) throw new Error('GitHub token must be set!')

    return publish({
        repo: pkg.name,
        owner: 'roman0x58',
        auth: {
            token: githubToken
        },
        assets: fs.readdirSync(paths.release('installers'))
            .filter((p) => !p.startsWith('.'))
            .map((p) => path.join('release/installers/', p))
    }, done)
})

let makeBundle = function (bundle, { sourceMap = false, uglify = false, fileName = 'build.js' }) {
    let lo = (s) => {
        $.util.log($.util.colors.blue(s))
    }

    lo('[Bundle] -> Bundling es6 application...')

    let stream = bundle.bundle()
        .on('error', $.util.log)
        .pipe(source(fileName))
        .pipe(buffer())

    if (uglify === true) {
        lo('[Bundle] -> Uglifiyng bundle')
        stream.pipe($.uglify({ compress: { drop_console: true }}))
    }

    if (sourceMap === true) {
        lo('[Bundle] -> Creating source map')
        return stream
            .pipe($.sourcemaps.init({ loadMaps: true }))
            .pipe($.sourcemaps.write('./'))
    }
    return stream
}

gulp.task('start', gulp.series('build', gulp.parallel('watch', () => {
    return proc.spawn(electron, ['--js-flags=--harmony-async-await', './electron/main.js'], { stdio: 'inherit' }).on('close', process.exit)
})))<|endoftext|>


<commit_before>var path         = require('path');
var childProcess = require('child_process');
var gulp         = require('gulp');
var babel        = require('gulp-babel');
var eslint       = require('gulp-eslint');
var flatten      = require('gulp-flatten');
var mocha        = require('gulp-mocha');
var msbuild      = require('gulp-msbuild');
var del          = require('del');
var through      = require('through2');
var Promise      = require('promise');

var exec = Promise.denodeify(childProcess.exec);

// Windows natives
gulp.task('clean-win-natives', function (cb) {
    del('bin/win', cb);
});

gulp.task('build-win-natives', ['clean-win-natives'], function () {
    return gulp
        .src('src/**/*.csproj')
        .pipe(msbuild({
            targets: ['Clean', 'Build']
        }));
});

gulp.task('copy-win-natives', ['build-win-natives'], function () {
    return gulp
        .src('src/**/win/bin/Release/*.exe')
        .pipe(flatten())
        .pipe(gulp.dest('bin/win'));
});

// Mac natives
gulp.task('clean-mac-natives', function (callback) {
    del('bin/mac', callback);
});

gulp.task('build-mac-natives', ['clean-mac-natives'], function () {
    function make (options) {
        return through.obj(function (file, enc, callback) {
            if (file.isNull()) {
                callback(null, file);
                return;
            }

            var dirPath = path.dirname(file.path);

            exec('make -C ' + dirPath, { env: options })
                .then(function () {
                    callback(null, file);
                })
                .catch(function (error) {
                    callback(error);
                });
        });
    }

    return gulp
        .src('src/**/mac/Makefile')
        .pipe(make({
            DEST: path.join(__dirname, 'bin/mac')
        }));
});

gulp.task('copy-mac-natives', ['clean-mac-natives'], function () {
    return gulp
        .src('src/**/mac/*.scpt')
        .pipe(flatten())
        .pipe(gulp.dest('bin/mac'));
});

// Test
gulp.task('run-playground-win', ['build-win'], function () {
    require('./test/playground/index');
});

gulp.task('run-playground-mac', ['build-mac'], function () {
    require('./test/playground/index');
});

gulp.task('test-lib', ['build-lib'], function () {
    return gulp
        .src('test/tests/*-test.js')
        .pipe(mocha({
            ui:       'bdd',
            reporter: 'spec',
            timeout:  typeof v8debug === 'undefined' ? 2000 : Infinity // NOTE: disable timeouts in debug
        }));
});

gulp.task('test', ['lint', 'test-lib']);

// General tasks
gulp.task('lint', function () {
    return gulp
        .src([
            'src/**/*.js',
            'test/**/*.js',
            '!test/playground/public/**/*',
            'Gulpfile.js'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('clean-lib', function (cb) {
    del('lib', cb);
});

gulp.task('build-lib', ['clean-lib'], function () {
    return gulp
        .src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('build-win', ['build-lib', 'build-win-natives', 'copy-win-natives']);
gulp.task('build-mac', ['build-lib', 'build-mac-natives', 'copy-mac-natives']);
<commit_msg>Gulp tasks refactoring (close #10)<commit_after>var path         = require('path');
var childProcess = require('child_process');
var gulp         = require('gulp');
var babel        = require('gulp-babel');
var eslint       = require('gulp-eslint');
var flatten      = require('gulp-flatten');
var mocha        = require('gulp-mocha');
var msbuild      = require('gulp-msbuild');
var del          = require('del');
var through      = require('through2');
var Promise      = require('promise');

var exec = Promise.denodeify(childProcess.exec);

// Windows bin
gulp.task('clean-win-bin', function (cb) {
    del('bin/win', cb);
});

gulp.task('build-win-executables', ['clean-win-bin'], function () {
    return gulp
        .src('src/**/*.csproj')
        .pipe(msbuild({
            targets: ['Clean', 'Build']
        }));
});

gulp.task('copy-win-executables', ['build-win-executables'], function () {
    return gulp
        .src('src/**/win/bin/Release/*.exe')
        .pipe(flatten())
        .pipe(gulp.dest('bin/win'));
});

// Mac bin
gulp.task('clean-mac-bin', function (callback) {
    del('bin/mac', callback);
});

gulp.task('build-mac-executables', ['clean-mac-bin'], function () {
    function make (options) {
        return through.obj(function (file, enc, callback) {
            if (file.isNull()) {
                callback(null, file);
                return;
            }

            var dirPath = path.dirname(file.path);

            exec('make -C ' + dirPath, { env: options })
                .then(function () {
                    callback(null, file);
                })
                .catch(callback);
        });
    }

    return gulp
        .src('src/**/mac/Makefile')
        .pipe(make({
            DEST: path.join(__dirname, 'bin/mac')
        }));
});

gulp.task('copy-mac-scripts', ['clean-mac-bin'], function () {
    return gulp
        .src('src/**/mac/*.scpt')
        .pipe(flatten())
        .pipe(gulp.dest('bin/mac'));
});

// Test
gulp.task('run-playground-win', ['build-win'], function () {
    require('./test/playground/index');
});

gulp.task('run-playground-mac', ['build-mac'], function () {
    require('./test/playground/index');
});

gulp.task('test-lib', ['build-lib'], function () {
    return gulp
        .src('test/tests/*-test.js')
        .pipe(mocha({
            ui:       'bdd',
            reporter: 'spec',
            timeout:  typeof v8debug === 'undefined' ? 2000 : Infinity // NOTE: disable timeouts in debug
        }));
});

gulp.task('test', ['lint', 'test-lib']);

// General tasks
gulp.task('lint', function () {
    return gulp
        .src([
            'src/**/*.js',
            'test/**/*.js',
            '!test/playground/public/**/*',
            'Gulpfile.js'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('clean-lib', function (cb) {
    del('lib', cb);
});

gulp.task('build-lib', ['clean-lib'], function () {
    return gulp
        .src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('build-win', ['build-lib', 'copy-win-executables']);
gulp.task('build-mac', ['build-lib', 'build-mac-executables', 'copy-mac-scripts']);
<|endoftext|>


<commit_before>/* =========================================================================== */
/* Requires & Vars
/* =========================================================================== */
// Require.
var gulp   = require('gulp'),
	args   = require('yargs').argv,
	gulpif = require('gulp-if'),
	util   = require('gulp-util'),
	notify = require('gulp-notify'),
	buffer = require('vinyl-buffer'),
	header = require('gulp-header'),
	source = require('vinyl-source-stream');

// Vars.
var version        = '1.0.0',
	src_dir        = './src/',
	dist_dir       = './src/dist/',
	is_development = (args.config == 'development') ? true : false,
	is_production  = (args.config == 'production' || args.config == undefined) ? true : false,
	error_handler  = function(err){
		// Show notification.
		gulp.src('gulpfile.js').pipe(notify({
			message: 'Error: ' + err.message
		}));
		// Show in terminal log.
		util.log(util.colors.red('Error'), err.message);
	},
	task_handler = function(err){
		// Standard error.
		error_handler(err);
		// Don't break stream.
		this.emit('end');
	}

/* =========================================================================== */
/* Combined Tasks
/* =========================================================================== */
// Task.
gulp.task('default', [
	// All states.
	'js',
	'css',
	'images',
	// Development states.
	'dalek',
	'jasmine',
	'jshint'
], function(){
	// Show notification.
	gulp.src('gulpfile.js').pipe(notify({
		message: 'Default task is complete'
	}));
});

/* =========================================================================== */
/* CSS
/* =========================================================================== */
// CSS Build File.
gulp.task('css', function(){
	// Require.
	var sass         = require('gulp-sass'),
		sourcemaps   = require('gulp-sourcemaps'),
		globbing     = require('gulp-css-globbing'),
		autoprefixer = require('gulp-autoprefixer');

	// Header template.
	var header_tpl = ['/* ==========================================================================',
		'<%= type %> Stylesheet',
		'Application Version: <%= version %>',
		'Compiled: <%= date %>',
		'========================================================================== */',
		'',
		''].join('\n');

	// Task.
	return gulp.src(dist_dir + 'css/scss/build.scss')
		.pipe(globbing({
			extensions: ['.scss']
		}))
        .pipe(sourcemaps.init())
        .pipe(sass({
	        outputStyle: (is_production) ? 'compressed' : 'expanded',
        	errLogToConsole: true,
	        onError: function(err){
	            return notify.write(err);
	        }
	    }))
		.on('error', task_handler)
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: false
        }))
        .pipe(sourcemaps.write('/', {includeContent: false}))
		.pipe(header(header_tpl, {
			type   : (is_production) ? 'Minified' : 'Unminified',
			version: version,
			date   : Date()
		}))
		.pipe(gulp.dest(dist_dir + 'css'))
		.pipe(notify({message: 'CSS task complete.'}));
});

/* =========================================================================== */
/* JavaScript Compiling
/* =========================================================================== */
// JS Common Libraries & Vendors.
gulp.task('js:common', function(){
	// Require.
	var browserify = require('browserify'),
		rename     = require('gulp-rename');

	// Task.
	return browserify(dist_dir + 'js/vendor/').bundle()
		.on('error', task_handler)
		.pipe(source('index.js'))
	    .pipe(buffer())
		.pipe(rename('common.js'))
		.pipe(gulp.dest(dist_dir + 'js/compiled/'))
		.pipe(notify({message: 'JS Common task complete.'}));
});

// JS Application Files.
gulp.task('js:app', function(){
	// Require.
	var browserify = require('browserify'),
		rename     = require('gulp-rename');

	// Task.
	return browserify(dist_dir + 'js/app/').bundle()
		.on('error', task_handler)
	    .pipe(source('index.js'))
	    .pipe(buffer())
		.pipe(rename('app.js'))
		.pipe(gulp.dest(dist_dir + 'js/compiled/'))
		.pipe(notify({message: 'JS App task complete.'}));
});

// JS Build File (Concatenated App & Common).
gulp.task('js', ['js:app'], function(){
	// Require.
	var concat = require('gulp-concat'),
		uglify = require('gulp-uglify');

	// Header template.
	var header_tpl_env = ['// Set environment variable',
	'window.gulp_env = "<%= env %>";',
	'',
	''].join('\n');
	var header_tpl = ['/* ==========================================================================',
		'<%= type %> JavaScript',
		'Application Version: <%= version %>',
		'Compiled: <%= date %>',
		'========================================================================== */',
		'',
		''].join('\n');

	// Task.
	return gulp.src([dist_dir + 'js/compiled/common.js', dist_dir + 'js/compiled/app.js'])
	    .pipe(concat('build.js'))
		.pipe(header(header_tpl_env, {
			env: (is_production) ? 'production' : 'development'
		}))
		.pipe(gulpif(is_production, uglify()))
		.pipe(header(header_tpl, {
			type   : (is_production) ? 'Minified' : 'Unminified',
			version: version,
			date   : Date()
		}))
	    .pipe(gulp.dest(dist_dir + 'js/build'))
		.on('error', task_handler)
		.pipe(notify({message: 'JS Build task complete.'}));
});

/* =========================================================================== */
/* Watch
/* =========================================================================== */
gulp.task('watch', function(){
	// Run JS Master on JS and HBS file changes.
	gulp.watch([dist_dir + 'js/app/**/*.js', dist_dir + 'js/plugins/**/*.js', dist_dir + 'js/**/*.hbs'], ['js']);
	// Run CSS on SCSS file changes.
	gulp.watch(dist_dir + 'css/scss/**/*.scss', ['css']);
});

/* =========================================================================== */
/* Sync (BrowserSync)
/* =========================================================================== */
gulp.task('sync', function(){
	// Require.
	var browserSync = require('browser-sync'),
		reload      = browserSync.reload;

	// Vars.
	var url    = args.url || false,
		notify = args.notify || false,
		xip    = args.xip || true,
		https  = args.https || false;

	if(url){
		browserSync.init({
			open   : 'external',
			browser: ['google chrome'],
			notify : notify,
			https  : https,
			xip    : xip,
			proxy  : url
		});
	}
	else{
		browserSync.init({
			open   : 'external',
			browser: ['google chrome'],
			notify : notify,
			https  : https,
			xip    : xip,
			server : {
				baseDir: [src_dir]
			}
		});
	}

	// Run Browserify on JS and HBS file changes.
	gulp.watch([dist_dir + 'js/app/**/*.js', dist_dir + 'js/plugins/**/*.js', dist_dir + 'js/**/*.hbs'], ['js']);
	// Run Compass on SCSS file changes.
	gulp.watch(dist_dir + 'css/scss/**/*.scss', ['css']);
	// Reload on file changes.
	gulp.watch([
		src_dir + '**/*.html',
		src_dir + '**/*.php',
		dist_dir + 'css/build.css',
		dist_dir + 'js/build/build.js'
	], reload);
});

/* =========================================================================== */
/* Testing
/* =========================================================================== */
// Dalek - Browser Testing (Development Mode Only).
gulp.task('dalek', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Require.
	var dalek = require('gulp-dalek');

	// Files.
	var tests = [
		// dist_dir + 'js/spec/dalek/examples.js',
		dist_dir + 'js/spec/dalek/elements.js',
		dist_dir + 'js/spec/dalek/roles.js'
	];

	// Task.
	return gulp.src(tests)
		.pipe(
			dalek({
				browser : [
					'phantomjs',
					// 'chrome'
				],
				reporter: [
					'console',
					// 'html',
					// 'junit'
				]
			})
		)
		.on('error', task_handler);
});

// Jasmine - Client Testing (Development Mode Only).
gulp.task('jasmine', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Require.
	var karma = require('gulp-karma');

    // Task.
	return gulp.src(dist_dir + 'js/spec/jasmine/*')
		.pipe(karma({
			configFile: 'karma.conf.js',
			action    : 'run'
		}))
		.on('error', task_handler);
});

/* =========================================================================== */
/* Task Tools
/* =========================================================================== */
// JSHint (Development Mode Only).
gulp.task('jshint', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Vars.
	var jshint  = require('gulp-jshint'),
		stylish = require('jshint-stylish');

    // Task.
	return gulp.src(dist_dir + 'js/app/**/*.js')
	    .pipe(jshint())
	    .pipe(jshint.reporter(stylish))
		.pipe(notify({message: 'JSHint task complete.'}));
});

// Image Minification.
gulp.task('images', function(){
	// Require.
	var imagemin = require('gulp-imagemin')
		cache	 = require('gulp-cache');

	// Task.
    return gulp.src(dist_dir + 'images/**/*')
        .pipe(cache(imagemin({
            optimizationLevel: 3,
            progressive      : true,
            interlaced       : true
        })))
        .pipe(gulp.dest(dist_dir + 'images'))
		.pipe(notify({message: 'Images task complete.'}));
});

/* =========================================================================== */
/* One Off Tools
/* =========================================================================== */
// Image Sprites.
gulp.task('sprite', function(){
	// Require.
	var sprity = require('sprity');

	// Task.
    return sprity.src({
		src         : dist_dir + 'images/icons/sprite/*.png',
		style       : dist_dir + 'css/scss/site/_sprites.scss',
		cssPath     : '../images/icons/',
		margin      : 5,
		base64      : false,
		retina      : false,
		background  : '#FFFFFF',
		orientation : 'horizontal',
		prefix      : 'css-sprite',
		name        : 'sprite',
		processor   : 'sass',
		'style-type': 'scss'
	})
    .pipe(gulpif('*.png', gulp.dest(dist_dir + 'images/icons'), gulp.dest(dist_dir + 'css/scss/site')))
	.pipe(notify({message: 'Sprite task complete.'}));
});

// App release.
gulp.task('release', function(){
	// Vars.
	var files = [
        './src/**/*.*',
        '!./src/**/*.scss',
        '!./src/dist/js/app/**/*',
        '!./src/dist/js/compiled/**/*',
        '!./src/dist/js/plugins/**/*',
        '!./src/dist/js/spec/**/*',
        '!./src/dist/js/vendor/**/*',
    ];

    // Task.
	return gulp.src(files, {base: src_dir})
		.pipe(gulp.dest('releases/release-' + version))
		.pipe(notify({message: 'Release task complete.'}));
});

// Google Page Speed Tests.
gulp.task('psi', function(){
	// Require.
	var psi = require('psi'),
		fs  = require('fs-extra');

	// Vars.
	var url  = args.url || 'http://google.com',
		mode = args.mode || 'desktop';

	// Seems to freeze without this.
	console.log('Query URL: ' + url);

	// Functions.
	function convert_object(obj){
		var arr = [];
		for(var key in obj){
		    if(obj.hasOwnProperty(key)){
		    	var k = key.replace(/([A-Z])/g, ' $1'),
		    		k = k.replace(/^./, function(str){return str.toUpperCase()});

		        arr.push(k + ' = ' + obj[key]);
		    }
		};

		return arr.join(',');
	}
	function get_name(str){
		if(str.indexOf('http://') !=-1 || str.indexOf('https://') !=-1 || str.indexOf('www://') !=-1){
			var matches = url.match(/^https?\:\/\/(?:www\.)?([^\/?#]+)(?:[\/?#]|$)/i),
				domain = matches && matches[1];
		}
		else{
			var domain = str;
		}

	    return domain;
	}

	// Task.
	// var options = ['', mode, 'en_GB'];
	var options = [];

	// Task.
	psi(url, function(err, data){
		// Stats template.
		var stats = ['-----------------------------------',
			'Date: <%= date %>',
			'-',
			'Total Score: <%= score %>',
			'-',
			'URL: <%= url %>',
			'-',
			'Page Title: <%= title %>',
			'-',
			'Strategy / Mode: <%= mode %>',
			'-',
			'Page Stats:',
			'<%= pageStats %>',
			'-----------------------------------',
			'',
			''].join('\n');

		var dir  = get_name(url),
			file = './logs/pagespeed/' + dir;

		// Create file
		fs.ensureFile(file, function(err){
			// Task
			gulp.src(file)
			.pipe(header(stats, {
				date     : Date(),
				pageStats: convert_object(data.pageStats).split(',').join("\r\n"),
				score    : data.score,
				title    : data.title,
				mode     : mode,
				url      : data.id
			}))
			.pipe(gulp.dest('./psi/'))
			.pipe(notify({message: 'PSI task complete. Log has been recorded to: ' + file}));
		});
	});
});
<commit_msg>Fixed sourcemaps by reordering CSS task.<commit_after>/* =========================================================================== */
/* Requires & Vars
/* =========================================================================== */
// Require.
var gulp   = require('gulp'),
	args   = require('yargs').argv,
	gulpif = require('gulp-if'),
	util   = require('gulp-util'),
	notify = require('gulp-notify'),
	buffer = require('vinyl-buffer'),
	header = require('gulp-header'),
	source = require('vinyl-source-stream');

// Vars.
var version        = '1.0.0',
	src_dir        = './src/',
	dist_dir       = './src/dist/',
	is_development = (args.config == 'development') ? true : false,
	is_production  = (args.config == 'production' || args.config == undefined) ? true : false,
	error_handler  = function(err){
		// Show notification.
		gulp.src('gulpfile.js').pipe(notify({
			message: 'Error: ' + err.message
		}));
		// Show in terminal log.
		util.log(util.colors.red('Error'), err.message);
	},
	task_handler = function(err){
		// Standard error.
		error_handler(err);
		// Don't break stream.
		this.emit('end');
	}

/* =========================================================================== */
/* Combined Tasks
/* =========================================================================== */
// Task.
gulp.task('default', [
	// All states.
	'js',
	'css',
	'images',
	// Development states.
	'dalek',
	'jasmine',
	'jshint'
], function(){
	// Show notification.
	gulp.src('gulpfile.js').pipe(notify({
		message: 'Default task is complete'
	}));
});

/* =========================================================================== */
/* CSS
/* =========================================================================== */
// CSS Build File.
gulp.task('css', function(){
	// Require.
	var sass         = require('gulp-sass'),
		sourcemaps   = require('gulp-sourcemaps'),
		globbing     = require('gulp-css-globbing'),
		autoprefixer = require('gulp-autoprefixer');

	// Header template.
	var header_tpl = ['/* ==========================================================================',
		'<%= type %> Stylesheet',
		'Application Version: <%= version %>',
		'Compiled: <%= date %>',
		'========================================================================== */',
		'',
		''].join('\n');

	// Task.
	return gulp.src(dist_dir + 'css/scss/build.scss')
		.pipe(globbing({
			extensions: ['.scss']
		}))
        .pipe(sourcemaps.init())
        .pipe(sass({
	        outputStyle: (is_production) ? 'compressed' : 'expanded',
        	errLogToConsole: true,
	        onError: function(err){
	            return notify.write(err);
	        }
	    }))
		.on('error', task_handler)
        .pipe(autoprefixer({
            browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'],
            cascade: false
        }))
		.pipe(header(header_tpl, {
			type   : (is_production) ? 'Minified' : 'Unminified',
			version: version,
			date   : Date()
		}))
        .pipe(sourcemaps.write('/', {includeContent: false}))
		.pipe(gulp.dest(dist_dir + 'css'))
		.pipe(notify({message: 'CSS task complete.'}));
});

/* =========================================================================== */
/* JavaScript Compiling
/* =========================================================================== */
// JS Common Libraries & Vendors.
gulp.task('js:common', function(){
	// Require.
	var browserify = require('browserify'),
		rename     = require('gulp-rename');

	// Task.
	return browserify(dist_dir + 'js/vendor/').bundle()
		.on('error', task_handler)
		.pipe(source('index.js'))
	    .pipe(buffer())
		.pipe(rename('common.js'))
		.pipe(gulp.dest(dist_dir + 'js/compiled/'))
		.pipe(notify({message: 'JS Common task complete.'}));
});

// JS Application Files.
gulp.task('js:app', function(){
	// Require.
	var browserify = require('browserify'),
		rename     = require('gulp-rename');

	// Task.
	return browserify(dist_dir + 'js/app/').bundle()
		.on('error', task_handler)
	    .pipe(source('index.js'))
	    .pipe(buffer())
		.pipe(rename('app.js'))
		.pipe(gulp.dest(dist_dir + 'js/compiled/'))
		.pipe(notify({message: 'JS App task complete.'}));
});

// JS Build File (Concatenated App & Common).
gulp.task('js', ['js:app'], function(){
	// Require.
	var concat = require('gulp-concat'),
		uglify = require('gulp-uglify');

	// Header template.
	var header_tpl_env = ['// Set environment variable',
	'window.gulp_env = "<%= env %>";',
	'',
	''].join('\n');
	var header_tpl = ['/* ==========================================================================',
		'<%= type %> JavaScript',
		'Application Version: <%= version %>',
		'Compiled: <%= date %>',
		'========================================================================== */',
		'',
		''].join('\n');

	// Task.
	return gulp.src([dist_dir + 'js/compiled/common.js', dist_dir + 'js/compiled/app.js'])
	    .pipe(concat('build.js'))
		.pipe(header(header_tpl_env, {
			env: (is_production) ? 'production' : 'development'
		}))
		.pipe(gulpif(is_production, uglify()))
		.pipe(header(header_tpl, {
			type   : (is_production) ? 'Minified' : 'Unminified',
			version: version,
			date   : Date()
		}))
	    .pipe(gulp.dest(dist_dir + 'js/build'))
		.on('error', task_handler)
		.pipe(notify({message: 'JS Build task complete.'}));
});

/* =========================================================================== */
/* Watch
/* =========================================================================== */
gulp.task('watch', function(){
	// Run JS Master on JS and HBS file changes.
	gulp.watch([dist_dir + 'js/app/**/*.js', dist_dir + 'js/plugins/**/*.js', dist_dir + 'js/**/*.hbs'], ['js']);
	// Run CSS on SCSS file changes.
	gulp.watch(dist_dir + 'css/scss/**/*.scss', ['css']);
});

/* =========================================================================== */
/* Sync (BrowserSync)
/* =========================================================================== */
gulp.task('sync', function(){
	// Require.
	var browserSync = require('browser-sync'),
		reload      = browserSync.reload;

	// Vars.
	var url    = args.url || false,
		notify = args.notify || false,
		xip    = args.xip || true,
		https  = args.https || false;

	if(url){
		browserSync.init({
			open   : 'external',
			browser: ['google chrome'],
			notify : notify,
			https  : https,
			xip    : xip,
			proxy  : url
		});
	}
	else{
		browserSync.init({
			open   : 'external',
			browser: ['google chrome'],
			notify : notify,
			https  : https,
			xip    : xip,
			server : {
				baseDir: [src_dir]
			}
		});
	}

	// Run Browserify on JS and HBS file changes.
	gulp.watch([dist_dir + 'js/app/**/*.js', dist_dir + 'js/plugins/**/*.js', dist_dir + 'js/**/*.hbs'], ['js']);
	// Run Compass on SCSS file changes.
	gulp.watch(dist_dir + 'css/scss/**/*.scss', ['css']);
	// Reload on file changes.
	gulp.watch([
		src_dir + '**/*.html',
		src_dir + '**/*.php',
		dist_dir + 'css/build.css',
		dist_dir + 'js/build/build.js'
	], reload);
});

/* =========================================================================== */
/* Testing
/* =========================================================================== */
// Dalek - Browser Testing (Development Mode Only).
gulp.task('dalek', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Require.
	var dalek = require('gulp-dalek');

	// Files.
	var tests = [
		// dist_dir + 'js/spec/dalek/examples.js',
		dist_dir + 'js/spec/dalek/elements.js',
		dist_dir + 'js/spec/dalek/roles.js'
	];

	// Task.
	return gulp.src(tests)
		.pipe(
			dalek({
				browser : [
					'phantomjs',
					// 'chrome'
				],
				reporter: [
					'console',
					// 'html',
					// 'junit'
				]
			})
		)
		.on('error', task_handler);
});

// Jasmine - Client Testing (Development Mode Only).
gulp.task('jasmine', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Require.
	var karma = require('gulp-karma');

    // Task.
	return gulp.src(dist_dir + 'js/spec/jasmine/*')
		.pipe(karma({
			configFile: 'karma.conf.js',
			action    : 'run'
		}))
		.on('error', task_handler);
});

/* =========================================================================== */
/* Task Tools
/* =========================================================================== */
// JSHint (Development Mode Only).
gulp.task('jshint', function(){
	// Check environment.
	if(!is_development){
		if(this.seq.slice(-1)[0] == 'default'){
			util.log(util.colors.yellow('Warning: Task skipped. Not run with default profile.'));
			return;
		}
		else{
			throw new Error('This task must be run in development mode. Try running `gulp ' + this.seq.slice(-1)[0] + ' --config development`.');
		}
	}

	// Vars.
	var jshint  = require('gulp-jshint'),
		stylish = require('jshint-stylish');

    // Task.
	return gulp.src(dist_dir + 'js/app/**/*.js')
	    .pipe(jshint())
	    .pipe(jshint.reporter(stylish))
		.pipe(notify({message: 'JSHint task complete.'}));
});

// Image Minification.
gulp.task('images', function(){
	// Require.
	var imagemin = require('gulp-imagemin')
		cache	 = require('gulp-cache');

	// Task.
    return gulp.src(dist_dir + 'images/**/*')
        .pipe(cache(imagemin({
            optimizationLevel: 3,
            progressive      : true,
            interlaced       : true
        })))
        .pipe(gulp.dest(dist_dir + 'images'))
		.pipe(notify({message: 'Images task complete.'}));
});

/* =========================================================================== */
/* One Off Tools
/* =========================================================================== */
// Image Sprites.
gulp.task('sprite', function(){
	// Require.
	var sprity = require('sprity');

	// Task.
    return sprity.src({
		src         : dist_dir + 'images/icons/sprite/*.png',
		style       : dist_dir + 'css/scss/site/_sprites.scss',
		cssPath     : '../images/icons/',
		margin      : 5,
		base64      : false,
		retina      : false,
		background  : '#FFFFFF',
		orientation : 'horizontal',
		prefix      : 'css-sprite',
		name        : 'sprite',
		processor   : 'sass',
		'style-type': 'scss'
	})
    .pipe(gulpif('*.png', gulp.dest(dist_dir + 'images/icons'), gulp.dest(dist_dir + 'css/scss/site')))
	.pipe(notify({message: 'Sprite task complete.'}));
});

// App release.
gulp.task('release', function(){
	// Vars.
	var files = [
        './src/**/*.*',
        '!./src/**/*.scss',
        '!./src/dist/js/app/**/*',
        '!./src/dist/js/compiled/**/*',
        '!./src/dist/js/plugins/**/*',
        '!./src/dist/js/spec/**/*',
        '!./src/dist/js/vendor/**/*',
    ];

    // Task.
	return gulp.src(files, {base: src_dir})
		.pipe(gulp.dest('releases/release-' + version))
		.pipe(notify({message: 'Release task complete.'}));
});

// Google Page Speed Tests.
gulp.task('psi', function(){
	// Require.
	var psi = require('psi'),
		fs  = require('fs-extra');

	// Vars.
	var url  = args.url || 'http://google.com',
		mode = args.mode || 'desktop';

	// Seems to freeze without this.
	console.log('Query URL: ' + url);

	// Functions.
	function convert_object(obj){
		var arr = [];
		for(var key in obj){
		    if(obj.hasOwnProperty(key)){
		    	var k = key.replace(/([A-Z])/g, ' $1'),
		    		k = k.replace(/^./, function(str){return str.toUpperCase()});

		        arr.push(k + ' = ' + obj[key]);
		    }
		};

		return arr.join(',');
	}
	function get_name(str){
		if(str.indexOf('http://') !=-1 || str.indexOf('https://') !=-1 || str.indexOf('www://') !=-1){
			var matches = url.match(/^https?\:\/\/(?:www\.)?([^\/?#]+)(?:[\/?#]|$)/i),
				domain = matches && matches[1];
		}
		else{
			var domain = str;
		}

	    return domain;
	}

	// Task.
	// var options = ['', mode, 'en_GB'];
	var options = [];

	// Task.
	psi(url, function(err, data){
		// Stats template.
		var stats = ['-----------------------------------',
			'Date: <%= date %>',
			'-',
			'Total Score: <%= score %>',
			'-',
			'URL: <%= url %>',
			'-',
			'Page Title: <%= title %>',
			'-',
			'Strategy / Mode: <%= mode %>',
			'-',
			'Page Stats:',
			'<%= pageStats %>',
			'-----------------------------------',
			'',
			''].join('\n');

		var dir  = get_name(url),
			file = './logs/pagespeed/' + dir;

		// Create file
		fs.ensureFile(file, function(err){
			// Task
			gulp.src(file)
			.pipe(header(stats, {
				date     : Date(),
				pageStats: convert_object(data.pageStats).split(',').join("\r\n"),
				score    : data.score,
				title    : data.title,
				mode     : mode,
				url      : data.id
			}))
			.pipe(gulp.dest('./psi/'))
			.pipe(notify({message: 'PSI task complete. Log has been recorded to: ' + file}));
		});
	});
});
<|endoftext|>


<commit_before>var themename = 'humescores';

var gulp = require('gulp'),
	// Prepare and optimize code etc
	autoprefixer = require('autoprefixer'),
	browserSync = require('browser-sync').create(),
	image = require('gulp-image'),
	jshint = require('gulp-jshint'),
	postcss = require('gulp-postcss'),
	sass = require('gulp-sass'),
	sourcemaps = require('gulp-sourcemaps'),

	// Only work with new or updated files
	newer = require('gulp-newer'),

	// Name of working theme folder
	root = '../' + themename + '/',
	scss = root + 'sass/',
	js = root + 'js/',
	img = root + 'images/',
	languages = root + 'languages/';

// CSS via Sass and Autoprefixer
gulp.task('css', function() {
	return gulp.src(scss + '{style.scss,rtl.scss}')
	.pipe(sourcemaps.init())
	.pipe(sass({
		outputStyle: 'expanded',
		indentType: 'tab',
		indentWidth: '1'
	}).on('error', sass.logError))
	.pipe(postcss([
		autoprefixer('last 2 versions', '> 1%')
	]))
	.pipe(sourcemaps.write(scss + 'maps'))
	.pipe(gulp.dest(root));
});

// Optimize images through gulp-image
gulp.task('images', function() {
	return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
	.pipe(newer(img))
	.pipe(image())
	.pipe(gulp.dest(img));
});

// JavaScript
gulp.task('javascript', function() {
	return gulp.src([js + '*.js'])
	.pipe(jshint())
	.pipe(jshint.reporter('default'))
	.pipe(gulp.dest(js));
});

// Watch everything
gulp.task('watch', function() {
	browserSync.init({
		open: 'external',
		proxy: 'humescores.dev',
		port: 8080
	});
	gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
	gulp.watch(js + '**/*.js', ['javascript']);
	gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
	gulp.watch(root + '**/*').on('change', browserSync.reload);
});

// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
<commit_msg>Update Gulpfile.js<commit_after>var themename = 'dragonscores';

var gulp = require('gulp'),
	// Prepare and optimize code etc
	autoprefixer = require('autoprefixer'),
	browserSync = require('browser-sync').create(),
	image = require('gulp-image'),
	jshint = require('gulp-jshint'),
	postcss = require('gulp-postcss'),
	sass = require('gulp-sass'),
	sourcemaps = require('gulp-sourcemaps'),

	// Only work with new or updated files
	newer = require('gulp-newer'),

	// Name of working theme folder
	root = '../' + themename + '/',
	scss = root + 'sass/',
	js = root + 'js/',
	img = root + 'images/',
	languages = root + 'languages/';

// CSS via Sass and Autoprefixer
gulp.task('css', function() {
	return gulp.src(scss + '{style.scss,rtl.scss}')
	.pipe(sourcemaps.init())
	.pipe(sass({
		outputStyle: 'expanded',
		indentType: 'tab',
		indentWidth: '1'
	}).on('error', sass.logError))
	.pipe(postcss([
		autoprefixer('last 2 versions', '> 1%')
	]))
	.pipe(sourcemaps.write(scss + 'maps'))
	.pipe(gulp.dest(root));
});

// Optimize images through gulp-image
gulp.task('images', function() {
	return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
	.pipe(newer(img))
	.pipe(image())
	.pipe(gulp.dest(img));
});

// JavaScript
gulp.task('javascript', function() {
	return gulp.src([js + '*.js'])
	.pipe(jshint())
	.pipe(jshint.reporter('default'))
	.pipe(gulp.dest(js));
});

// Watch everything
gulp.task('watch', function() {
	browserSync.init({
		open: 'external',
		proxy: 'humescores.dev',
		port: 8080
	});
	gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
	gulp.watch(js + '**/*.js', ['javascript']);
	gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
	gulp.watch(root + '**/*').on('change', browserSync.reload);
});

// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>// gulp libs
var gulp = require('gulp');
var release = require('gulp-github-release');
var gutil = require('gulp-util');

var TAG_ERR_TEXT = 'Unable to resolve GIT TAG from environment variable GIT_LATEST_TAG';

gulp.task('release', function (callback) {
	var latestTag = process.env.GIT_LATEST_TAG;
	if (latestTag)
	{
		gutil.log('Using release tag: ' + latestTag);
		return gulp
				.src('./dist/deploy.zip')
				.pipe(release({
					tag: latestTag,
					name: 'publish release ' + latestTag,     // if missing, it will be the same as the tag
					notes: 'very good!',                // if missing it will be left undefined
					draft: false,                       // if missing it's false
					prerelease: false,                  // if missing it's false
					manifest: require('./package.json') // package.json from which default values will be extracted if they're missing
				}));
	}
	else
	{
		callback(TAG_ERR_TEXT);
	}
});

gulp.task('default', ['release']);
<commit_msg>Added task for git tag resolving using child_process .exec()<commit_after>// gulp libs
var gulp = require('gulp');
var release = require('gulp-github-release');
var gutil = require('gulp-util');
var exec = require('child_process').exec;

var latestReleaseTag;

gulp.task('gittag', function () {
	return new Promise(function (resolve, reject) {
		// get the latest tag with "release-" prefix
		var command = 'git describe --tags --abbrev^=0 --match release-*';
		exec(command, function (error, stdout, stderr) {
			var outText = '' + stdout,
				errText = '' + stderr;

			if (error || errText || !outText)
			{
				reject();
			}
			else
			{
				latestReleaseTag = outText.trim();
				if (latestReleaseTag)
				{
					resolve();
				}
				else
				{
					gutil.log(gutil.colors.red('GIT tag not found - aborting!'));
					reject();
				}
			}
		});
	});
});

gulp.task('release:novar', ['gittag'], function (callback) {
	gutil.log('Using release tag: ' + latestReleaseTag);
	if (!process.env.GITHUB_TOKEN)
	{
		callback('Unable to resolve GitHub authentication token from environment variable GITHUB_TOKEN');
	}
	else
	{
		return gulp
				.src('./dist/deploy.zip')
				.pipe(release({
					tag: latestReleaseTag,
					name: 'publish release ' + latestReleaseTag,     // if missing, it will be the same as the tag
					notes: 'very good!',                // if missing it will be left undefined
					draft: false,                       // if missing it's false
					prerelease: false,                  // if missing it's false
					manifest: require('./package.json') // package.json from which default values will be extracted if they're missing
				}));
	}
});

// depends on environment variable set from tag.bat
gulp.task('release', function (callback) {
	var latestTag = process.env.GIT_LATEST_TAG;
	if (!process.env.GITHUB_TOKEN)
	{
		callback('Unable to resolve GitHub authentication token from environment variable GITHUB_TOKEN');
	}
	if (latestTag)
	{
		gutil.log('Using release tag: ' + latestTag);
		return gulp
				.src('./dist/deploy.zip')
				.pipe(release({
					tag: latestTag,
					name: 'publish release ' + latestTag,     // if missing, it will be the same as the tag
					notes: 'very good!',                // if missing it will be left undefined
					draft: false,                       // if missing it's false
					prerelease: false,                  // if missing it's false
					manifest: require('./package.json') // package.json from which default values will be extracted if they're missing
				}));
	}
	else
	{
		callback('Unable to resolve GIT tag from environment variable GIT_LATEST_TAG');
	}
});

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


<commit_before>// Generated on 2017-03-22 using generator-mendix 2.0.4 :: git+https://github.com/mendix/generator-mendix.git
/*jshint -W069,-W097*/
"use strict";

// In case you seem to have trouble starting Mendix through `gulp modeler`, you might have to set the path to the Mendix application, otherwise leave both values as they are
var MODELER_PATH = null;
var MODELER_ARGS = "/file:{path}";

/********************************************************************************
 * Do not edit anything below, unless you know what you are doing
 ********************************************************************************/
var gulp = require("gulp"),
    zip = require("gulp-zip"),
    del = require("del"),
    newer = require("gulp-newer"),
    gutil = require("gulp-util"),
    gulpif = require("gulp-if"),
    jsonTransform = require("gulp-json-transform"),
    intercept = require("gulp-intercept"),
    argv = require("yargs").argv,
    widgetBuilderHelper = require("widgetbuilder-gulp-helper"),
    jsValidate = require("gulp-jsvalidate");

var pkg = require("./package.json"),
    paths = widgetBuilderHelper.generatePaths(pkg),
    xmlversion = widgetBuilderHelper.xmlversion;

gulp.task("default", function() {
    gulp.watch("./src/**/*", ["compress"]);
    gulp.watch("./src/**/*.js", ["copy:js"]);
});

gulp.task("clean", function () {
    return del([
        paths.WIDGET_TEST_DEST,
        paths.WIDGET_DIST_DEST
    ], { force: true });
});

gulp.task("compress", ["clean"], function () {
    return gulp.src("src/**/*")
        .pipe(zip(pkg.name + ".mpk"))
        .pipe(gulp.dest(paths.TEST_WIDGETS_FOLDER))
        .pipe(gulp.dest("dist"));
});

gulp.task("copy:js", function () {
    return gulp.src(["./src/**/*.js"])
        .pipe(jsValidate())
        .pipe(newer(paths.TEST_WIDGETS_DEPLOYMENT_FOLDER))
        .pipe(gulp.dest(paths.TEST_WIDGETS_DEPLOYMENT_FOLDER));
});

gulp.task("version:xml", function () {
    return gulp.src(paths.PACKAGE_XML)
        .pipe(xmlversion(argv.n))
        .pipe(gulp.dest("./src/"));
});

gulp.task("version:json", function () {
    return gulp.src("./package.json")
        .pipe(gulpif(typeof argv.n !== "undefined", jsonTransform(function(data) {
            data.version = argv.n;
            return data;
        }, 2)))
        .pipe(gulp.dest("./"));
});

gulp.task("icon", function (cb) {
    var icon = (typeof argv.file !== "undefined") ? argv.file : "./icon.png";
    console.log("\nUsing this file to create a base64 string: " + gutil.colors.cyan(icon));
    gulp.src(icon)
        .pipe(intercept(function (file) {
            console.log("\nCopy the following to your " + pkg.name + ".xml (after description):\n\n" + gutil.colors.cyan("<icon>") + file.contents.toString("base64") + gutil.colors.cyan("<\/icon>") + "\n");
            cb();
        }));
});

gulp.task("folders", function () {
    paths.showPaths(); return;
});

gulp.task("modeler", function (cb) {
    widgetBuilderHelper.runmodeler(MODELER_PATH, MODELER_ARGS, paths.TEST_PATH, cb);
});

gulp.task("build", ["compress"]);
gulp.task("version", ["version:xml", "version:json"]);
<commit_msg>added build:prod task<commit_after>// Generated on 2017-03-22 using generator-mendix 2.0.4 :: git+https://github.com/mendix/generator-mendix.git
/*jshint -W069,-W097*/
"use strict";

// In case you seem to have trouble starting Mendix through `gulp modeler`, you might have to set the path to the Mendix application, otherwise leave both values as they are
var MODELER_PATH = null;
var MODELER_ARGS = "/file:{path}";

/********************************************************************************
 * Do not edit anything below, unless you know what you are doing
 ********************************************************************************/
var gulp = require("gulp"),
    zip = require("gulp-zip"),
    del = require("del"),
    newer = require("gulp-newer"),
    gutil = require("gulp-util"),
    gulpif = require("gulp-if"),
    jsonTransform = require("gulp-json-transform"),
    intercept = require("gulp-intercept"),
    argv = require("yargs").argv,
    widgetBuilderHelper = require("widgetbuilder-gulp-helper"),
    jsValidate = require("gulp-jsvalidate"),
    minify = require('gulp-minify'),
    gulpCopy = require('gulp-copy'),
    fs = require("fs-extra");

var pkg = require("./package.json"),
    paths = widgetBuilderHelper.generatePaths(pkg),
    xmlversion = widgetBuilderHelper.xmlversion;

gulp.task("default", function () {
    gulp.watch("./src/**/*", ["compress"]);
    gulp.watch("./src/**/*.js", ["copy:js"]);
});

gulp.task("clean", function () {
    return del([
        paths.WIDGET_TEST_DEST,
        paths.WIDGET_DIST_DEST
    ], {
        force: true
    });
});

gulp.task("compress", ["clean"], function () {
    return gulp.src("src/**/*")
        .pipe(zip(pkg.name + ".mpk"))
        .pipe(gulp.dest(paths.TEST_WIDGETS_FOLDER))
        .pipe(gulp.dest("dist"));
});

gulp.task("copy:js", function () {
    return gulp.src(["./src/**/*.js"])
        .pipe(jsValidate())
        .pipe(newer(paths.TEST_WIDGETS_DEPLOYMENT_FOLDER))
        .pipe(gulp.dest(paths.TEST_WIDGETS_DEPLOYMENT_FOLDER));
});

gulp.task("version:xml", function () {
    return gulp.src(paths.PACKAGE_XML)
        .pipe(xmlversion(argv.n))
        .pipe(gulp.dest("./src/"));
});

gulp.task("version:json", function () {
    return gulp.src("./package.json")
        .pipe(gulpif(typeof argv.n !== "undefined", jsonTransform(function (data) {
            data.version = argv.n;
            return data;
        }, 2)))
        .pipe(gulp.dest("./"));
});

gulp.task("icon", function (cb) {
    var icon = (typeof argv.file !== "undefined") ? argv.file : "./icon.png";
    console.log("\nUsing this file to create a base64 string: " + gutil.colors.cyan(icon));
    gulp.src(icon)
        .pipe(intercept(function (file) {
            console.log("\nCopy the following to your " + pkg.name + ".xml (after description):\n\n" + gutil.colors.cyan("<icon>") + file.contents.toString("base64") + gutil.colors.cyan("<\/icon>") + "\n");
            cb();
        }));
});

gulp.task("folders", function () {
    paths.showPaths();
    return;
});

gulp.task("modeler", function (cb) {
    widgetBuilderHelper.runmodeler(MODELER_PATH, MODELER_ARGS, paths.TEST_PATH, cb);
});

gulp.task("build:prod", function () {
    try {
        fs.copySync('src', 'build'); // copy everthing
        gulp.src(['src/**/*.js']) // overwrite .js files with the minified ones.
            .pipe(minify({
                ext: {
                    min: ".js"
                },
                noSource: true,
                mangle: true
            }))
            .pipe(gulp.dest('build'));
        return gulp.src("build/**/*")
            .pipe(zip(pkg.name + ".mpk"))
            .pipe(gulp.dest(paths.TEST_WIDGETS_FOLDER))
            .pipe(gulp.dest("build"))
            .pipe(gulp.dest("dist"));
    } catch (e) {
        console.error(e);
    }
});<|endoftext|>


<commit_before>"use strict";

var walk = require('walk');
var fs = require('fs');
var path = require("path");
var util = require("util");
var through = require('through2');
var mkdirp = require('mkdirp');

var namespace_tree = {};
var suffix = ".js";
var namespace_regex = /^\/\/namespace\s[\\]?(\w[\\]?)*/i;
var autoload_regex = /autoload\(['"]\\([\w.][\\]?)*['"]\)/ig;

var status = {
	fileWalker: true,
	openStreams: 0
};

function logMap() {
	console.log(util.inspect(namespace_tree, {depth: null, colors: true}));
}

function buildMap(source, destination) {
	console.log("Building map");
	var fileWalker = walk.walk(source, {followLinks: false});

	fileWalker.on('file', function (root, fileStats, next) {
		if (fileStats.name.indexOf(suffix, fileStats.name.length - suffix.length) !== -1) {
			status.openStreams++;
			mkdirp.sync(path.join(destination, root));

			var stream = fs.createReadStream(path.join(root, fileStats.name), {encoding: 'utf-8'});

			stream.on('data', function (data) {

				stream.pause();

				var namespace = data.match(namespace_regex);

				//there is a namespace on the first line
				if (namespace !== null) {

					//remove everything up until the end of the word namespace, and then trim it
					namespace = (""+namespace[0].substring(namespace[0].indexOf("namespace")+9)).trim();

					//remove backslash if it exists
					if(namespace.charAt(0) === "\\"){
						namespace = namespace.substring(1);
					}

					//split up the namespace into its parts
					var namespace_arr = namespace.split('\\');

					var tree = namespace_tree;

					//for each part of the namespace, traverse the tree
					for (var i = 0; i < namespace_arr.length; i++) {

						//and get the branch of the tree we want to work with, and
						//if it doesnt exist, make it an empty object
						tree = tree[namespace_arr[i]] = tree[namespace_arr[i]] || {};
					}

					//make sure there is always a files array
					if (!('files' in tree)) {
						tree.files = [];
					}

					//push the file we found
					tree.files.push({
						name: fileStats.name.substr(0, fileStats.name.lastIndexOf(".")),
						path: './' + path.join(root, fileStats.name)
					});
				}

				stream.destroy();
			});

			stream.on('error', function (error) {
				console.log(error);
				stream.destroy();
			});

			stream.on('end', function () {
				status.openStreams--;

				if (!status.fileWalker && status.openStreams === 0) {
					logMap();
					build(source, destination);
				}
			});
		}
		next();
	});

	fileWalker.on('end', function () {
		status.fileWalker = false;
	});
}

function transformer(root, fileStats) {

	var stream = through.obj(function (data, encoding, next) {

		var streamer = through();
		streamer.on('error', this.emit.bind(this, 'error'));

		this.push(data.replace(autoload_regex, function (data) {

			var tree = JSON.parse(JSON.stringify(namespace_tree));
			var filePath = '';

			try {
				var namespace_arr = data.match(/\\([\w.][\\]?)*/i)[0].split('\\').splice(1);
				var file = namespace_arr.pop();

				if (namespace_arr[0] === '') {
					namespace_arr.shift();
				}
				for (var i = 0; i < namespace_arr.length; i++) {
					tree = tree[namespace_arr[i]];
				}

				for (var i = 0; i < tree.files.length; i++) {
					if (tree.files[i].name === file) {
						filePath = "./"+path.relative(path.join(root), tree.files[i].path);
					}
				}

			} catch (err) {
				console.log("There was an error building the file path for " + data);
				console.log(err);
			}

			return "require('" + filePath + "')";
		}));

		next();
	});

	return stream;
}

function build(source, destination) {

	status.fileWalker = true;

	var fileWalker = walk.walk(source, {followLinks: false});

	fileWalker.on('file', function (root, fileStats, next) {

		if (fileStats.name.indexOf(suffix, fileStats.name.length - suffix.length) !== -1) {

			status.openStreams++;

			var stream = fs.createReadStream(path.join(root, fileStats.name), {encoding: 'utf-8'});

			stream.pipe(transformer(root, fileStats)).pipe(fs.createWriteStream(path.join(destination, root, fileStats.name)));
		}

		next();
	});

	fileWalker.on('end', function () {
		status.fileWalker = false;
	});
}

function autoload(source, destination) {
	buildMap(source, destination);
}

module.exports = autoload;<commit_msg>Commited the sad left out file from last commit<commit_after>"use strict";

var walk = require('walk');
var fs = require('fs');
var path = require("path");
var util = require("util");
var through = require('through2');
var mkdirp = require('mkdirp');

var namespace_tree = {};
var happyContextualTree = {};
var suffix = ".js";
var namespace_regex = /^\/\/namespace\s[\\]?(\w[\\]?)*/i;
var autoload_regex = /autoload\(['"][\\]?([\w.][\\]?)*['"]\)/ig;

var status = {
	fileWalker: true,
	openStreams: 0
};

function logMap() {
	console.log(util.inspect(namespace_tree, {depth: null, colors: true}));
	console.log(util.inspect(happyContextualTree, {depth: null, colors: true}));
}

//Sets the namespace contect for the given path
//This is a complete waste of a function. However...
//I've had a little alcohol.
function doTheThing(root, fileStats, namespace) {
	happyContextualTree[path.normalize(path.join(root, fileStats.name))] = namespace;
}

function buildMap(source, destination) {
	console.log("Building map");
	var fileWalker = walk.walk(source, {followLinks: false});

	fileWalker.on('file', function (root, fileStats, next) {
		if (fileStats.name.indexOf(suffix, fileStats.name.length - suffix.length) !== -1) {
			status.openStreams++;
			mkdirp.sync(path.join(destination, root));

			var stream = fs.createReadStream(path.join(root, fileStats.name), {encoding: 'utf-8'});

			stream.on('data', function (data) {

				stream.pause();

				var namespace = data.match(namespace_regex);

				//there is a namespace on the first line
				if (namespace !== null) {

					//remove everything up until the end of the word namespace, and then trim it
					namespace = ("" + namespace[0].substring(namespace[0].indexOf("namespace") + 9)).trim();

					//remove backslash if it exists
					if (namespace.charAt(0) === "\\") {
						namespace = namespace.substring(1);
					}

					//split up the namespace into its parts
					var namespace_arr = namespace.split('\\');

					doTheThing(root, fileStats, namespace_arr);

					var tree = namespace_tree;

					//for each part of the namespace, traverse the tree
					for (var i = 0; i < namespace_arr.length; i++) {

						//and get the branch of the tree we want to work with, and
						//if it doesnt exist, make it an empty object
						tree = tree[namespace_arr[i]] = tree[namespace_arr[i]] || {};
					}

					//make sure there is always a files array
					if (!('files' in tree)) {
						tree.files = [];
					}

					//push the file we found
					tree.files.push({
						name: fileStats.name.substr(0, fileStats.name.lastIndexOf(".")),
						path: './' + path.join(root, fileStats.name)
					});
				} else {
					doTheThing(root, fileStats, []);
				}

				stream.destroy();
			});

			stream.on('error', function (error) {
				console.log(error);
				stream.destroy();
			});

			stream.on('end', function () {
				status.openStreams--;

				if (!status.fileWalker && status.openStreams === 0) {
					logMap();
					build(source, destination);
				}
			});
		}
		next();
	});

	fileWalker.on('end', function () {
		status.fileWalker = false;
	});
}

function transformer(root, fileStats) {

	var stream = through.obj(function (data, encoding, next) {

		var streamer = through();
		streamer.on('error', this.emit.bind(this, 'error'));

		//get the current namespace context as array
		var happyContext = happyContextualTree[path.normalize(path.join(root, fileStats.name))];

		this.push(data.replace(autoload_regex, function (data) {

			var tree = JSON.parse(JSON.stringify(namespace_tree));
			var filePath = '';

			try {
				var namespace_arr = data.substring(10, data.length - 2).split('\\');

				var relative = true;
				var file = namespace_arr.pop();

				if (namespace_arr[0] === '') {
					namespace_arr.shift();
					relative = false;
				}

				if (relative) {
					for (var i = 0; i < happyContext.length; i++) {
						tree = tree[happyContext[i]];
					}
				}

				for (var i = 0; i < namespace_arr.length; i++) {
					tree = tree[namespace_arr[i]];
				}

				for (var i = 0; i < tree.files.length; i++) {
					if (tree.files[i].name === file) {
						filePath = "./" + path.relative(path.join(root), tree.files[i].path);
					}
				}

			} catch (err) {
				console.log("There was an error building the file path for " + data);
				console.log(err);
			}

			return "require('" + filePath + "')";
		}));

		next();
	});

	return stream;
}

function build(source, destination) {

	status.fileWalker = true;

	var fileWalker = walk.walk(source, {followLinks: false});

	fileWalker.on('file', function (root, fileStats, next) {

		if (fileStats.name.indexOf(suffix, fileStats.name.length - suffix.length) !== -1) {

			status.openStreams++;

			var stream = fs.createReadStream(path.join(root, fileStats.name), {encoding: 'utf-8'});

			stream.pipe(transformer(root, fileStats)).pipe(fs.createWriteStream(path.join(destination, root, fileStats.name)));
		}

		next();
	});

	fileWalker.on('end', function () {
		status.fileWalker = false;
	});
}

function autoload(source, destination) {
	buildMap(source, destination);
}

module.exports = autoload;<|endoftext|>


<commit_before><commit_msg>逗号运算符 & Comma operator<commit_after><|endoftext|>


<commit_before>describe("chorus.dialogs.Attach", function() {
    beforeEach(function() {
        this.dialog = new chorus.dialogs.Attach({ workspaceId : "33" });
        this.dialog.collectionClass = chorus.collections.Base;
        this.dialog.submitButtonTranslationKey = "loading";
        this.dialog.emptyListTranslationKey = "test.mouse";
        this.dialog.collection = this.dialog.resource = new chorus.collections.Base([fixtures.user(), fixtures.user()]);
        this.dialog.collection.loaded = true;
    });

    context("when selectedAttachments have been passed", function() {
        beforeEach(function() {
            var collection = new chorus.collections.Base([fixtures.user(), fixtures.user()]);
            this.dialog = new chorus.dialogs.Attach({ workspaceId : '33', selectedAttachments: collection});
            this.dialog.collection = this.dialog.resource = collection;
            this.dialog.collection.loaded = true;
            this.dialog.submitButtonTranslationKey = "loading";
            this.dialog.render();
        });

        it("renders them as selected", function() {
            expect(this.dialog.$("li").eq(0)).toHaveClass("selected");
            expect(this.dialog.$("li").eq(1)).toHaveClass("selected");
        });
    });

    it("when there are no attachable items", function() {
        this.dialog.collection.reset();
        this.dialog.render();

        expect(this.dialog.$(".collection_list")).toContainTranslation("test.mouse");
    });

    describe("render", function() {
        beforeEach(function() {
            this.dialog.collectionModelContext = function() {
                return {
                    iconUrl: '/image.png',
                    name: 'my name'
                }
            }
            this.dialog.render();
        });

        it("renders an item for each collection entry", function() {
            expect(this.dialog.$("li").length).toBe(this.dialog.collection.length);
        })

        it("includes an image for each entry", function() {
            var images = this.dialog.$(".collection_list img");
            expect(images.length).toBe(this.dialog.collection.length);
            expect(images.eq(0)).toHaveAttr("src", '/image.png');
        });

        it("includes a name for each entry", function() {
            var names = this.dialog.$('.name');
            expect(names.length).toBe(this.dialog.collection.length);
            expect(names.eq(0)).toContainText("my name");
        })

        it("has a close window button that cancels the dialog", function() {
            expect(this.dialog.$("button.cancel").length).toBe(1);
        });

        it("has the 'Attach File' button disabled by default", function() {
            expect(this.dialog.$('button.submit')).toBeDisabled();
        });
    });

    describe("selecting attachments", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(0).click();
            this.dialog.$("li").eq(1).click();
        });

        it("add class selected", function() {
            expect(this.dialog.$("li").eq(0)).toHaveClass("selected");
            expect(this.dialog.$("li").eq(1)).toHaveClass("selected");
        });

        it("enables the submit button", function() {
            expect(this.dialog.$('button.submit')).not.toBeDisabled();
        });

        context("clicking a previously selected attachment", function() {
            beforeEach(function() {
                this.dialog.$("li").eq(0).click();
            });

            it("removes class selected when user click previously selected attachment", function() {
                expect(this.dialog.$("li").eq(0)).not.toHaveClass("selected");
            });

            it("disable the submit button if it was the last selected item", function() {
                expect(this.dialog.$('li.selected').length).toBeGreaterThan(0);
                expect(this.dialog.$('button.submit')).not.toBeDisabled();
                this.dialog.$("li.selected").click();
                expect(this.dialog.$('li.selected').length).toBe(0);
                expect(this.dialog.$('button.submit')).toBeDisabled();
            });
        });

    });

    describe("submit", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(1).click();
        });

        it("populates the selectedAttachments attribute", function() {
            this.dialog.$("button.submit").click();
            expect(this.dialog.selectedAttachments.length).toBe(1);
            var model = this.dialog.selectedAttachments.models[0];
            expect(model).toBe(this.dialog.collection.get(model.id));
        })

        it("dismisses the dialog", function() {
            spyOnEvent($(document), "close.facebox");

            this.dialog.$("button.submit").click();

            expect("close.facebox").toHaveBeenTriggeredOn($(document))
        });

        it("triggers the 'selectedEvent' event on itself, passing in the selected attachments", function() {
            this.selectedSpy = jasmine.createSpy("attachmentsSelected");
            this.dialog.selectedEvent = 'something:selected'
            this.dialog.bind("something:selected", this.selectedSpy);

            this.dialog.$("button.submit").click();

            expect(this.selectedSpy).toHaveBeenCalledWith(this.dialog.selectedAttachments);
        });
    });

    describe("cancel", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(1).click();
            this.dialog.$("button.cancel").click();
        });

        it("should not populate selected attachments", function() {
            expect(this.dialog.selectedAttachments).not.toExist();
        });
    });
});
<commit_msg>eliminated console error due to missing /image.png<commit_after>describe("chorus.dialogs.Attach", function() {
    beforeEach(function() {
        this.dialog = new chorus.dialogs.Attach({ workspaceId : "33" });
        this.dialog.collectionClass = chorus.collections.Base;
        this.dialog.submitButtonTranslationKey = "loading";
        this.dialog.emptyListTranslationKey = "test.mouse";
        this.dialog.collection = this.dialog.resource = new chorus.collections.Base([fixtures.user(), fixtures.user()]);
        this.dialog.collection.loaded = true;
    });

    context("when selectedAttachments have been passed", function() {
        beforeEach(function() {
            var collection = new chorus.collections.Base([fixtures.user(), fixtures.user()]);
            this.dialog = new chorus.dialogs.Attach({ workspaceId : '33', selectedAttachments: collection});
            this.dialog.collection = this.dialog.resource = collection;
            this.dialog.collection.loaded = true;
            this.dialog.submitButtonTranslationKey = "loading";
            this.dialog.render();
        });

        it("renders them as selected", function() {
            expect(this.dialog.$("li").eq(0)).toHaveClass("selected");
            expect(this.dialog.$("li").eq(1)).toHaveClass("selected");
        });
    });

    it("when there are no attachable items", function() {
        this.dialog.collection.reset();
        this.dialog.render();

        expect(this.dialog.$(".collection_list")).toContainTranslation("test.mouse");
    });

    describe("render", function() {
        beforeEach(function() {
            this.dialog.collectionModelContext = function() {
                return {
                    iconUrl: '/emclogo.png',
                    name: 'my name'
                }
            }
            this.dialog.render();
        });

        it("renders an item for each collection entry", function() {
            expect(this.dialog.$("li").length).toBe(this.dialog.collection.length);
        })

        it("includes an image for each entry", function() {
            var images = this.dialog.$(".collection_list img");
            expect(images.length).toBe(this.dialog.collection.length);
            expect(images.eq(0)).toHaveAttr("src", '/emclogo.png');
        });

        it("includes a name for each entry", function() {
            var names = this.dialog.$('.name');
            expect(names.length).toBe(this.dialog.collection.length);
            expect(names.eq(0)).toContainText("my name");
        })

        it("has a close window button that cancels the dialog", function() {
            expect(this.dialog.$("button.cancel").length).toBe(1);
        });

        it("has the 'Attach File' button disabled by default", function() {
            expect(this.dialog.$('button.submit')).toBeDisabled();
        });
    });

    describe("selecting attachments", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(0).click();
            this.dialog.$("li").eq(1).click();
        });

        it("add class selected", function() {
            expect(this.dialog.$("li").eq(0)).toHaveClass("selected");
            expect(this.dialog.$("li").eq(1)).toHaveClass("selected");
        });

        it("enables the submit button", function() {
            expect(this.dialog.$('button.submit')).not.toBeDisabled();
        });

        context("clicking a previously selected attachment", function() {
            beforeEach(function() {
                this.dialog.$("li").eq(0).click();
            });

            it("removes class selected when user click previously selected attachment", function() {
                expect(this.dialog.$("li").eq(0)).not.toHaveClass("selected");
            });

            it("disable the submit button if it was the last selected item", function() {
                expect(this.dialog.$('li.selected').length).toBeGreaterThan(0);
                expect(this.dialog.$('button.submit')).not.toBeDisabled();
                this.dialog.$("li.selected").click();
                expect(this.dialog.$('li.selected').length).toBe(0);
                expect(this.dialog.$('button.submit')).toBeDisabled();
            });
        });

    });

    describe("submit", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(1).click();
        });

        it("populates the selectedAttachments attribute", function() {
            this.dialog.$("button.submit").click();
            expect(this.dialog.selectedAttachments.length).toBe(1);
            var model = this.dialog.selectedAttachments.models[0];
            expect(model).toBe(this.dialog.collection.get(model.id));
        })

        it("dismisses the dialog", function() {
            spyOnEvent($(document), "close.facebox");

            this.dialog.$("button.submit").click();

            expect("close.facebox").toHaveBeenTriggeredOn($(document))
        });

        it("triggers the 'selectedEvent' event on itself, passing in the selected attachments", function() {
            this.selectedSpy = jasmine.createSpy("attachmentsSelected");
            this.dialog.selectedEvent = 'something:selected'
            this.dialog.bind("something:selected", this.selectedSpy);

            this.dialog.$("button.submit").click();

            expect(this.selectedSpy).toHaveBeenCalledWith(this.dialog.selectedAttachments);
        });
    });

    describe("cancel", function() {
        beforeEach(function() {
            this.dialog.render();
            this.dialog.$("li").eq(1).click();
            this.dialog.$("button.cancel").click();
        });

        it("should not populate selected attachments", function() {
            expect(this.dialog.selectedAttachments).not.toExist();
        });
    });
});
<|endoftext|>


<commit_before>import { iconIFrame } from '../../locators';

Then('background color is set to {string}', (color) => {
  iconIFrame().should('have.css', 'background-color', color);
});

Then('Icon height is set to {string}', (height) => {
  iconIFrame().should('have.css', 'height', height);
});

Then('radius is set to {string}', (radius) => {
  iconIFrame().should('have.css', 'border-bottom-left-radius', radius)
    .and('have.css', 'border-bottom-right-radius', radius)
    .and('have.css', 'border-top-left-radius', radius)
    .and('have.css', 'border-top-right-radius', radius);
});
<commit_msg>test(icon): remove not used methods<commit_after><|endoftext|>


<commit_before>describe("Jax.MatrixStack", function() {
  var stack;

  beforeEach(function() { stack = new Jax.MatrixStack(); });

  it('should return a model matrix', function() { expect(stack.getModelMatrix()).toBeTruthy(); });
  it('should return a view matrix', function() { expect(stack.getViewMatrix()).toBeTruthy(); });
  it('should return a proj matrix', function() { expect(stack.getProjectionMatrix()).toBeTruthy(); });
  it('should return a mvp matrix', function() {
    expect(stack.getInverseModelViewMatrix()).toBeTruthy();
  });

  describe("with a pushed matrix", function() {
    beforeEach(function() { stack.push(); });

    it('should return a mvp matrix', function() {
      expect(stack.getInverseModelViewMatrix()).toBeTruthy();
    });

    it('should return a model matrix', function() { expect(stack.getModelMatrix()).toBeTruthy(); });
    it('should return a view matrix', function() { expect(stack.getViewMatrix()).toBeTruthy(); });
    it('should return a proj matrix', function() { expect(stack.getProjectionMatrix()).toBeTruthy(); });

    describe("translate", function() {
      beforeEach(function() { stack.loadViewMatrix(GLMatrix.mat4.translate(GLMatrix.mat4.create(), mat4.IDENTITY, [1,1,1])); });

      it("should not be an identity matrix", function() { expect(stack.getViewMatrix()).not.toEqualMatrix(mat4.IDENTITY); });

      it("should produce coords relative to eye", function() {
        var vec = vec3.transformMat4([], [0,0,0], stack.getInverseViewMatrix());
        expect(vec).toEqualVector([-1,-1,-1]);
      });
    });

    it("should revert when popped", function() {
      GLMatrix.mat4.copy(stack.getModelMatrix(), [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]);
      stack.pop();
      expect(stack.getModelMatrix()).toEqualVector(GLMatrix.mat4.identity(GLMatrix.mat4.create()));
    });
  });
});
<commit_msg>updates for gl-matrix 2<commit_after>describe("Jax.MatrixStack", function() {
  var stack;

  beforeEach(function() { stack = new Jax.MatrixStack(); });

  it('should return a model matrix', function() { expect(stack.getModelMatrix()).toBeTruthy(); });
  it('should return a view matrix', function() { expect(stack.getViewMatrix()).toBeTruthy(); });
  it('should return a proj matrix', function() { expect(stack.getProjectionMatrix()).toBeTruthy(); });
  it('should return a mvp matrix', function() {
    expect(stack.getInverseModelViewMatrix()).toBeTruthy();
  });

  describe("with a pushed matrix", function() {
    beforeEach(function() { stack.push(); });

    it('should return a mvp matrix', function() {
      expect(stack.getInverseModelViewMatrix()).toBeTruthy();
    });

    it('should return a model matrix', function() { expect(stack.getModelMatrix()).toBeTruthy(); });
    it('should return a view matrix', function() { expect(stack.getViewMatrix()).toBeTruthy(); });
    it('should return a proj matrix', function() { expect(stack.getProjectionMatrix()).toBeTruthy(); });

    describe("translate", function() {
      beforeEach(function() { stack.loadViewMatrix(GLMatrix.mat4.translate(GLMatrix.mat4.create(), mat4.IDENTITY, [1,1,1])); });

      it("should not be an identity matrix", function() { expect(stack.getViewMatrix()).not.toEqualMatrix(mat4.IDENTITY); });

      it("should produce coords relative to eye", function() {
        var vec = GLMatrix.vec3.transformMat4([], [0,0,0], stack.getInverseViewMatrix());
        expect(vec).toEqualVector([-1,-1,-1]);
      });
    });

    it("should revert when popped", function() {
      GLMatrix.mat4.copy(stack.getModelMatrix(), [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]);
      stack.pop();
      expect(stack.getModelMatrix()).toEqualVector(GLMatrix.mat4.identity(GLMatrix.mat4.create()));
    });
  });
});
<|endoftext|>


<commit_before>// Code goes here

var myApp = angular.module('MyApp', ['angularUtils.directives.dirPagination','ngMap']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 5;
  $scope.items = [];

 $http.get("entities.json")
    .then(function(response) {
        $scope.items = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<commit_msg>Update app.js<commit_after>// Code goes here

var myApp = angular.module('MyApp', ['angularUtils.directives.dirPagination','ngMap']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];

 $http.get("entities.json")
    .then(function(response) {
        $scope.items = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<|endoftext|>