<commit_before>const minimist = require('minimist'),
    path = require('path'),
    gulp = require('gulp'),
    del = require('del'),
    zip = require('gulp-zip'),
    concat = require('gulp-concat'),
    cssnano = require('gulp-cssnano'),
    connect = require('gulp-connect'),
    rollupCfg = require('./build/rollup.config'),
    BundleHelper = require('maptalks-build-helpers').BundleHelper,
    Server = require('karma').Server,
    package = require('./package.json');

const rollupWatch = rollupCfg.watch;
const bundler = new BundleHelper(package);

const knownOptions = {
    string: ['browsers', 'pattern'],
    boolean: 'coverage',
    alias: {
        'coverage': 'cov'
    },
    default: {
        browsers: null,
        coverage: false
    }
};

const options = minimist(process.argv.slice(2), knownOptions);

const browsers = [];

const configBrowsers = options.browsers || process.env['MAPTALKS_BROWSERS'] || '';
configBrowsers.split(',').forEach(name => {
    if (!name || name.length < 1) {
        return;
    }
    browsers.push(name);
});

gulp.task('scripts', () => {
    return bundler.bundle('src/index.js', rollupCfg.config);
});

const stylesPattern = './assets/css/**/*.css';

gulp.task('styles', () => {
    return gulp.src(stylesPattern)
        .pipe(concat('maptalks.css'))
        .pipe(cssnano())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('images', () => {
    return gulp.src('./assets/images/**/*')
        .pipe(gulp.dest('./dist/images'));
});

gulp.task('build', ['scripts', 'styles', 'images'], () => {});

gulp.task('minify', ['build'], () => {
    bundler.minify();
});

gulp.task('watch', ['styles', 'images'], () => {
    rollupWatch(() => {
        gulp.src('./dist/*.js')
            .pipe(connect.reload());
    });
    gulp.watch(stylesPattern, ['styles']);
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.test.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.coverage) {
        karmaConfig.configFile = path.join(__dirname, 'build/karma.cover.config.js');
    }
    if (configBrowsers === 'IE9') {
        //override IE9's pattern
        options.pattern = 'IE9.Specs';
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }
    new Server(karmaConfig, done).start();
});

/**
 * Watch for file changes and re-run tests on each change
 */
gulp.task('tdd', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.tdd.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.pattern) {
        karmaConfig.client = {
            mocha: {
                grep: options.pattern
            }
        };
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }

    let started = false;
    rollupWatch(() => {
        if (!started) {
            const karmaServer = new Server(karmaConfig, done);
            karmaServer.start();
            started = true;
        }
    });
});

gulp.task('connect', ['watch'], () => {
    connect.server({
        root: ['dist', 'debug'],
        livereload: true,
        port: 20000
    });
});

gulp.task('reload', ['scripts'], () => {
    gulp.src('./dist/*.js')
        .pipe(connect.reload());
});

gulp.task('doc', (done) => {
    const sources = require('./build/api-files.js');
    del([
        './docs/api/**/*'
    ], {
        force : true
    });
    const conf = require('./jsdoc.json');
    const cmd = 'jsdoc';
    const args = ['-c', 'jsdoc.json'].concat(['-P', 'package.json']).concat(sources);
    const exec = require('child_process').exec;
    exec([cmd].concat(args).join(' '), (error, stdout, stderr) => {
        if (error) {
            console.error('JSDoc returned with error: ' + stderr ? stderr : '');
            done(error);
            return;
        }
        if (stderr) {
            console.error(stderr);
        }
        if (stdout) { console.log(stdout); }
        console.log('Documented ' + sources.length + ' files in:');
        console.log(conf.opts.destination);
        done(stderr);
    });
});

gulp.task('editdoc', ['doc'], () => {
    gulp.watch(['src/**/*.js'], ['doc']);
});

gulp.task('beforeZip', () => {
    return gulp.src(['LICENSE', 'ACKNOWLEDGEMENT', 'docs/**/*'])
    .pipe(gulp.dest('dist'))
});

gulp.task('zip', ['beforeZip'], done => {
    gulp.src(['dist/*.js', 'dist/images/**/*', 'dist/maptalks.css', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT', 'dist/api/**/*'], { base: 'dist/' })
        .pipe(zip('maptalks-' + package.version + '.zip'))
        .pipe(gulp.dest('dist'));
    setTimeout(function () {
        del([
            'dist/api/**/*', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT'
        ], {
            force : true
        });
        done();
    }, 2000);
});

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

<commit_msg>[ci skip] fix publish zip<commit_after>const minimist = require('minimist'),
    path = require('path'),
    gulp = require('gulp'),
    del = require('del'),
    zip = require('gulp-zip'),
    concat = require('gulp-concat'),
    cssnano = require('gulp-cssnano'),
    connect = require('gulp-connect'),
    rollupCfg = require('./build/rollup.config'),
    BundleHelper = require('maptalks-build-helpers').BundleHelper,
    Server = require('karma').Server,
    package = require('./package.json');

const rollupWatch = rollupCfg.watch;
const bundler = new BundleHelper(package);

const knownOptions = {
    string: ['browsers', 'pattern'],
    boolean: 'coverage',
    alias: {
        'coverage': 'cov'
    },
    default: {
        browsers: null,
        coverage: false
    }
};

const options = minimist(process.argv.slice(2), knownOptions);

const browsers = [];

const configBrowsers = options.browsers || process.env['MAPTALKS_BROWSERS'] || '';
configBrowsers.split(',').forEach(name => {
    if (!name || name.length < 1) {
        return;
    }
    browsers.push(name);
});

gulp.task('scripts', () => {
    return bundler.bundle('src/index.js', rollupCfg.config);
});

const stylesPattern = './assets/css/**/*.css';

gulp.task('styles', () => {
    return gulp.src(stylesPattern)
        .pipe(concat('maptalks.css'))
        .pipe(cssnano())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('images', () => {
    return gulp.src('./assets/images/**/*')
        .pipe(gulp.dest('./dist/images'));
});

gulp.task('build', ['scripts', 'styles', 'images'], () => {});

gulp.task('minify', ['build'], () => {
    bundler.minify();
});

gulp.task('watch', ['styles', 'images'], () => {
    rollupWatch(() => {
        gulp.src('./dist/*.js')
            .pipe(connect.reload());
    });
    gulp.watch(stylesPattern, ['styles']);
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.test.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.coverage) {
        karmaConfig.configFile = path.join(__dirname, 'build/karma.cover.config.js');
    }
    if (configBrowsers === 'IE9') {
        //override IE9's pattern
        options.pattern = 'IE9.Specs';
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }
    new Server(karmaConfig, done).start();
});

/**
 * Watch for file changes and re-run tests on each change
 */
gulp.task('tdd', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.tdd.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.pattern) {
        karmaConfig.client = {
            mocha: {
                grep: options.pattern
            }
        };
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }

    let started = false;
    rollupWatch(() => {
        if (!started) {
            const karmaServer = new Server(karmaConfig, done);
            karmaServer.start();
            started = true;
        }
    });
});

gulp.task('connect', ['watch'], () => {
    connect.server({
        root: ['dist', 'debug'],
        livereload: true,
        port: 20000
    });
});

gulp.task('reload', ['scripts'], () => {
    gulp.src('./dist/*.js')
        .pipe(connect.reload());
});

gulp.task('doc', (done) => {
    const sources = require('./build/api-files.js');
    del([
        './docs/api/**/*'
    ], {
        force : true
    });
    const conf = require('./jsdoc.json');
    const cmd = 'jsdoc';
    const args = ['-c', 'jsdoc.json'].concat(['-P', 'package.json']).concat(sources);
    const exec = require('child_process').exec;
    exec([cmd].concat(args).join(' '), (error, stdout, stderr) => {
        if (error) {
            console.error('JSDoc returned with error: ' + stderr ? stderr : '');
            done(error);
            return;
        }
        if (stderr) {
            console.error(stderr);
        }
        if (stdout) { console.log(stdout); }
        console.log('Documented ' + sources.length + ' files in:');
        console.log(conf.opts.destination);
        done(stderr);
    });
});

gulp.task('editdoc', ['doc'], () => {
    gulp.watch(['src/**/*.js'], ['doc']);
});

gulp.task('beforeZip', () => {
    return gulp.src(['LICENSE', 'ACKNOWLEDGEMENT', 'docs/**/*'])
    .pipe(gulp.dest('dist'))
});

gulp.task('zip', ['beforeZip'], done => {
    gulp.src(['dist/*.js', 'dist/*.mjs', 'dist/images/**/*', 'dist/maptalks.css', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT', 'dist/api/**/*'], { base: 'dist/' })
        .pipe(zip('maptalks-' + package.version + '.zip'))
        .pipe(gulp.dest('dist'));
    setTimeout(function () {
        del([
            'dist/api/**/*', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT'
        ], {
            force : true
        });
        done();
    }, 2000);
});

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

<|endoftext|>


<commit_before>var path = require('path');
var gulp = require('gulp');
var rename = require('gulp-rename');
var metalsmith = require('gulp-metalsmith');
var layouts = require('metalsmith-layouts');
var drafts = require('metalsmith-drafts');
var define = require('metalsmith-define');

var markupRegex = /([^\/^\.]*)\.html$/;
var locale = process.env.locale || 'en';

var defines = define({
  'urls': {
    'zh': {
      'urlTemplate': 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
      'subdomains': '[1, 2, 3, 4]'
    },
    'en': {
      //'urlTemplate': 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
      'urlTemplate' : 'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      'subdomains': '[1, 2, 3, 4]'
    }
  }
});

function readExamplesInfo () {
  var json = require('./examples/examples.json');
  var items = json.examples[0];
  var count = Math.floor(items.length/3);
  var info = {};
  var i, j, order = 0;
  for (i = 0; i < count; i++) {
    var ibase = i*3;
    var subItems = items[ibase+2];
    var subCount = Math.floor(subItems.length/2);
    for (j = 0; j < subCount; j++) {
      order++;
      var jbase = j*2;
      var key = path.join(items[ibase], subItems[jbase]);
      info[key] = {
        'category': items[ibase+1],
        'title': subItems[jbase+1],
        'order': order
      };
    }
  }
  return info;
}

function processSingleFile (file, filepath, files, metadata) {
  var basename = path.basename(filepath);
  var match = basename.match(markupRegex);
  if (!match) return;

  var id = match[1];
  var dirname = path.dirname(filepath);

  var info = readExamplesInfo();
  file.meta = info[dirname] || {};
  file.category = file.meta.category[locale];
  file.title = file.meta.title[locale];
  file.order = file.meta.order;

  var js = path.join(dirname, id + '.js');
  if (js in files) {
    var url = metadata['urls'][locale];
    file.js = {
      basename: id + '.js',
      source: files[js].contents.toString()
        .replace(/\$\(urlTemplate\)/g, url.urlTemplate)
        .replace(/\$\(subdomains\)/g, url.subdomains)
    };
    delete files[js];
  }

  var css = path.join(dirname, id + '.css');
  if (css in files) {
    file.css = {
      basename: id + '.css',
      source: files[css].contents.toString()
    };
    delete files[css];
  }
}

function processRaw (files, metalsmith, done) {
  setImmediate(done);
  for (var filepath in files) {
    var file = files[filepath];
    processSingleFile(file, filepath, files, metalsmith.metadata());
  }
}

function processDemo (files, metalsmith, done) {
  setImmediate(done);
  for (var filepath in files) {
    var file = files[filepath];
    var basename = path.basename(filepath);
    processSingleFile(file, filepath, files, metalsmith.metadata());
    file.basename = basename;
  }
}

gulp.task('examples-raw', function () {
  return gulp.src('examples/**/*.{html,js,css}')
    .pipe(metalsmith({
      use: [
        drafts(),
        defines,
        processRaw,
        layouts({engine: 'handlebars', directory: 'layouts/raw'})
      ]
    }))
    .pipe(rename(function (path) {
      path.dirname += '/raw';
      return path;
    }))
    .pipe(gulp.dest(path.join('dist/examples', locale)));
});

gulp.task('examples-demo', function () {
  return gulp.src('examples/**/*.{html,js,css}')
    .pipe(metalsmith({
      use: [
        drafts(),
        defines,
        processDemo,
        layouts({engine: 'handlebars', directory: 'layouts'})
      ]
    }))
    .pipe(gulp.dest(path.join('dist/examples', locale)));
});

gulp.task('examples', ['examples-raw', 'examples-demo'], function () {
  return gulp.src('assets/**/*')
    .pipe(gulp.dest('dist'));
});

gulp.task('default', ['examples']);
<commit_msg>update config.<commit_after>var path = require('path');
var gulp = require('gulp');
var rename = require('gulp-rename');
var metalsmith = require('gulp-metalsmith');
var layouts = require('metalsmith-layouts');
var drafts = require('metalsmith-drafts');
var define = require('metalsmith-define');

var markupRegex = /([^\/^\.]*)\.html$/;
var locale = process.env.locale || 'en';

var defines = define({
  'urls': {
    'zh': {
      'urlTemplate': 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
      'subdomains': '[1, 2, 3, 4]'
    },
    'en': {
      'urlTemplate' : 'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      'subdomains': '[1, 2, 3, 4]'
    }
  }
});

function readExamplesInfo () {
  var json = require('./examples/examples.json');
  var items = json.examples[0];
  var count = Math.floor(items.length/3);
  var info = {};
  var i, j, order = 0;
  for (i = 0; i < count; i++) {
    var ibase = i*3;
    var subItems = items[ibase+2];
    var subCount = Math.floor(subItems.length/2);
    for (j = 0; j < subCount; j++) {
      order++;
      var jbase = j*2;
      var key = path.join(items[ibase], subItems[jbase]);
      info[key] = {
        'category': items[ibase+1],
        'title': subItems[jbase+1],
        'order': order
      };
    }
  }
  return info;
}

function processSingleFile (file, filepath, files, metadata) {
  var basename = path.basename(filepath);
  var match = basename.match(markupRegex);
  if (!match) return;

  var id = match[1];
  var dirname = path.dirname(filepath);

  var info = readExamplesInfo();
  file.meta = info[dirname] || {};
  file.category = file.meta.category[locale];
  file.title = file.meta.title[locale];
  file.order = file.meta.order;

  var js = path.join(dirname, id + '.js');
  if (js in files) {
    var url = metadata['urls'][locale];
    file.js = {
      basename: id + '.js',
      source: files[js].contents.toString()
        .replace(/\$\(urlTemplate\)/g, url.urlTemplate)
        .replace(/\$\(subdomains\)/g, url.subdomains)
    };
    delete files[js];
  }

  var css = path.join(dirname, id + '.css');
  if (css in files) {
    file.css = {
      basename: id + '.css',
      source: files[css].contents.toString()
    };
    delete files[css];
  }
}

function processRaw (files, metalsmith, done) {
  setImmediate(done);
  for (var filepath in files) {
    var file = files[filepath];
    processSingleFile(file, filepath, files, metalsmith.metadata());
  }
}

function processDemo (files, metalsmith, done) {
  setImmediate(done);
  for (var filepath in files) {
    var file = files[filepath];
    var basename = path.basename(filepath);
    processSingleFile(file, filepath, files, metalsmith.metadata());
    file.basename = basename;
  }
}

gulp.task('examples-raw', function () {
  return gulp.src('examples/**/*.{html,js,css}')
    .pipe(metalsmith({
      use: [
        drafts(),
        defines,
        processRaw,
        layouts({engine: 'handlebars', directory: 'layouts/raw'})
      ]
    }))
    .pipe(rename(function (path) {
      path.dirname += '/raw';
      return path;
    }))
    .pipe(gulp.dest(path.join('dist/examples', locale)));
});

gulp.task('examples-demo', function () {
  return gulp.src('examples/**/*.{html,js,css}')
    .pipe(metalsmith({
      use: [
        drafts(),
        defines,
        processDemo,
        layouts({engine: 'handlebars', directory: 'layouts'})
      ]
    }))
    .pipe(gulp.dest(path.join('dist/examples', locale)));
});

gulp.task('examples', ['examples-raw', 'examples-demo'], function () {
  return gulp.src('assets/**/*')
    .pipe(gulp.dest('dist'));
});

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


<commit_before>/**
 * Build system.
 * @module gulpfile
 */
'use strict';

// Module dependencies.
var browserify=require('browserify');
var child=require('child_process');
var del=require('del');
var gulp=require('gulp');
var loadPlugins=require('gulp-load-plugins');
var pkg=require('./package.json');
var util=require('util');

/**
 * Provides tasks for [Gulp.js](http://gulpjs.com) build system.
 * @class cli.Gulpfile
 * @static
 */

/**
 * The task settings.
 * @property config
 * @type Object
 */
var config={
  output: util.format('%s-%s.zip', pkg.yuidoc.name.toLowerCase(), pkg.version)
};

/**
 * The task plugins.
 * @property plugins
 * @type Object
 */
var plugins=loadPlugins({
  pattern: [ 'gulp-*', 'vinyl-*' ],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 * @method default
 */
gulp.task('default', [ 'css', 'js' ]);

/**
 * Checks the package dependencies.
 * @method check
 */
gulp.task('check', function() {
  return gulp.src('package.json')
    .pipe(plugins.david())
    .pipe(plugins.david.reporter);
});

/**
 * Deletes all generated files and reset any saved state.
 * @method clean
 */
gulp.task('clean', function(callback) {
  del('var/'+config.output, callback);
});

/**
 * Builds the stylesheets.
 * @method css
 */
gulp.task('css', function() {
  return gulp.src(require.resolve('mocha/mocha.css'))
    .pipe(gulp.dest('www/css'));
});

/**
 * Creates a distribution file for this program.
 * @method dist
 */
gulp.task('dist', [ 'default' ], function() {
  var sources=[
    '*.js',
    '*.json',
    '*.md',
    '*.txt',
    'bin/*',
    'lib/*.js',
    'test/*.js',
    'www/**/*',
    '!www/**/*.map'
  ];

  return gulp.src(sources, { base: '.' })
    .pipe(plugins.zip(config.output))
    .pipe(gulp.dest('var'));
});

/**
 * Builds the documentation.
 * @method doc
 */
gulp.task('doc', [ 'doc:assets' ]);

gulp.task('doc:assets', [ 'doc:build' ], function() {
  return gulp.src([ 'www/apple-touch-icon.png', 'www/favicon.ico' ])
    .pipe(gulp.dest('doc/api/assets'));
});

gulp.task('doc:build', function(callback) {
  _exec('docgen', callback);
});

/**
 * Builds the client scripts.
 * @method js
 */
gulp.task('js', [ 'js:tests' ], function() {
  return browserify({ debug: true, entries: [ './www/js/main.js' ] })
    .bundle()
    .pipe(plugins.sourceStream('tests.js'))
    .pipe(plugins.buffer())
    .pipe(plugins.sourcemaps.init({ loadMaps: true }))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest('www/js'));
});

gulp.task('js:tests', function() {
  return gulp.src(require.resolve('mocha/mocha.js'))
    .pipe(plugins.uglify())
    .pipe(gulp.dest('www/js'));
});

/**
 * Performs static analysis of source code.
 * @method lint
 */
gulp.task('lint', [ 'lint:doc', 'lint:js' ]);

gulp.task('lint:doc', function(callback) {
  _exec('docgen --lint', callback);
});

gulp.task('lint:js', function() {
  return gulp.src([ '*.js', 'bin/*.js', 'lib/*.js', 'test/*.js', 'www/js/main.js' ])
    .pipe(plugins.jshint(pkg.jshintConfig))
    .pipe(plugins.jshint.reporter('default', { verbose: true }));
});

/**
 * Starts the Web server.
 * @method serve
 */
gulp.task('serve', function(callback) {
  if('_server' in config) {
    config._server.kill();
    delete config._server;
  }

  config._server=child.fork('bin/cli.js');
  callback();
});

/**
 * Runs the unit tests.
 * @method test
 */
gulp.task('test', [ 'test:env' ], function() {
  return gulp.src([ 'test/*.js' ], { read: false })
    .pipe(plugins.mocha());
});

gulp.task('test:env', function(callback) {
  if('AKISMET_API_KEY' in process.env) callback();
  else callback(new Error('AKISMET_API_KEY environment variable not set.'));
});

/**
 * Watches for file changes.
 * @method watch
 */
gulp.task('watch', [ 'js', 'serve' ], function() {
  gulp.watch('lib/*.js', [ 'js', 'serve' ]);
  gulp.watch([ 'test/*.js', 'www/js/main.js' ], [ 'js' ]);
});

/**
 * Runs a command and prints its output.
 * @method _exec
 * @param {String} command The command to run, with space-separated arguments.
 * @param {Function} callback The function to invoke when the task is over.
 * @async
 * @private
 */
function _exec(command, callback) {
  child.exec(command, function(err, stdout) {
    var output=stdout.trim();
    if(output.length) console.log(output);
    if(err) console.error(err);
    callback();
  });
}
<commit_msg>Migrating the code to ES6<commit_after>/**
 * Build system.
 * @module gulpfile
 */
'use strict';

// Module dependencies.
const browserify=require('browserify');
const child=require('child_process');
const del=require('del');
const fs=require('fs');
const gulp=require('gulp');
const loadPlugins=require('gulp-load-plugins');
const pkg=require('./package.json');

/**
 * The task settings.
 * @var {object}
 */
const config={
  output: `${pkg.name}-${pkg.version}.zip`,
  sources: [
    '*.json',
    '*.md',
    '*.txt',
    'index.js',
    'bin/*',
    'lib/*.js',
    'test/*.js',
    'www/**/*',
    '!www/**.map'
  ]
};

/**
 * The task plugins.
 * @var {object}
 */
const plugins=loadPlugins({
  pattern: ['gulp-*', 'vinyl-*'],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 */
gulp.task('default', ['css', 'js']);

/**
 * Checks the package dependencies.
 */
gulp.task('check', () => gulp.src('package.json')
  .pipe(plugins.david())
  .pipe(plugins.david.reporter));

/**
 * Deletes all generated files and reset any saved state.
 */
gulp.task('clean', callback => del(`var/${config.output}`, callback));

/**
 * Builds the stylesheets.
 */
gulp.task('css', function() {
  return gulp.src(require.resolve('mocha/mocha.css'))
    .pipe(gulp.dest('www/css'));
});

/**
 * Creates a distribution file for this program.
 */
gulp.task('dist', ['default'], () => gulp.src(config.sources, { base: '.' })
  .pipe(plugins.zip(config.output))
  .pipe(gulp.dest('var')));

/**
 * Builds the documentation.
 */
gulp.task('doc', ['doc:assets']);

gulp.task('doc:assets', ['doc:rename'], () => gulp.src(['web/apple-touch-icon.png', 'web/favicon.ico'])
  .pipe(gulp.dest('doc/api')));

gulp.task('doc:build', callback => {
  _exec('jsdoc --configure doc/conf.json').then(callback, callback)
});

gulp.task('doc:rename', ['doc:build'], callback => fs.rename(`doc/${pkg.name}/${pkg.version}`, 'doc/api', callback));

/**
 * Builds the client scripts.
 */
gulp.task('js', ['js:tests'], function() {
  return browserify({ debug: true, entries: ['./www/js/main.js'] })
    .bundle()
    .pipe(plugins.sourceStream('tests.js'))
    .pipe(plugins.buffer())
    .pipe(plugins.sourcemaps.init({ loadMaps: true }))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(gulp.dest('www/js'));
});

gulp.task('js:tests', function() {
  return gulp.src(require.resolve('mocha/mocha.js'))
    .pipe(plugins.uglify())
    .pipe(gulp.dest('www/js'));
});

/**
 * Performs static analysis of source code.
 */
gulp.task('lint', () => gulp.src(['*.js', 'bin/*.js', 'lib/*.js', 'test/*.js', 'www/js/main.js'])
  .pipe(plugins.jshint(pkg.jshintConfig))
  .pipe(plugins.jshint.reporter('default', { verbose: true })));

/**
 * Starts the Web server.
 */
gulp.task('serve', callback => {
  if('_server' in config) {
    config._server.kill();
    delete config._server;
  }

  config._server=child.fork('bin/cli.js');
  callback();
});

/**
 * Runs the unit tests.
 */
gulp.task('test', ['test:env'], () => gulp.src(['test/*.js'], { read: false })
  .pipe(plugins.mocha()));

gulp.task('test:env', function(callback) {
  if('AKISMET_API_KEY' in process.env) callback();
  else callback(new Error('AKISMET_API_KEY environment variable not set.'));
});

/**
 * Watches for file changes.
 */
gulp.task('watch', ['js', 'serve'], function() {
  gulp.watch('lib/*.js', ['js', 'serve']);
  gulp.watch(['test/*.js', 'www/js/main.js'], ['js']);
});

/**
 * Runs a command and prints its output.
 * @param {string} command The command to run, with space-separated arguments.
 * @return {Promise} Completes when the command is finally terminated.
 * @private
 */
function _exec(command) {
  return new Promise((resolve, reject) => child.exec(command, (err, stdout) => {
    let output=stdout.trim();
    if(output.length) console.log(output);
    if(err) reject(err);
    else resolve();
  }));
}
<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var mocha = require('gulp-mocha');
var coffee = require('gulp-coffee');
var istanbul = require('gulp-coffee-istanbul');
var plumber = require('gulp-plumber');
var coffeeify = require('gulp-coffeeify');
var through = require('through');
var jade = require('gulp-jade');
var nodemon = require('gulp-nodemon');
var coffeelint = require('gulp-coffeelint');
var ghPages = require('gulp-gh-pages');
var del = require('del');
var imagemin = require('gulp-imagemin');
var debug = require('gulp-debug');
var changed = require('gulp-changed');
var isDist = process.argv.indexOf('watch') === -1;
var deployDir = process.argv.indexOf('deploy') === -1 ? '' : 'deploy/';

gulp.task('lint:js', function() {
  return gulp.src(['js/**/*.js', 'gulpfile.js'])
    .pipe(eslint({
      useEslintrc: false,
      env: {
        browser: 1,
        node: 1
      },
      rules: {
        quotes: [1, 'single'],
        strict: 1,
        eqeqeq: 2,
        'comma-dangle': 0,
        'no-extend-native': 0
      }
    }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('lint:test', function() {
  return gulp.src(['test/**/*.js'])
    .pipe(eslint({
      useEslintrc: false,
      env: {
        browser: 1,
        node: 1
      },
      rules: {
        quotes: [1, 'single'],
        strict: 1,
        eqeqeq: 2,
        'comma-dangle': 0,
        'no-extend-native': 0,
        'no-unused-expressions': 0
      },
      globals: {
        describe: 0,
        it: 0,
        before: 0,
        beforeEach: 0,
        after: 0,
        afterEach: 0
      }
    }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('lint:coffee', function() {
  return gulp.src('@(server|client)/**/*.coffee')
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())
    .pipe(coffeelint.reporter('fail'));
});

gulp.task('lint', ['lint:js', 'lint:coffee']);

gulp.task('test', function(done) {
  gulp.src(['js/**/*.js', '@(server|client)/**/*.coffee'])
    .pipe(istanbul()) // Covering files
    .pipe(istanbul.hookRequire()) // Force `require` to return covered files
    .on('finish', function() {
      gulp.src(['test/**/*.@(js|coffee)'])
        .pipe(mocha())
        .pipe(istanbul.writeReports()) // Creating the reports after tests runned
        .on('end', done);
    });
});

gulp.task('html', function() {
  return gulp.src('client/**/*.jade')
    .pipe(isDist ? through() : plumber())
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./' + deployDir + 'public'));
});

gulp.task('js', function() {
  return gulp.src('client/main.coffee')
    .pipe(isDist ? through() : plumber())
    .pipe(coffeeify({
      options: {
        debug: !isDist
      }
    }))
    .pipe(gulp.dest('./' + deployDir + 'public'));
});

gulp.task('start', function() {
  nodemon({
    script: 'server/server.coffee',
    ext: 'coffee',
    //verbose: true,
    nodeArgs: ['--nodejs', '--debug'],
    ignore: ['client/**/*', 'public/*.js', 'test/', 'node_modules/'],
    watch: ['server/**/*.coffee', 'public/data/**/*.json'],
    env: {
      'NODE_ENV': 'development'
    }
  });
});

gulp.task('js:server', function() {
  return gulp.src('./server/**/*.coffee')
    .pipe(isDist ? through() : plumber())
    .pipe(coffee({
      bare: true
    }).on('error', console.log))
    .pipe(gulp.dest('./' + deployDir + 'build/'));
});

gulp.task('img-optimization', function() {
  return gulp.src('./data/img/**/*')
    .pipe(isDist ? through() : plumber())
    .pipe(imagemin({
      progressive: true
    }))
    .pipe(debug({
      title: 'Optimizing images:'
    }))
    .pipe(gulp.dest('./data/img/'));
});

gulp.task('data', function() {
  var dest = './' + deployDir + 'public/data/';
  return gulp.src('./data/**/*')
    .pipe(isDist ? through() : plumber())
    .pipe(changed(dest))
    .pipe(imagemin({
      progressive: true
    }))
    .pipe(debug({
      title: 'Copying data:'
    }))
    .pipe(gulp.dest(dest));
});

gulp.task('build', ['js', 'html', 'js:server', 'data']);

gulp.task('watch', ['start', 'js', 'html', 'data'], function() {
  gulp.watch('client/**/*.jade', ['html']);
  gulp.watch('data/**/*', ['data']);
  gulp.watch([
    'client/**/*.coffee',
    'js/**/*.js'
  ], ['js']);
});

gulp.task('deploy', ['build'], function() {
  del.sync(['heroku-deploy']);
  return gulp.src(['deploy/**/*', 'package.json'])
    .pipe(ghPages({
      //push: false,
      force: true,
      branch: 'master',
      cacheDir: 'heroku-deploy',
      remoteUrl: 'git@heroku.com:dominiongame.git'
    }));
});

gulp.task('default', ['lint', 'test']);
<commit_msg>Don't push force when deploying<commit_after>'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var mocha = require('gulp-mocha');
var coffee = require('gulp-coffee');
var istanbul = require('gulp-coffee-istanbul');
var plumber = require('gulp-plumber');
var coffeeify = require('gulp-coffeeify');
var through = require('through');
var jade = require('gulp-jade');
var nodemon = require('gulp-nodemon');
var coffeelint = require('gulp-coffeelint');
var ghPages = require('gulp-gh-pages');
var del = require('del');
var imagemin = require('gulp-imagemin');
var debug = require('gulp-debug');
var changed = require('gulp-changed');
var isDist = process.argv.indexOf('watch') === -1;
var deployDir = process.argv.indexOf('deploy') === -1 ? '' : 'deploy/';

gulp.task('lint:js', function() {
  return gulp.src(['js/**/*.js', 'gulpfile.js'])
    .pipe(eslint({
      useEslintrc: false,
      env: {
        browser: 1,
        node: 1
      },
      rules: {
        quotes: [1, 'single'],
        strict: 1,
        eqeqeq: 2,
        'comma-dangle': 0,
        'no-extend-native': 0
      }
    }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('lint:test', function() {
  return gulp.src(['test/**/*.js'])
    .pipe(eslint({
      useEslintrc: false,
      env: {
        browser: 1,
        node: 1
      },
      rules: {
        quotes: [1, 'single'],
        strict: 1,
        eqeqeq: 2,
        'comma-dangle': 0,
        'no-extend-native': 0,
        'no-unused-expressions': 0
      },
      globals: {
        describe: 0,
        it: 0,
        before: 0,
        beforeEach: 0,
        after: 0,
        afterEach: 0
      }
    }))
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
});

gulp.task('lint:coffee', function() {
  return gulp.src('@(server|client)/**/*.coffee')
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())
    .pipe(coffeelint.reporter('fail'));
});

gulp.task('lint', ['lint:js', 'lint:coffee']);

gulp.task('test', function(done) {
  gulp.src(['js/**/*.js', '@(server|client)/**/*.coffee'])
    .pipe(istanbul()) // Covering files
    .pipe(istanbul.hookRequire()) // Force `require` to return covered files
    .on('finish', function() {
      gulp.src(['test/**/*.@(js|coffee)'])
        .pipe(mocha())
        .pipe(istanbul.writeReports()) // Creating the reports after tests runned
        .on('end', done);
    });
});

gulp.task('html', function() {
  return gulp.src('client/**/*.jade')
    .pipe(isDist ? through() : plumber())
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./' + deployDir + 'public'));
});

gulp.task('js', function() {
  return gulp.src('client/main.coffee')
    .pipe(isDist ? through() : plumber())
    .pipe(coffeeify({
      options: {
        debug: !isDist
      }
    }))
    .pipe(gulp.dest('./' + deployDir + 'public'));
});

gulp.task('start', function() {
  nodemon({
    script: 'server/server.coffee',
    ext: 'coffee',
    //verbose: true,
    nodeArgs: ['--nodejs', '--debug'],
    ignore: ['client/**/*', 'public/*.js', 'test/', 'node_modules/'],
    watch: ['server/**/*.coffee', 'public/data/**/*.json'],
    env: {
      'NODE_ENV': 'development'
    }
  });
});

gulp.task('js:server', function() {
  return gulp.src('./server/**/*.coffee')
    .pipe(isDist ? through() : plumber())
    .pipe(coffee({
      bare: true
    }).on('error', console.log))
    .pipe(gulp.dest('./' + deployDir + 'build/'));
});

gulp.task('img-optimization', function() {
  return gulp.src('./data/img/**/*')
    .pipe(isDist ? through() : plumber())
    .pipe(imagemin({
      progressive: true
    }))
    .pipe(debug({
      title: 'Optimizing images:'
    }))
    .pipe(gulp.dest('./data/img/'));
});

gulp.task('data', function() {
  var dest = './' + deployDir + 'public/data/';
  return gulp.src('./data/**/*')
    .pipe(isDist ? through() : plumber())
    .pipe(changed(dest))
    .pipe(imagemin({
      progressive: true
    }))
    .pipe(debug({
      title: 'Copying data:'
    }))
    .pipe(gulp.dest(dest));
});

gulp.task('build', ['js', 'html', 'js:server', 'data']);

gulp.task('watch', ['start', 'js', 'html', 'data'], function() {
  gulp.watch('client/**/*.jade', ['html']);
  gulp.watch('data/**/*', ['data']);
  gulp.watch([
    'client/**/*.coffee',
    'js/**/*.js'
  ], ['js']);
});

gulp.task('deploy', ['build'], function() {
  del.sync(['heroku-deploy']);
  return gulp.src(['deploy/**/*', 'package.json'])
    .pipe(ghPages({
      //push: false,
      //force: true,
      branch: 'master',
      cacheDir: 'heroku-deploy',
      remoteUrl: 'git@heroku.com:dominiongame.git'
    }));
});

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


<commit_before>/* External imports */
var os    = require('os');
var redis = require('redis');

/* Internal imports */
var lua    = require('./lua').lua;
var config = require('./config').config;
var queue  = require('./queue').queue;

function client(host, port, hostname) {
	this.redis  = redis.createClient(port || 6379, host || 'localhost');
	this.worker = hostname || os.hostname();
	this.config = new config(this);

	/* This is a reference to queues as they're lazily loaded */
	this.__queues = {}

	var commands = [
		'cancel', 'complete', 'depends', 'fail', 'failed', 'get', 'getconfig', 'heartbeat',
	    'jobs', 'peek', 'pop', 'put', 'queues', 'setconfig', 'stats', 'track', 'workers'];
	for (var index in commands) {
		this['_' + commands[index]] = new lua(commands[index], this.redis);
	}
}

client.prototype.queue = function(name) {
	if (!this.__queues[name]) {
		this.__queues[name] = new queue(name, this, this.worker);
	}
	return this.__queues[name];
}

client.prototype.queues = function(queue, cb, eb) {
	if (queue) {
		return this._queues.call([], [(new Date().getTime() / 1000), queue], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		return this._queues.call([], [(new Date().getTime() / 1000)], function(r) {
			cb(JSON.parse(r));
		}, eb);
	}
}

client.prototype.tracked = function(cb, eb) {
	return this._track.call([], [], function(r) {
		var results = JSON.parse(r);
		for (var index in results['jobs']) {
			results['jobs'][index] = new job(this, results['jobs'][index]);
		}
		cb(results);
	}, eb);
}

client.prototype.failed = function(group, start, limit, cb, eb) {
	if (typeof(group) == 'function') {
		eb = start; cb = group;
		group = null;
	} else if (typeof(start) == 'function') {
		eb = limit; cb = start;
		start = 0; limit = 25;
	} else if (typeof(limit) == 'function') {
		eb = cb; cb = limit;
		limit = 25;
	}
	if (group == null) {
		this._failed.call([], [], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		this._failed.call([], [group, start, limit], function(r) {
			var results = JSON.parse(r);
			for (var index in results['jobs']) {
				results['jobs'][index] = new job(this, results['jobs'][index]);
			}
			cb(results);
		}, eb);
	}
}

client.prototype.workers = function(worker, cb, eb) {
	if (typeof(worker) == 'function') {
		eb = cb; cb = worker;
		this._workers.call([], [(new Date().getTime() / 1000)], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		this._workers.call([], [(new Date().gettime() / 1000), worker], function(r) {
			cb(JSON.parse(r));
		}, eb);
	}
}

client.prototype.job = function(id, cb, eb) {
	this._get.call([], [id], function(r) {
		if (r) {
			cb(new job(this, JSON.parse(r)));
		} else {
			cb(null);
		}
	}, eb);
}

exports.client = client;<commit_msg>added require for job and fixed reference to this<commit_after>/* External imports */
var os    = require('os');
var redis = require('redis');

/* Internal imports */
var lua    = require('./lua').lua;
var job    = require('./job').job;
var config = require('./config').config;
var queue  = require('./queue').queue;

function client(host, port, hostname) {
	this.redis  = redis.createClient(port || 6379, host || 'localhost');
	this.worker = hostname || os.hostname();
	this.config = new config(this);

	/* This is a reference to queues as they're lazily loaded */
	this.__queues = {}

	var commands = [
		'cancel', 'complete', 'depends', 'fail', 'failed', 'get', 'getconfig', 'heartbeat',
	    'jobs', 'peek', 'pop', 'put', 'queues', 'setconfig', 'stats', 'track', 'workers'];
	for (var index in commands) {
		this['_' + commands[index]] = new lua(commands[index], this.redis);
	}
}

client.prototype.queue = function(name) {
	if (!this.__queues[name]) {
		this.__queues[name] = new queue(name, this, this.worker);
	}
	return this.__queues[name];
}

client.prototype.queues = function(queue, cb, eb) {
	if (queue) {
		return this._queues.call([], [(new Date().getTime() / 1000), queue], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		return this._queues.call([], [(new Date().getTime() / 1000)], function(r) {
			cb(JSON.parse(r));
		}, eb);
	}
}

client.prototype.tracked = function(cb, eb) {
	return this._track.call([], [], function(r) {
		var results = JSON.parse(r);
		for (var index in results['jobs']) {
			results['jobs'][index] = new job(this, results['jobs'][index]);
		}
		cb(results);
	}, eb);
}

client.prototype.failed = function(group, start, limit, cb, eb) {
	if (typeof(group) == 'function') {
		eb = start; cb = group;
		group = null;
	} else if (typeof(start) == 'function') {
		eb = limit; cb = start;
		start = 0; limit = 25;
	} else if (typeof(limit) == 'function') {
		eb = cb; cb = limit;
		limit = 25;
	}
	if (group == null) {
		this._failed.call([], [], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		this._failed.call([], [group, start, limit], function(r) {
			var results = JSON.parse(r);
			for (var index in results['jobs']) {
				results['jobs'][index] = new job(this, results['jobs'][index]);
			}
			cb(results);
		}, eb);
	}
}

client.prototype.workers = function(worker, cb, eb) {
	if (typeof(worker) == 'function') {
		eb = cb; cb = worker;
		this._workers.call([], [(new Date().getTime() / 1000)], function(r) {
			cb(JSON.parse(r));
		}, eb);
	} else {
		this._workers.call([], [(new Date().gettime() / 1000), worker], function(r) {
			cb(JSON.parse(r));
		}, eb);
	}
}

client.prototype.job = function(id, cb, eb) {
	var self = this;
	self._get.call([], [id], function(r) {
		var that = self;
		if (r) {
			cb(new job(that, JSON.parse(r)));
		} else {
			cb(null);
		}
	}, eb);
}

exports.client = client;
<|endoftext|>


<commit_before>'use strict'
const { get, post } = require('./support/request')
const db = require('./support/db')
const { asyncWrap } = require('./support/nodeunit')
const app = require('./support/app')
const auth = require('./support/auth')
const rat = require('./support/rat')
const { HTTP_CREATED, HTTP_OK } = require('./support/const')

module.exports = {
  setUp: async function (test) {
    await db.init()
    await app.init()
    test()
  },
  /**
   * @api {post} /rats Create rat
   * @apiName CreateRat
   * @apiGroup Rat
   *
   * @apiHeader {String} Cookie auth token
   * @apiParam {String} name
   * @apiParam {String} platform
   * @apiPermission user.write
   * @apiSuccess (201) {Object} data Rat data
   */
  ratCreate: asyncWrap(async function (test) {

    const NUM_TESTS = 5
    test.expect(NUM_TESTS)

    const adminUser = await auth.adminUser()
    const data = {
      name: 'roland',
      platform: 'xb'
    }

    let create = await new post(adminUser, '/rats', data)

    let res = create.body

    test.strictEqual(create.response.statusCode, HTTP_CREATED)
    test.ifError(res.error)

    if (res.data) {
      let { attributes } = res.data
      test.notEqual(res.data.id, null)
      test.strictEqual(attributes.name, data.name)
      test.strictEqual(attributes.platform, data.platform)
    }

  }),
  /**
   * @api {get} /rats/:id Find rat
   * @apiName FindRatById
   * @apiGroup Rat
   *
   * @apiHeader {String} Cookie auth token
   * @apiParam {String} id rat id
   */
  ratFindById: asyncWrap(async function (test) {

    const NUM_TESTS = 5
    test.expect(NUM_TESTS)

    const adminUser = await auth.adminUser()

    const newRat = {
      name: 'roland',
      platform: 'xb'
    }

    const res = await rat.create(adminUser, newRat)

    const find = await get(adminUser, '/rats/' + res.id)

    test.strictEqual(find.response.statusCode, HTTP_OK)
    if (find.body) {
      let { data } = find.body
      test.strictEqual(data.length, 1) // should have only one rat returned
      test.strictEqual(data[0].id, res.id)
      const attr = data[0].attributes
      test.strictEqual(attr.name, newRat.name)
      test.strictEqual(attr.platform, newRat.platform)
    }
  })
}<commit_msg>added rat findByName test<commit_after>'use strict'
const { get, post } = require('./support/request')
const db = require('./support/db')
const { asyncWrap } = require('./support/nodeunit')
const app = require('./support/app')
const auth = require('./support/auth')
const rat = require('./support/rat')
const { HTTP_CREATED, HTTP_OK } = require('./support/const')

module.exports = {
  setUp: async function (test) {
    await db.init()
    await app.init()
    test()
  },
  /**
   * @api {post} /rats Create rat
   * @apiName CreateRat
   * @apiGroup Rat
   *
   * @apiHeader {String} Cookie auth token
   * @apiParam {String} name
   * @apiParam {String} platform
   * @apiPermission user.write
   * @apiSuccess (201) {Object} data Rat data
   *
   * @apiExample
   * POST /rats HTTP/1.1
   * Cookie: fuelrats:session=eyJ1c2VySWQiOiJiYTZmN2ViMy0zYzFjLTQ0MDktOWEwZS1iM2IwYjRjMzdjN2IiLCJfZXhwaXJlIjoxNTA5NDg0MDMwODg1LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; httponly;
   * Content-Type: application/json
   *
   * {
   *  "name": "roland",
   *  "platform": "xb"
   * }
   */
  ratCreate: asyncWrap(async function (test) {

    const NUM_TESTS = 5
    test.expect(NUM_TESTS)

    const adminUser = await auth.adminUser()
    const data = {
      name: 'roland',
      platform: 'xb'
    }

    let create = await new post(adminUser, '/rats', data)

    let res = create.body

    test.strictEqual(create.response.statusCode, HTTP_CREATED)
    test.ifError(res.error)

    if (res.data) {
      let { attributes } = res.data
      test.notEqual(res.data.id, null)
      test.strictEqual(attributes.name, data.name)
      test.strictEqual(attributes.platform, data.platform)
    }

  }),
  /**
   * @api {get} /rats/:id Find rat
   * @apiName FindRatById
   * @apiGroup Rat
   *
   * @apiHeader {String} Cookie auth token
   * @apiParam {String} id rat id
   *
   * @apiExample
   * GET /rats/afd9d83c-3b4b-4ad5-844b-4719850becff HTTP/1.1
   * Cookie: fuelrats:session=eyJ1c2VySWQiOiJiYTZmN2ViMy0zYzFjLTQ0MDktOWEwZS1iM2IwYjRjMzdjN2IiLCJfZXhwaXJlIjoxNTA5NDg0MDMwODg1LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; httponly;
   * Content-Type: application/json
   */
  ratFindById: asyncWrap(async function (test) {

    const NUM_TESTS = 5
    test.expect(NUM_TESTS)

    const adminUser = await auth.adminUser()

    const newRat = {
      name: 'roland',
      platform: 'xb'
    }

    const res = await rat.create(adminUser, newRat)

    const find = await get(adminUser, '/rats/' + res.id)

    test.strictEqual(find.response.statusCode, HTTP_OK)
    if (find.body) {
      let { data } = find.body
      test.strictEqual(data.length, 1) // should have only one rat returned
      test.strictEqual(data[0].id, res.id)
      const attr = data[0].attributes
      test.strictEqual(attr.name, newRat.name)
      test.strictEqual(attr.platform, newRat.platform)
    }
  }),
  /**
   * @api {get} /rats Find rat by attribute
   * @apiName FindRat
   * @apiGroup Rat
   *
   * @apiHeader {String} Cookie auth token
   *
   * @apiExample
   * GET /rats?name=roland HTTP/1.1
   * Cookie: fuelrats:session=eyJ1c2VySWQiOiJiYTZmN2ViMy0zYzFjLTQ0MDktOWEwZS1iM2IwYjRjMzdjN2IiLCJfZXhwaXJlIjoxNTA5NDg0MDMwODg1LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; httponly;
   * Content-Type: application/json
   *
   */
  ratFindByName: asyncWrap(async function (test) {

    const NUM_TESTS = 5
    test.expect(NUM_TESTS)

    const adminUser = await auth.adminUser()

    const newRat = {
      name: 'roland',
      platform: 'xb'
    }

    const res = await rat.create(adminUser, newRat)

    const find = await get(adminUser, '/rats?name=' + newRat.name)

    test.strictEqual(find.response.statusCode, HTTP_OK)
    if (find.body) {
      let { data } = find.body
      test.strictEqual(data.length, 1) // should have only one rat returned
      test.strictEqual(data[0].id, res.id)
      const attr = data[0].attributes
      test.strictEqual(attr.name, newRat.name)
      test.strictEqual(attr.platform, newRat.platform)
    }
  })
}<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const electron = require('electron-prebuilt');
const electronPackager = require('electron-packager');
var childProcess = require('child_process');

const packageJson = require('./package.json');

const _ = require('underscore');

const RELEASE_SETTINGS = {
    dir: '.',
    name: packageJson.name,
    out: 'releases',
    'app-version': packageJson.version,
	'version-string': {
		ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.name,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
		'file-version': packageJson.version,
		'product-version': packageJson.version,
		LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
	},
    win32metadata : {
        ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.name,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
		'file-version': packageJson.version,
		'product-version': packageJson.version,
		LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
    },
    ignore : '/.gitignore|CHANGELOG.md|README.md|gulpfile.js|screenshot.png/',
    appPath : packageJson.main,
    overwrite: true,
    asar: true,
    prune: true
};

require('gulp-task-list')(gulp);

gulp.task('start', (next) => {
    var child = childProcess.spawn(electron, ['./']);

    child.stdout.on('data', (data) => {
        console.log(data);
    });

    child.on('exit', (code) => {
        console.log('Child exited with code: ' + code);
        return next(code === 1 ? new Error('Error running run task') : null);
    });
});

gulp.task('pack-linux32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'ia32'
    }), next)
});

gulp.task('pack-linux64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'x64'
    }), next)
});

gulp.task('pack-windows32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'ia32',
		icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});

gulp.task('pack-windows64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'x64',
		icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});
<commit_msg>excluded dist and releases folder from build<commit_after>'use strict';

const gulp = require('gulp');
const electron = require('electron-prebuilt');
const electronPackager = require('electron-packager');
var childProcess = require('child_process');

const packageJson = require('./package.json');

const _ = require('underscore');

const RELEASE_SETTINGS = {
    dir: '.',
    name: packageJson.name,
    out: 'releases',
    'app-version': packageJson.version,
	'version-string': {
		ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.name,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
		'file-version': packageJson.version,
		'product-version': packageJson.version,
		LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
	},
    win32metadata : {
        ProductName : packageJson.name,
        CompanyName: packageJson.author,
        FileDescription: packageJson.name,
        OriginalFilename: packageJson.name + '.exe',
        ProductVersion : packageJson.version,
		'file-version': packageJson.version,
		'product-version': packageJson.version,
		LegalCopyright: 'Copyright (c) 2016 ' + packageJson.author
    },
    ignore : '/.gitignore|releases|dist|CHANGELOG.md|README.md|gulpfile.js|screenshot.png/',
    appPath : packageJson.main,
    overwrite: true,
    asar: true,
    prune: true
};

require('gulp-task-list')(gulp);

gulp.task('start', (next) => {
    var child = childProcess.spawn(electron, ['./']);

    child.stdout.on('data', (data) => {
        console.log(data.toString('utf-8'));
    });

    child.on('exit', (code) => {
        console.log('Child exited with code: ' + code);
        return next(code === 1 ? new Error('Error running run task') : null);
    });
});

gulp.task('pack-linux32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'ia32'
    }), next)
});

gulp.task('pack-linux64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'linux',
        arch: 'x64'
    }), next)
});

gulp.task('pack-windows32', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'ia32',
		icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});

gulp.task('pack-windows64', (next) => {
    electronPackager(_.extend(RELEASE_SETTINGS, {
        platform: 'win32',
        arch: 'x64',
		icon: 'resources/icons/kongdash-256x256.ico'
    }), next)
});
<|endoftext|>


<commit_before>import 'isomorphic-fetch';
import flatten from 'lodash/flatten';
import sortBy from 'lodash/sortBy';
import { get, post, remove } from 'utils/request';

export default class LayersService {
  constructor(options = {}) {
    this.opts = options;
  }

  // GET ALL DATA
  fetchAllData({ applications, dataset = '' }) {
    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}?application=${applications.join(',')}&includes=layer&page[size]=${Date.now() / 100000}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          if (Array.isArray(data)) {
            const layers = flatten(data.map(d => d.attributes.layer.map(layer => ({
              ...layer.attributes,
              id: layer.id
            }))));
            resolve(sortBy(layers, 'name'));
          } else {
            resolve(data.attributes.layer);
          }
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchData({ id }) {
    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/layer/${id}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveData({ type, body, id, dataset }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}/layer/${id}`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  deleteData({ id, dataset }) {
    return new Promise((resolve, reject) => {
      remove({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}/layer/${id}`,
        headers: [{
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: () => {
          resolve();
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }
}
<commit_msg>Layers: show correct data in table<commit_after>import 'isomorphic-fetch';
import flatten from 'lodash/flatten';
import sortBy from 'lodash/sortBy';
import { get, post, remove } from 'utils/request';

export default class LayersService {
  constructor(options = {}) {
    this.opts = options;
  }

  // GET ALL DATA
  fetchAllData({ applications, dataset = '' }) {
    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}?application=${applications.join(',')}&includes=layer&page[size]=${Date.now() / 100000}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: ({ data }) => {
          if (Array.isArray(data)) {
            const layers = flatten(data.map(d => d.attributes.layer.map(layer => ({
              ...layer.attributes,
              id: layer.id
            }))));
            resolve(sortBy(layers, 'name'));
          } else {
            const layers = data.attributes.layer.map(layer => ({
              ...layer.attributes,
              id: layer.id
            }));
            resolve(sortBy(layers, 'name'));
          }
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  fetchData({ id }) {
    return new Promise((resolve, reject) => {
      get({
        url: `${process.env.WRI_API_URL}/layer/${id}`,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  saveData({ type, body, id, dataset }) {
    return new Promise((resolve, reject) => {
      post({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}/layer/${id}`,
        type,
        body,
        headers: [{
          key: 'Content-Type',
          value: 'application/json'
        }, {
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: (response) => {
          resolve({
            ...response.data.attributes,
            id: response.data.id
          });
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }

  deleteData({ id, dataset }) {
    return new Promise((resolve, reject) => {
      remove({
        url: `${process.env.WRI_API_URL}/dataset/${dataset}/layer/${id}`,
        headers: [{
          key: 'Authorization',
          value: this.opts.authorization
        }],
        onSuccess: () => {
          resolve();
        },
        onError: (error) => {
          reject(error);
        }
      });
    });
  }
}
<|endoftext|>


<commit_before>var elixir = require('laravel-elixir');

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(function(mix) {
    mix.sass('app.scss');
});
<commit_msg>Remove gulpfile.js<commit_after><|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var path = require('path');
var gulp = require('gulp');
var rimraf = require('del');
var transport = require('gulp-cmd');
var uglify = require('gulp-uglify');
var css = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var colors = transport.colors;

// alias
var alias = {
  'import-style': '/online/loader/import-style',
  'jquery': 'base/jquery/1.11.2/jquery',
  'base': 'base/base/1.2.0/base',
  'class': 'base/class/1.2.0/class',
  'events': 'base/events/1.2.0/events',
  'widget': 'base/widget/1.2.0/widget',
  'template': 'base/template/3.0.3/template',
  'templatable': 'base/templatable/0.10.0/templatable',
  'iframe-shim': 'util/iframe-shim/1.1.0/iframe-shim',
  'position': 'util/position/1.1.0/position',
  'messenger': 'util/messenger/2.1.0/messenger',
  'mask': 'common/overlay/1.2.0/mask',
  'overlay': 'common/overlay/1.2.0/overlay',
  'dialog': 'common/dialog/1.5.1/dialog',
  'confirmbox': 'common/dialog/1.5.1/confirmbox'
};

var startTime = Date.now();

// complete callback
function complete(){
  var now = new Date();

  console.log(
    '  %s [%s] build complete ... %s%s',
    colors.cyan.bold('gulp-cmd'),
    now.toLocaleString(),
    colors.green(now - startTime),
    colors.cyan('ms')
  );
}

// clean task
gulp.task('clean', function (callback){
  rimraf('online', callback);
});

// runtime task
gulp.task('runtime', ['clean'], function (){
  gulp.src('assets/loader/**/*.js', { base: 'assets' })
    .pipe(uglify())
    .pipe(gulp.dest('online'));

  gulp.src('assets/?(loader|images)/**/*.!(js)', { base: 'assets' })
    .pipe(gulp.dest('online'));
});

// online task
gulp.task('online', ['runtime'], function (){
  // all js
  gulp.src('assets/js/**/*.js', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      ignore: ['jquery'],
      include: function (id){
        return id.indexOf('view') === 0 ? 'all' : 'relative';
      },
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(uglify())
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  // other file
  gulp.src('assets/js/**/*.!(js|css|json|tpl|html)')
    .pipe(gulp.dest('online/js'));

  // css
  gulp.src('assets/css/**/*.*')
    .pipe(css({ compatibility: 'ie8' }))
    .pipe(gulp.dest('online/css'));
});

// develop task
gulp.task('default', ['runtime'], function (){
  // all file
  gulp.src('assets/js/**/*.*', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      include: 'self',
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  gulp.src('assets/css/**/*.*', { base: 'assets' })
    .pipe(gulp.dest('online'));
});

// develop watch task
gulp.task('watch', ['default'], function (){
  var base = path.join(process.cwd(), 'assets');

  // watch all file
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets/js' })
        .pipe(plumber())
        .pipe(transport({
          alias: alias,
          include: 'self',
          cache: false,
          css: {
            onpath: function (path){
              return path.replace('assets/', 'online/')
            }
          }
        }))
        .pipe(gulp.dest('online/js'))
        .on('end', complete);
    }
  });

  // watch all file
  gulp.watch('assets/?(images|loader|css)/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets' })
        .pipe(plumber())
        .pipe(gulp.dest('online'))
        .on('end', complete);
    }
  });
});
<commit_msg>add source<commit_after>/**
 * Created by nuintun on 2015/5/5.
 */

'use strict';

var path = require('path');
var gulp = require('gulp');
var rimraf = require('del');
var transport = require('gulp-cmd');
var uglify = require('gulp-uglify');
var css = require('gulp-css');
var plumber = require('gulp-plumber');
var colors = transport.colors;

// alias
var alias = {
  'import-style': '/online/loader/import-style',
  'jquery': 'base/jquery/1.11.2/jquery',
  'base': 'base/base/1.2.0/base',
  'class': 'base/class/1.2.0/class',
  'events': 'base/events/1.2.0/events',
  'widget': 'base/widget/1.2.0/widget',
  'template': 'base/template/3.0.3/template',
  'templatable': 'base/templatable/0.10.0/templatable',
  'iframe-shim': 'util/iframe-shim/1.1.0/iframe-shim',
  'position': 'util/position/1.1.0/position',
  'messenger': 'util/messenger/2.1.0/messenger',
  'mask': 'common/overlay/1.2.0/mask',
  'overlay': 'common/overlay/1.2.0/overlay',
  'dialog': 'common/dialog/1.5.1/dialog',
  'confirmbox': 'common/dialog/1.5.1/confirmbox'
};

var startTime = Date.now();

// complete callback
function complete(){
  var now = new Date();

  console.log(
    '  %s [%s] build complete ... %s%s',
    colors.cyan.bold('gulp-cmd'),
    now.toLocaleString(),
    colors.green(now - startTime),
    colors.cyan('ms')
  );
}

// clean task
gulp.task('clean', function (callback){
  rimraf('online', callback);
});

// runtime task
gulp.task('runtime', ['clean'], function (){
  gulp.src('assets/loader/**/*.js', { base: 'assets' })
    .pipe(uglify())
    .pipe(gulp.dest('online'));

  gulp.src('assets/?(loader|images)/**/*.!(js)', { base: 'assets' })
    .pipe(gulp.dest('online'));
});

// online task
gulp.task('online', ['runtime'], function (){
  // all js
  gulp.src('assets/js/**/*.js', { base: 'assets/js' })
    .pipe(transport({
      alias: alias,
      ignore: ['jquery'],
      include: function (id){
        return id.indexOf('view') === 0 ? 'all' : 'relative';
      },
      css: {
        onpath: function (path){
          return path.replace('assets/', 'online/')
        }
      }
    }))
    .pipe(uglify())
    .pipe(gulp.dest('online/js'))
    .on('end', complete);

  // other file
  gulp.src('assets/js/**/*.!(js|css|json|tpl|html)')
    .pipe(gulp.dest('online/js'));

  // css
  gulp.src('assets/css/**/*.*')
    .pipe(css({ compatibility: 'ie8' }))
    .pipe(gulp.dest('online/css'));
});

// develop task
gulp.task('default', ['runtime'], function (){
  // all file
  //gulp.src('assets/js/**/*.*', { base: 'assets/js' })
  //  .pipe(transport({
  //    alias: alias,
  //    include: 'self',
  //    css: {
  //      onpath: function (path){
  //        return path.replace('assets/', 'online/')
  //      }
  //    }
  //  }))
  //  .pipe(gulp.dest('online/js'))
  //  .on('end', complete);

  gulp.src('assets/css/**/*.*', { base: 'assets' })
    .pipe(css({ compress: true }))
    .pipe(gulp.dest('online'));
});

// develop watch task
gulp.task('watch', ['default'], function (){
  var base = path.join(process.cwd(), 'assets');

  // watch all file
  gulp.watch('assets/js/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets/js' })
        .pipe(plumber())
        .pipe(transport({
          alias: alias,
          include: 'self',
          cache: false,
          css: {
            onpath: function (path){
              return path.replace('assets/', 'online/')
            }
          }
        }))
        .pipe(gulp.dest('online/js'))
        .on('end', complete);
    }
  });

  // watch all file
  gulp.watch('assets/?(images|loader|css)/**/*.*', function (e){
    if (e.type === 'deleted') {
      rimraf(path.resolve('online', path.relative(base, e.path)));
    } else {
      startTime = Date.now();

      gulp.src(e.path, { base: 'assets' })
        .pipe(plumber())
        .pipe(gulp.dest('online'))
        .on('end', complete);
    }
  });
});
<|endoftext|>


<commit_before>// Include gulp
var gulp = require('gulp');

//Dep
var del = require('del');
var less = require('gulp-less-sourcemap');
var minifyCSS = require('gulp-minify-css');
var cordova = require('gulp-cordova');
var autoprefixer = require('gulp-autoprefixer');

var folders = {
    root : "./www/",
}
folders.assets = folders.root+"assets/";
folders.less = folders.assets+"less/";
folders.css = folders.assets+"css/";
folders.platform = folders.assets+"platform/";

var platformList = ["android","browser","ios"]; //TODO generate from folder
gulp.task('clean', function() {
  //return
  del([folders.css+'/*.css',folders.css+'/*.css.map']);
  for (var i in platformList) {
	  if(platformList.hasOwnProperty(i)){
        var p = platformList[i];
        del([folders.platform + p +'/style.css',folders.platform + p +'/style.css.map'])
    }
}
  //TODO clear also platform build related
});

gulp.task('less', function () {
    //TODO add .map generation
    gulp.src(folders.less + '*.less')
      .pipe(less())
      .pipe(minifyCSS())
      .pipe(gulp.dest(folders.css));
    //TODO maybe migrate to a reserved folder in platform
    for (var i in platformList) {
        var p = platformList[i];
        gulp.src(folders.platform + p +'/*.less')
              .pipe(less())
	      .pipe(autoprefixer({
            	browsers: ['> 5%','last 2 versions','Android > 18', 'last 5 ChromeAndroid versions', 'iOS > 3'],
                cascade: false
              }))
              .pipe(minifyCSS())
              .pipe(gulp.dest(folders.platform + p));
    }
});

gulp.task('cordova:init', function() {
  gulp.src('./package.json')
    .pipe(cordova())
})

gulp.task('cordova:build', function() {
  //gulp.pipe(
    cordova(['build'])
    //)
  //TODO add specific platform build
})
// Watch for changes in files
gulp.task('watch', function() {
  // Watch .js files
  //gulp.watch(src + 'js/*.js', ['scripts']);
  // Watch .less files
  gulp.watch(folders.less + '*.less', ['clean','less']);
  gulp.watch(folders.platform + '/*/*.less', ['clean','less']);
  // Watch image files
  //gulp.watch(dest + 'img/**/*', ['images']);
});

gulp.task('build', ['clean','less', 'cordova:build']);
gulp.task('default', ['clean','less', 'watch']);

//TODO remove cli dependance for lessc ?
//TODO minify js
//TODO minify apk and other package delivery
<commit_msg>Apply autoprefix to comon css<commit_after>// Include gulp
var gulp = require('gulp');

//Dep
var del = require('del');
var less = require('gulp-less-sourcemap');
var minifyCSS = require('gulp-minify-css');
var cordova = require('gulp-cordova');
var autoprefixer = require('gulp-autoprefixer');

var folders = {
    root : "./www/",
}
folders.assets = folders.root+"assets/";
folders.less = folders.assets+"less/";
folders.css = folders.assets+"css/";
folders.platform = folders.assets+"platform/";

var platformList = ["android","browser","ios"]; //TODO generate from folder
gulp.task('clean', function() {
  //return
  del([folders.css+'/*.css',folders.css+'/*.css.map']);
  for (var i in platformList) {
	  if(platformList.hasOwnProperty(i)){
        var p = platformList[i];
        del([folders.platform + p +'/style.css',folders.platform + p +'/style.css.map'])
    }
}
  //TODO clear also platform build related
});

gulp.task('less', function () {
    //TODO add .map generation
    gulp.src(folders.less + '*.less')
      .pipe(less())
      .pipe(autoprefixer({
         browsers: ['> 5%','last 2 versions','Android > 18', 'last 5 ChromeAndroid versions', 'iOS > 3'],
         cascade: false
       }))
      .pipe(minifyCSS())
      .pipe(gulp.dest(folders.css));
    //TODO maybe migrate to a reserved folder in platform
    for (var i in platformList) {
        var p = platformList[i];
        gulp.src(folders.platform + p +'/*.less')
              .pipe(less())
	      .pipe(autoprefixer({
            	browsers: ['> 5%','last 2 versions','Android > 18', 'last 5 ChromeAndroid versions', 'iOS > 3'],
                cascade: false
              }))
              .pipe(minifyCSS())
              .pipe(gulp.dest(folders.platform + p));
    }
});

gulp.task('cordova:init', function() {
  gulp.src('./package.json')
    .pipe(cordova())
})

gulp.task('cordova:build', function() {
  //gulp.pipe(
    cordova(['build'])
    //)
  //TODO add specific platform build
})
// Watch for changes in files
gulp.task('watch', function() {
  // Watch .js files
  //gulp.watch(src + 'js/*.js', ['scripts']);
  // Watch .less files
  gulp.watch(folders.less + '*.less', ['clean','less']);
  gulp.watch(folders.platform + '/*/*.less', ['clean','less']);
  // Watch image files
  //gulp.watch(dest + 'img/**/*', ['images']);
});

gulp.task('build', ['clean','less', 'cordova:build']);
gulp.task('default', ['clean','less', 'watch']);

//TODO remove cli dependance for lessc ?
//TODO minify js
//TODO minify apk and other package delivery
<|endoftext|>


<commit_before>/**
 * Creates a queue
 *
 * @param (function(data, callback) worker
 * @param (number|function(workers, task)) concurrency
 * @return (Object)
 */
module.exports = function(worker, concurrency) {
  var workers = 0;
  var tasks = [];
  var q = {
      saturated: null
    , empty: null
    , drain: null
    , push: function(data, callback) {
        var length = tasks.push({
          data: data,
          callback: callback
        });
        if (q.saturated && concurrency(workers, null, length)) {
          q.saturated();
        }
        process.nextTick(q.process);
      }
    , process: function() {
        if (tasks.length) {
          var task = tasks.shift();
          if (q.concurrency(workers, task.data)) {
            if (q.empty && tasks.length === 0) q.empty();
            workers++;
            worker(task.data, function() {
              workers--;
              if (task.callback) task.callback.apply(task, arguments);
              if (q.drain && tasks.length + workers === 0) {
                q.drain();
              }
              q.process();
            });
          } else {
            return tasks.unshift(task);
          }
        }
      }
    , length: function() {
        return tasks.length;
      }
    , running: function() {
        return workers;
      }
  };

  q.__defineGetter__('concurrency', function() { return concurrency; });
  q.__defineSetter__('concurrency', function(c) {
    if (typeof c !== 'function') {
      concurrency = function(workers, task, length) {
        return length ? length === c : workers < c;
      };
    } else {
      concurrency = c;
    }
  });

  q.concurrency = concurrency;
  return q;
};
<commit_msg>updated queue.process<commit_after>/**
 * Creates a queue
 *
 * @param (function(data, callback) worker
 * @param (number|function(workers, task)) concurrency
 * @return (Object)
 */
module.exports = function(worker, concurrency) {
  var workers = 0;
  var tasks = [];
  var q = {
      saturated: null
    , empty: null
    , drain: null
    , push: function(data, callback) {
        var length = tasks.push({
          data: data,
          callback: callback
        });
        if (q.saturated && concurrency(workers, null, length)) {
          q.saturated();
        }
        process.nextTick(q.process);
      }
    , process: function() {
        if (tasks.length > 0) {
          var task = tasks.shift();
          if (q.concurrency(workers, task.data)) {
            if (q.empty && tasks.length === 0) q.empty();
            workers++;
            worker(task.data, function() {
              workers--;
              if (task.callback) task.callback.apply(task, arguments);
              if (q.drain && tasks.length + workers === 0) {
                q.drain();
              } else {
                q.process();
              }
            });
          } else {
            return tasks.unshift(task);
          }
        }
      }
    , length: function() {
        return tasks.length;
      }
    , running: function() {
        return workers;
      }
  };

  q.__defineGetter__('concurrency', function() { return concurrency; });
  q.__defineSetter__('concurrency', function(c) {
    if (typeof c !== 'function') {
      concurrency = function(workers, task, length) {
        return length ? length === c : workers < c;
      };
    } else {
      concurrency = c;
    }
  });

  q.concurrency = concurrency;
  return q;
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    mainBowerFiles = require('main-bower-files'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    less = require('gulp-less'),
    cleanCSS = require('gulp-clean-css'),
    jsFiles = ['src/js/*'];

gulp.task("concatVendorScripts", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.js' }))
        .pipe(concat("vendor.js"))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("concatApplicationScripts", function () {
    gulp.src(['src/js/*.js'])
        .pipe(concat("application.js"))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("compileVendorStyleCss", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.css' }))
        .pipe(concat("vendor-css.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("compileVendorStyles", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.less' }))
        .pipe(less())
        .pipe(concat("vendor-less.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("compileApplicationStyles", function () {
    gulp.src(['src/css/*.css'])
        .pipe(less())
        .pipe(concat("application.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("minifyVendorScripts", function () {
    gulp.src("assets/js/vendor.js")
        .pipe(uglify())
        .pipe(rename('vendor.min.js'))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("minifyApplicationScripts", function () {
    gulp.src("assets/js/application.js")
        .pipe(uglify())
        .pipe(rename('application.min.js'))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("minifyVendorStyles", function () {
    gulp.src("assets/css/vendor.css")
        .pipe(cleanCSS())
        .pipe(rename('vendor.min.css'))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("minifyApplicationStyles", function () {
    gulp.src(['assets/css/*.css'])
        .pipe(cleanCSS())
        .pipe(rename('application.min.css'))
        .pipe(gulp.dest("assets/css"));
});

gulp.task('copyFonts', function() {
    gulp.src([
            'bower_components/bootstrap/fonts/glyphicons-halflings-regular.*'
        ])
        .pipe(gulp.dest('assets/fonts/'));
});

// Single task
gulp.task("createDevScripts", ['concatVendorScripts', 'concatApplicationScripts']);
gulp.task("createProdScripts", ['createDevScripts', 'minifyVendorScripts', 'minifyApplicationScripts']);
gulp.task("createDevStyles", ['compileVendorStyles', 'compileVendorStyleCss', 'compileApplicationStyles', 'copyFonts']);
gulp.task("createProdStyles", ['createDevStyles', 'minifyVendorStyles', 'minifyApplicationStyles']);
gulp.task("test", ['createDevScripts', 'createDevStyles']);
gulp.task("build", ['createProdScripts', 'createProdStyles']);<commit_msg>Fix gulp build tas for production environment (#30)<commit_after>'use strict';

var gulp = require('gulp'),
    concat = require('gulp-concat'),
    mainBowerFiles = require('main-bower-files'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    less = require('gulp-less'),
    cleanCSS = require('gulp-clean-css'),
    jsFiles = ['src/js/*'];

gulp.task("concatVendorScripts", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.js' }))
        .pipe(concat("vendor.js"))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("concatApplicationScripts", function () {
    gulp.src(['src/js/*.js'])
        .pipe(concat("application.js"))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("compileVendorStyleCss", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.css' }))
        .pipe(concat("vendor-css.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("compileVendorStyles", function () {
    gulp.src(mainBowerFiles({ filter: '**/*.less' }))
        .pipe(less())
        .pipe(concat("vendor-less.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("compileApplicationStyles", function () {
    gulp.src(['src/css/*.css'])
        .pipe(less())
        .pipe(concat("application.css"))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("minifyVendorScripts", function () {
    gulp.src("assets/js/vendor.js")
        .pipe(uglify())
        .pipe(rename('vendor.min.js'))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("minifyApplicationScripts", function () {
    gulp.src("assets/js/application.js")
        .pipe(uglify())
        .pipe(rename('application.min.js'))
        .pipe(gulp.dest("assets/js"));
});

gulp.task("minifyVendorStyles", function () {
    gulp.src(['assets/css/vendor-*.css'])
        .pipe(cleanCSS())
        .pipe(rename('vendor.min.css'))
        .pipe(gulp.dest("assets/css"));
});

gulp.task("minifyApplicationStyles", function () {
    gulp.src(['assets/css/application.css'])
        .pipe(cleanCSS())
        .pipe(rename('application.min.css'))
        .pipe(gulp.dest("assets/css"));
});

gulp.task('copyFonts', function() {
    gulp.src([
            'bower_components/bootstrap/fonts/glyphicons-halflings-regular.*'
        ])
        .pipe(gulp.dest('assets/fonts/'));
});

// Single task
gulp.task("createDevScripts", ['concatVendorScripts', 'concatApplicationScripts']);
gulp.task("createProdScripts", ['createDevScripts', 'minifyVendorScripts', 'minifyApplicationScripts']);
gulp.task("createDevStyles", ['compileVendorStyles', 'compileVendorStyleCss', 'compileApplicationStyles', 'copyFonts']);
gulp.task("createProdStyles", ['createDevStyles', 'minifyVendorStyles', 'minifyApplicationStyles']);
gulp.task("test", ['createDevScripts', 'createDevStyles']);
gulp.task("build", ['createProdScripts', 'createProdStyles']);<|endoftext|>


<commit_before>import queue from './internal/queue';
import wrapAsync from './internal/wrapAsync';

/**
 * A queue of tasks for the worker function to complete.
 * @typedef {Iterable} QueueObject
 * @memberOf module:ControlFlow
 * @property {Function} length - a function returning the number of items
 * waiting to be processed. Invoke with `queue.length()`.
 * @property {boolean} started - a boolean indicating whether or not any
 * items have been pushed and processed by the queue.
 * @property {Function} running - a function returning the number of items
 * currently being processed. Invoke with `queue.running()`.
 * @property {Function} workersList - a function returning the array of items
 * currently being processed. Invoke with `queue.workersList()`.
 * @property {Function} idle - a function returning false if there are items
 * waiting or being processed, or true if not. Invoke with `queue.idle()`.
 * @property {number} concurrency - an integer for determining how many `worker`
 * functions should be run in parallel. This property can be changed after a
 * `queue` is created to alter the concurrency on-the-fly.
 * @property {number} payload - an integer that specifies how many items are
 * passed to the worker function at a time. only applies if this is a
 * [cargo]{@link module:ControlFlow.cargo} object
 * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
 * once the `worker` has finished processing the task. Instead of a single task,
 * a `tasks` array can be submitted. The respective callback is used for every
 * task in the list. Invoke with `queue.push(task, [callback])`,
 * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
 * Invoke with `queue.unshift(task, [callback])`.
 * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
 * a promise that rejects if an error occurs.
 * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns
 * a promise that rejects if an error occurs.
 * @property {Function} remove - remove items from the queue that match a test
 * function.  The test function will be passed an object with a `data` property,
 * and a `priority` property, if this is a
 * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
 * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
 * `function ({data, priority}) {}` and returns a Boolean.
 * @property {Function} saturated - a function that sets a callback that is
 * called when the number of running workers hits the `concurrency` limit, and
 * further tasks will be queued.  If the callback is omitted, `q.saturated()`
 * returns a promise for the next occurrence.
 * @property {Function} unsaturated - a function that sets a callback that is
 * called when the number of running workers is less than the `concurrency` &
 * `buffer` limits, and further tasks will not be queued. If the callback is
 * omitted, `q.unsaturated()` returns a promise for the next occurrence.
 * @property {number} buffer - A minimum threshold buffer in order to say that
 * the `queue` is `unsaturated`.
 * @property {Function} empty - a function that sets a callback that is called
 * when the last item from the `queue` is given to a `worker`. If the callback
 * is omitted, `q.empty()` returns a promise for the next occurrence.
 * @property {Function} drain - a function that sets a callback that is called
 * when the last item from the `queue` has returned from the `worker`. If the
 * callback is omitted, `q.drain()` returns a promise for the next occurrence.
 * @property {Function} error - a function that sets a callback that is called
 * when a task errors. Has the signature `function(error, task)`. If the
 * callback is omitted, `error()` returns a promise that rejects on the next
 * error.
 * @property {boolean} paused - a boolean for determining whether the queue is
 * in a paused state.
 * @property {Function} pause - a function that pauses the processing of tasks
 * until `resume()` is called. Invoke with `queue.pause()`.
 * @property {Function} resume - a function that resumes the processing of
 * queued tasks when the queue is paused. Invoke with `queue.resume()`.
 * @property {Function} kill - a function that removes the `drain` callback and
 * empties remaining tasks from the queue forcing it to go idle. No more tasks
 * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
 *
 * @example
 * const q = async.queue(worker, 2)
 * q.push(item1)
 * q.push(item2)
 * q.push(item3)
 * // queues are iterable, spread into an array to inspect
 * const items = [...q] // [item1, item2, item3]
 * // or use for of
 * for (let item of q) {
 *     console.log(item)
 * }
 *
 * q.drain(() => {
 *     console.log('all done')
 * })
 * // or
 * await q.drain()
 */

/**
 * Creates a `queue` object with the specified `concurrency`. Tasks added to the
 * `queue` are processed in parallel (up to the `concurrency` limit). If all
 * `worker`s are in progress, the task is queued until one becomes available.
 * Once a `worker` completes a `task`, that `task`'s callback is called.
 *
 * @name queue
 * @static
 * @memberOf module:ControlFlow
 * @method
 * @category Control Flow
 * @param {AsyncFunction} worker - An async function for processing a queued task.
 * If you want to handle errors from an individual task, pass a callback to
 * `q.push()`. Invoked with (task, callback).
 * @param {number} [concurrency=1] - An `integer` for determining how many
 * `worker` functions should be run in parallel.  If omitted, the concurrency
 * defaults to `1`.  If the concurrency is `0`, an error is thrown.
 * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
 * attached as certain properties to listen for specific events during the
 * lifecycle of the queue.
 * @example
 *
 * // create a queue object with concurrency 2
 * var q = async.queue(function(task, callback) {
 *     console.log('hello ' + task.name);
 *     callback();
 * }, 2);
 *
 * // assign a callback
 * q.drain(function() {
 *     console.log('all items have been processed');
 * });
 * // or await the end
 * await q.drain()
 *
 * // assign an error callback
 * q.error(function(err, task) {
 *     console.error('task experienced an error');
 * });
 *
 * // add some items to the queue
 * q.push({name: 'foo'}, function(err) {
 *     console.log('finished processing foo');
 * });
 * // callback is optional
 * q.push({name: 'bar'});
 *
 * // add some items to the queue (batch-wise)
 * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
 *     console.log('finished processing item');
 * });
 *
 * // add some items to the front of the queue
 * q.unshift({name: 'bar'}, function (err) {
 *     console.log('finished processing bar');
 * });
 */
export default function (worker, concurrency) {
    var _worker = wrapAsync(worker);
    return queue((items, cb) => {
        _worker(items[0], cb);
    }, concurrency, 1);
}
<commit_msg>V3 Docs :: Fix "unshirtAsync" typo (#1712)<commit_after>import queue from './internal/queue';
import wrapAsync from './internal/wrapAsync';

/**
 * A queue of tasks for the worker function to complete.
 * @typedef {Iterable} QueueObject
 * @memberOf module:ControlFlow
 * @property {Function} length - a function returning the number of items
 * waiting to be processed. Invoke with `queue.length()`.
 * @property {boolean} started - a boolean indicating whether or not any
 * items have been pushed and processed by the queue.
 * @property {Function} running - a function returning the number of items
 * currently being processed. Invoke with `queue.running()`.
 * @property {Function} workersList - a function returning the array of items
 * currently being processed. Invoke with `queue.workersList()`.
 * @property {Function} idle - a function returning false if there are items
 * waiting or being processed, or true if not. Invoke with `queue.idle()`.
 * @property {number} concurrency - an integer for determining how many `worker`
 * functions should be run in parallel. This property can be changed after a
 * `queue` is created to alter the concurrency on-the-fly.
 * @property {number} payload - an integer that specifies how many items are
 * passed to the worker function at a time. only applies if this is a
 * [cargo]{@link module:ControlFlow.cargo} object
 * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
 * once the `worker` has finished processing the task. Instead of a single task,
 * a `tasks` array can be submitted. The respective callback is used for every
 * task in the list. Invoke with `queue.push(task, [callback])`,
 * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
 * Invoke with `queue.unshift(task, [callback])`.
 * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
 * a promise that rejects if an error occurs.
 * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns
 * a promise that rejects if an error occurs.
 * @property {Function} remove - remove items from the queue that match a test
 * function.  The test function will be passed an object with a `data` property,
 * and a `priority` property, if this is a
 * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
 * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
 * `function ({data, priority}) {}` and returns a Boolean.
 * @property {Function} saturated - a function that sets a callback that is
 * called when the number of running workers hits the `concurrency` limit, and
 * further tasks will be queued.  If the callback is omitted, `q.saturated()`
 * returns a promise for the next occurrence.
 * @property {Function} unsaturated - a function that sets a callback that is
 * called when the number of running workers is less than the `concurrency` &
 * `buffer` limits, and further tasks will not be queued. If the callback is
 * omitted, `q.unsaturated()` returns a promise for the next occurrence.
 * @property {number} buffer - A minimum threshold buffer in order to say that
 * the `queue` is `unsaturated`.
 * @property {Function} empty - a function that sets a callback that is called
 * when the last item from the `queue` is given to a `worker`. If the callback
 * is omitted, `q.empty()` returns a promise for the next occurrence.
 * @property {Function} drain - a function that sets a callback that is called
 * when the last item from the `queue` has returned from the `worker`. If the
 * callback is omitted, `q.drain()` returns a promise for the next occurrence.
 * @property {Function} error - a function that sets a callback that is called
 * when a task errors. Has the signature `function(error, task)`. If the
 * callback is omitted, `error()` returns a promise that rejects on the next
 * error.
 * @property {boolean} paused - a boolean for determining whether the queue is
 * in a paused state.
 * @property {Function} pause - a function that pauses the processing of tasks
 * until `resume()` is called. Invoke with `queue.pause()`.
 * @property {Function} resume - a function that resumes the processing of
 * queued tasks when the queue is paused. Invoke with `queue.resume()`.
 * @property {Function} kill - a function that removes the `drain` callback and
 * empties remaining tasks from the queue forcing it to go idle. No more tasks
 * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
 *
 * @example
 * const q = async.queue(worker, 2)
 * q.push(item1)
 * q.push(item2)
 * q.push(item3)
 * // queues are iterable, spread into an array to inspect
 * const items = [...q] // [item1, item2, item3]
 * // or use for of
 * for (let item of q) {
 *     console.log(item)
 * }
 *
 * q.drain(() => {
 *     console.log('all done')
 * })
 * // or
 * await q.drain()
 */

/**
 * Creates a `queue` object with the specified `concurrency`. Tasks added to the
 * `queue` are processed in parallel (up to the `concurrency` limit). If all
 * `worker`s are in progress, the task is queued until one becomes available.
 * Once a `worker` completes a `task`, that `task`'s callback is called.
 *
 * @name queue
 * @static
 * @memberOf module:ControlFlow
 * @method
 * @category Control Flow
 * @param {AsyncFunction} worker - An async function for processing a queued task.
 * If you want to handle errors from an individual task, pass a callback to
 * `q.push()`. Invoked with (task, callback).
 * @param {number} [concurrency=1] - An `integer` for determining how many
 * `worker` functions should be run in parallel.  If omitted, the concurrency
 * defaults to `1`.  If the concurrency is `0`, an error is thrown.
 * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
 * attached as certain properties to listen for specific events during the
 * lifecycle of the queue.
 * @example
 *
 * // create a queue object with concurrency 2
 * var q = async.queue(function(task, callback) {
 *     console.log('hello ' + task.name);
 *     callback();
 * }, 2);
 *
 * // assign a callback
 * q.drain(function() {
 *     console.log('all items have been processed');
 * });
 * // or await the end
 * await q.drain()
 *
 * // assign an error callback
 * q.error(function(err, task) {
 *     console.error('task experienced an error');
 * });
 *
 * // add some items to the queue
 * q.push({name: 'foo'}, function(err) {
 *     console.log('finished processing foo');
 * });
 * // callback is optional
 * q.push({name: 'bar'});
 *
 * // add some items to the queue (batch-wise)
 * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
 *     console.log('finished processing item');
 * });
 *
 * // add some items to the front of the queue
 * q.unshift({name: 'bar'}, function (err) {
 *     console.log('finished processing bar');
 * });
 */
export default function (worker, concurrency) {
    var _worker = wrapAsync(worker);
    return queue((items, cb) => {
        _worker(items[0], cb);
    }, concurrency, 1);
}
<|endoftext|>