<commit_before>/*!
 * chaindb.js - content data management for decentraland
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * Copyright (c) 2016-2017, Manuel Araoz (MIT License).
 * Copyright (c) 2016-2017, Esteban Ordano (MIT License).
 * Copyright (c) 2016-2017, Yemel Jardi (MIT License).
 * Copyright (c) 2016-2017, The Decentraland Development Team (MIT License).
 * https://github.com/decentraland/decentraland-node
 */

'use strict';

var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var WebTorrent = require('webtorrent-hybrid');
var EventEmitter = require('events').EventEmitter;
var pass = require('stream').PassThrough;
var fs = require('fs');
var createTorrent = require('create-torrent');
var parseTorrent = require('parse-torrent');

var constants = require('../protocol/constants');
var util = require('../utils/util');
var co = require('../utils/co');

/**
 * WebTorrent-based content database
 * @exports ContentDB
 */
function ContentDB(chain) {
  if (!(this instanceof ContentDB))
    return new ContentDB(chain);

  EventEmitter.call(this);

  this.chain = chain;
  this.logger = chain.logger;
  this.network = chain.network;
  this.options = chain.options;
  this.webtorrent = new WebTorrent();
  var self = this;
  this.webtorrent.on('error', (err) => {
    self.logger.error('WebTorrent:', err.message);
  });

  var dirPath = this._dirPath();
  mkdirp.sync(dirPath);

  this.startSeeding();
}
util.inherits(ContentDB, EventEmitter);

ContentDB.prototype.startSeeding = function () {
  // Explore directory for latest version
  const testFolder = this._dirPath();
  fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
      if (!this._nameMatch(file)) {
        return;
      }
      const { x, y } = this._getCoorsFromFileName(file);
      this._seed(x, y);
    });
  });
};

const NAME_REGEX = new RegExp('^(-?\\d+)\\.(-?\\d+)\.lnd$');

ContentDB.prototype._nameMatch = function (file) {
  return !!NAME_REGEX.exec(file);
};

ContentDB.prototype._getCoorsFromFileName = function (file) {
  const res = NAME_REGEX.exec(file);
  return { x: parseInt(res[1], 10), y: parseInt(res[2], 10) };
};

ContentDB.prototype._dirPath = function () {
  return this.options.prefix + 'tiles' + path.sep;
};

ContentDB.prototype._pathFor = function (x, y, hash) {
  var dirPath = this._dirPath();
  var namePath = x + '.' + y;
  if (hash) {
    namePath += '.' + hash;
  }
  namePath += '.lnd';
  const fullPath = dirPath + namePath;
  return fullPath;
};

ContentDB.prototype._seed = co(function* _seed(x, y) {
  var self = this;
  const file = this._pathFor(x,y);
  const infoHash = yield new Promise((resolve, reject) => {
    return createTorrent(file, (err, result) => err && reject(err) || resolve(result))
  }).then(buffer => parseTorrent(buffer).infoHash)
    .catch(error => console.log(`Could not read file ${file}`, error, error.stack))

  if (infoHash) {
    self.webtorrent.seed(file,
      (torrent) => {
          self.logger.info('WebTorrent is seeding:', torrent.infoHash);
          self.logger.info('Total torrents:', self.webtorrent.torrents.length);
      }
    );
  }

  return infoHash;
});

ContentDB.prototype._copy = co(function* _copy(from, to) {
  yield fs.createReadStream(from)
    .pipe(fs.createWriteStream(to));
});

ContentDB.prototype._dump = co(function* _dump(base64content, to) {
  var content = Buffer.from(base64content, 'base64');
  var stream = new pass();
  stream.end(content);
  yield stream.pipe(fs.createWriteStream(to));
});

ContentDB.prototype.save = co(function* save(x, y, hash, stream, isCurrent) {
  const currentPath = this._pathFor(x, y);
  const historicPath = this._pathFor(x, y, hash);
  var save = stream.pipe(fs.createWriteStream(historicPath));
  var self = this;
  save.on('finish', () => {
    if (isCurrent) {
      self.logger.info(`Saving new version of ${x}, ${y} at ${historicPath}`);
      this._copy(historicPath, currentPath);
      this._seed(x , y);
    }
  });
});

ContentDB.prototype.fetch = function fetch(x, y, hash) {

  // check if we already have that file
  if (fs.existsSync(this._pathFor(x, y, hash))) {
    return;
  }

  // if null content, save default tile without downloading torrent
  if (hash === constants.NULL_HASH) {
    return;
  }

  var self = this;

  hash = hash.substr(0, 40);

  if (this.webtorrent.torrents.filter(t => t.infoHash == hash).length > 0) {
    return;
  }
  this.logger.info('ContentDB asked to fetch content, adding torrent', hash);
  this.webtorrent.add(hash, (torrent) => {
    // new torrent loaded for download
    self.logger.info(`WebTorrent new torrent loaded for ${x}, ${y}`,
      torrent.infoHash);

    torrent.on('ready', () => {
			self.logger.info('WebTorrent ready: ' + torrent.infoHash);
    });

    torrent.on('warning', (err) => {
      self.logger.warning('WebTorrent', err);
    });

    torrent.on('error', (err) => {
      self.logger.error('WebTorrent', err);
    });

		torrent.on('download', (bytes) => {
			self.logger.info('XXX just downloaded: ' + bytes);
			self.logger.info('XXX total downloaded: ' + torrent.downloaded);
			self.logger.info('XXX download speed: ' + torrent.downloadSpeed);
			self.logger.info('XXX progress: ' + torrent.progress);
		});

    torrent.on('done', () => {
      self.logger.info('WebTorrent finished downloading', torrent.infoHash);
      var content = torrent.files[0];
      self.emit('content', x, y, content, hash);
    });

  });
};

ContentDB.prototype.putFile = co(function* putFile(x, y, base64content) {
  var self = this;

  const copyPath = this._pathFor(x,y);
  yield this._dump(base64content, copyPath);
  self.logger.info('Tile file ('+x+','+y+') copy finished, starting to seed torrent');
  return this._seed(x, y);
});

module.exports = ContentDB;
<commit_msg>Update contentdb.js<commit_after>/*!
 * chaindb.js - content data management for decentraland
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
 * Copyright (c) 2016-2017, Manuel Araoz (MIT License).
 * Copyright (c) 2016-2017, Esteban Ordano (MIT License).
 * Copyright (c) 2016-2017, Yemel Jardi (MIT License).
 * Copyright (c) 2016-2017, The Decentraland Development Team (MIT License).
 * https://github.com/decentraland/decentraland-node
 */

'use strict';

var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var WebTorrent = require('webtorrent-hybrid');
var EventEmitter = require('events').EventEmitter;
var pass = require('stream').PassThrough;
var fs = require('fs');
var createTorrent = require('create-torrent');
var parseTorrent = require('parse-torrent');

var constants = require('../protocol/constants');
var util = require('../utils/util');
var co = require('../utils/co');

/**
 * WebTorrent-based content database
 * @exports ContentDB
 */
function ContentDB(chain) {
  if (!(this instanceof ContentDB))
    return new ContentDB(chain);

  EventEmitter.call(this);

  this.chain = chain;
  this.logger = chain.logger;
  this.network = chain.network;
  this.options = chain.options;
  this.webtorrent = new WebTorrent();
  var self = this;
  this.webtorrent.on('error', (err) => {
    self.logger.error('WebTorrent:', err.message);
  });

  var dirPath = this._dirPath();
  mkdirp.sync(dirPath);

  this.startSeeding();
}
util.inherits(ContentDB, EventEmitter);

ContentDB.prototype.startSeeding = function () {
  // Explore directory for latest version
  const testFolder = this._dirPath();
  fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
      if (!this._nameMatch(file)) {
        return;
      }
      const { x, y } = this._getCoorsFromFileName(file);
      this._seed(x, y);
    });
  });
};

const NAME_REGEX = new RegExp('^(-?\\d+)\\.(-?\\d+)\.lnd$');

ContentDB.prototype._nameMatch = function (file) {
  return !!NAME_REGEX.exec(file);
};

ContentDB.prototype._getCoorsFromFileName = function (file) {
  const res = NAME_REGEX.exec(file);
  return { x: parseInt(res[1], 10), y: parseInt(res[2], 10) };
};

ContentDB.prototype._dirPath = function () {
  return this.options.prefix + 'tiles' + path.sep;
};

ContentDB.prototype._pathFor = function (x, y, hash) {
  var dirPath = this._dirPath();
  var namePath = x + '.' + y;
  if (hash) {
    namePath += '.' + hash;
  }
  namePath += '.lnd';
  const fullPath = dirPath + namePath;
  return fullPath;
};

ContentDB.prototype._seed = co(function* _seed(x, y) {
  var self = this;
  const file = this._pathFor(x,y);
  const infoHash = yield new Promise((resolve, reject) => {
    return createTorrent(file, (err, result) => err && reject(err) || resolve(result))
  }).then(buffer => parseTorrent(buffer).infoHash)
    .catch(error => console.log(`Could not read file ${file}`, error, error.stack))

  if (infoHash) {
    self.webtorrent.seed(file,
      (torrent) => {
          self.logger.info('WebTorrent is seeding:', torrent.infoHash);
          self.logger.info('Total torrents:', self.webtorrent.torrents.length);
      }
    );
  }

  return infoHash;
});

ContentDB.prototype._copy = co(function* _copy(from, to) {
  yield fs.createReadStream(from)
    .pipe(fs.createWriteStream(to));
});

ContentDB.prototype._dump = co(function* _dump(base64content, to) {
  var content = Buffer.from(base64content, 'base64');
  var stream = new pass();
  stream.end(content);
  yield stream.pipe(fs.createWriteStream(to));
});

ContentDB.prototype.save = co(function* save(x, y, hash, stream, isCurrent) {
  const currentPath = this._pathFor(x, y);
  const historicPath = this._pathFor(x, y, hash);
  var save = stream.pipe(fs.createWriteStream(historicPath));
  var self = this;
  save.on('finish', () => {
    if (isCurrent) {
      self.logger.info(`Saving new version of ${x}, ${y} at ${historicPath}`);
      this._copy(historicPath, currentPath);
      this._seed(x , y);
    }
  });
});

ContentDB.prototype.fetch = function fetch(x, y, hash) {

  // if null content, save default tile without downloading torrent
  if (hash === constants.NULL_HASH) {
    return;
  }

  hash = hash.substr(0, 40);

  // check if we already have that file
  if (fs.existsSync(this._pathFor(x, y, hash))) {
    return;
  }

  var self = this;

  if (this.webtorrent.torrents.filter(t => t.infoHash == hash).length > 0) {
    return;
  }
  this.logger.info('ContentDB asked to fetch content, adding torrent', hash);
  this.webtorrent.add(hash, (torrent) => {
    // new torrent loaded for download
    self.logger.info(`WebTorrent new torrent loaded for ${x}, ${y}`,
      torrent.infoHash);

    torrent.on('ready', () => {
			self.logger.info('WebTorrent ready: ' + torrent.infoHash);
    });

    torrent.on('warning', (err) => {
      self.logger.warning('WebTorrent', err);
    });

    torrent.on('error', (err) => {
      self.logger.error('WebTorrent', err);
    });

		torrent.on('download', (bytes) => {
			self.logger.info('XXX just downloaded: ' + bytes);
			self.logger.info('XXX total downloaded: ' + torrent.downloaded);
			self.logger.info('XXX download speed: ' + torrent.downloadSpeed);
			self.logger.info('XXX progress: ' + torrent.progress);
		});

    torrent.on('done', () => {
      self.logger.info('WebTorrent finished downloading', torrent.infoHash);
      var content = torrent.files[0];
      self.emit('content', x, y, content, hash);
    });

  });
};

ContentDB.prototype.putFile = co(function* putFile(x, y, base64content) {
  var self = this;

  const copyPath = this._pathFor(x,y);
  yield this._dump(base64content, copyPath);
  self.logger.info('Tile file ('+x+','+y+') copy finished, starting to seed torrent');
  return this._seed(x, y);
});

module.exports = ContentDB;
<|endoftext|>


<commit_before>{
  addImage: [
    ['font',             'resources/CasualEncounter.png'],
    ['logo',             'resources/logo.png'],
    ['player_sprite',    'resources/walk.png'],
    ['map_spritesheet',  'resources/map_pieces.png'],
    ['enemy_sprite',  'resources/enemy_sprite.png'],
    ['block_sprite',  'resources/block_sprite.png'],
    ['background_tilesheet',  'resources/bg1.png'],
    ['explosion_sprite',  'resources/Frk_Blast1.png']
  ],

  addFont: [
    { id: 'small', image: 'font', firstletter: ' ', tileh: 20, tilew: 14, tilerow: 255, gapx: 0, gapy: 0 }
  ],

  addTiles: [
    {
      id:      'map_pieces',
      image:   'map_spritesheet',
      tileh:   32,
      tilew:   32,
      tilerow: 9,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'player_tiles',  // Set a unique ID for future reference
      image:   'player_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   64,
      tilew:   32,
      tilerow: 10,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'block_tiles',  // Set a unique ID for future reference
      image:   'block_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 3,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'background_tiles',  // Set a unique ID for future reference
      image:   'background_tilesheet', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 3,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'enemy_tiles',  // Set a unique ID for future reference
      image:   'enemy_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 2,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'explosion_tiles',  // Set a unique ID for future reference
      image:   'explosion_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   96,
      tilew:   96,
      tilerow: 14,
      gapx:    0,
      gapy:    0
    }
  ],

	// Audio resources
	addAudio:[
/*	["jump",["resources/jump.mp3","resources/jump.ogg"],{channel:"jump"}],
    ["hit",["resources/hit.mp3","resources/hit.ogg"],{channel:"hit"}],
    ["squish",["resources/sword.mp3","resources/sword.ogg"],{channel:"hit"}],
    ["explode",["resources/megaexplosion.mp3","resources/megaexplosion.ogg"],{channel:"boom"}],
    ["star",["resources/coin.mp3","resources/coin.ogg"],{channel:"hit"}]
*/	]
}<commit_msg>Re-enabling sound<commit_after>{
  addImage: [
    ['font',             'resources/CasualEncounter.png'],
    ['logo',             'resources/logo.png'],
    ['player_sprite',    'resources/walk.png'],
    ['map_spritesheet',  'resources/map_pieces.png'],
    ['enemy_sprite',  'resources/enemy_sprite.png'],
    ['block_sprite',  'resources/block_sprite.png'],
    ['background_tilesheet',  'resources/bg1.png'],
    ['explosion_sprite',  'resources/Frk_Blast1.png']
  ],

  addFont: [
    { id: 'small', image: 'font', firstletter: ' ', tileh: 20, tilew: 14, tilerow: 255, gapx: 0, gapy: 0 }
  ],

  addTiles: [
    {
      id:      'map_pieces',
      image:   'map_spritesheet',
      tileh:   32,
      tilew:   32,
      tilerow: 9,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'player_tiles',  // Set a unique ID for future reference
      image:   'player_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   64,
      tilew:   32,
      tilerow: 10,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'block_tiles',  // Set a unique ID for future reference
      image:   'block_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 3,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'background_tiles',  // Set a unique ID for future reference
      image:   'background_tilesheet', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 3,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'enemy_tiles',  // Set a unique ID for future reference
      image:   'enemy_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   32,
      tilew:   32,
      tilerow: 2,
      gapx:    0,
      gapy:    0
    },
    {
      id:      'explosion_tiles',  // Set a unique ID for future reference
      image:   'explosion_sprite', // Use the 'player_sprite' image, as loaded above
      tileh:   96,
      tilew:   96,
      tilerow: 14,
      gapx:    0,
      gapy:    0
    }
  ],

	// Audio resources
	addAudio:[
  	["jump",["resources/jump.mp3","resources/jump.ogg"],{channel:"jump"}],
    ["hit",["resources/hit.mp3","resources/hit.ogg"],{channel:"hit"}],
    ["squish",["resources/sword.mp3","resources/sword.ogg"],{channel:"hit"}],
    ["explode",["resources/megaexplosion.mp3","resources/megaexplosion.ogg"],{channel:"boom"}],
    ["star",["resources/coin.mp3","resources/coin.ogg"],{channel:"hit"}]
  	]
}<|endoftext|>


<commit_before>"use strict";

var defaultsDeep = require('ember-cli-lodash-subset').defaultsDeep;
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var ConfigLoader  = require('broccoli-config-loader');
var ConfigReplace = require('broccoli-config-replace');
var Funnel = require('broccoli-funnel');

var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var typescript = require('broccoli-typescript-compiler').typescript;
var concat = require('broccoli-concat');
var merge = require('broccoli-merge-trees');
var stew = require('broccoli-stew');
var compileSass = require('broccoli-sass');
var replace = require('broccoli-string-replace');
var mv = stew.mv;
var find = stew.find;
var map = stew.map;
var babel = require('broccoli-babel-transpiler');
var assetRev = require('broccoli-asset-rev');
var uglify = require('broccoli-uglify-sourcemap');

var RollupWithDependencies = require('./rollup-with-dependencies');
var GlimmerTemplatePrecompiler = require('./glimmer-template-precompiler');
const ModuleMapCreator = require('./module-map-creator');

var DEFAULT_CONFIG = {
  configPath: './config/environment',
  trees: {
    app: 'src',
    styles: 'src/ui/styles'
  },
  jshintrc: {
    tests: 'tests',
    app: 'src'
  }
};

module.exports = GlimmerApp;

/**
 * GlimmerApp provides an interface to a package (app, engine, or addon)
 * compatible with the module unification layout.
 *
 * @class GlimmerApp
 * @extends EmberApp
 * @constructor
 * @param {Object} [defaults]
 * @param {Object} [options={}] Configuration options
 */
function GlimmerApp(defaults, options) {
  if (arguments.length === 0) {
    options = {};
  } else if (arguments.length === 1) {
    options = defaults;
  } else {
    defaultsDeep(options, defaults);
  }

  this.appConstructor(defaultsDeep(options, DEFAULT_CONFIG));
}

GlimmerApp.__proto__ = EmberApp;

GlimmerApp.prototype = Object.create(EmberApp.prototype);
GlimmerApp.prototype.constructor = GlimmerApp;
GlimmerApp.prototype.appConstructor = EmberApp.prototype.constructor;

GlimmerApp.prototype.toTree = function(options) {
  var projectDir = process.cwd();
  var projectFolder = this.projectFolder = (options && options.projectFolder || 'src');
  var app = projectDir + '/' + projectFolder;

  console.log('Building app tree:', app);

  if (process.env.EMBER_ENV !== 'production') {
    rimraf.sync('dist');
  }

  var tsOptions = {
    tsconfig: {
      compilerOptions: {
        target: "es5",
        module: "es2015",
        inlineSourceMap: true,
        inlineSources: true,
        moduleResolution: "node",
        rootDir: '.',
        mapRoot : '/'
      },
      exclude: [
        'node_modules',
        '**/*.d.ts'
      ]
    }
  };

  var srcTree = find(app, {
    destDir: 'src'
  });

  var nodeModules = find(path.join(projectDir, 'node_modules'), {
    destDir: 'node_modules'
  });

  var tsTree = merge([srcTree, nodeModules]);

  var compiledTS = typescript(tsTree, tsOptions);

  var jsTree = find(compiledTS, {
    srcDir: 'src',
    exclude: ['config/**', '**/*.d.ts']
  });

  var hbsTree = find(projectDir, {
    include: ['src/**/*.hbs']
  });

  var resolvableTree = find([compiledTS, hbsTree], {
    srcDir: 'src',
    include: ['**/*.js', '**/*.hbs'],
    exclude: ['config/**']
  });

  var configEnvironment = find(compiledTS, {
    srcDir: 'src',
    include: ['config/environment.js']
  });

  var moduleMap = this.buildModuleMap(resolvableTree, configEnvironment);

  configEnvironment = this.rewriteConfigEnvironment(configEnvironment);

  jsTree = merge([
    jsTree,
    moduleMap,
    configEnvironment
  ]);

  hbsTree = find(hbsTree, {
    srcDir: 'src'
  });

  hbsTree = new GlimmerTemplatePrecompiler(hbsTree, {
    rootName: this.project.pkg.name
  });

  jsTree = merge([jsTree,
                  hbsTree]);

  jsTree = new RollupWithDependencies(jsTree, {
    inputFiles: ['**/*.js'],
    rollup: {
      onwarn(message) {
        // Suppress known error message caused by TypeScript compiled code with Rollup
        // https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined
        if (/The \`this\` keyword is equivalent to \`undefined\` at the top level of an ES module, and has been rewritten/.test(message)) {
          return;
        }
        console.error(message);
      },
      entry: 'index.js',
      dest: 'app.js',
      sourceMap: 'inline'
    }
  });

  if (process.env.EMBER_ENV === 'production') {
    jsTree = uglify(jsTree, {
      compress: {
        screw_ie8: true,
      },
      sourceMapConfig: {
        enabled: false
      }
    });
  }

  var htmlTree = this.index();

  var cssTree = compileSass([app + '/ui/styles'],
                            'app.scss', 'app.css');

  var appTree = merge([
    jsTree,
    htmlTree,
    cssTree,
    'public/'
  ]);

  if (process.env.EMBER_ENV === 'production') {
    var extensions = ['js'];
    var replaceExtensions = ['html', 'js'];

    if (!options.preventCssFingerPrinting) {
      extensions.push('css');
      replaceExtensions.push('css');
    }
    appTree = assetRev(appTree, {
      extensions: extensions,
      replaceExtensions: replaceExtensions
    });

    if (!options.disableCache) {
      var manifestTree = appcache(appTree, {
        cache: ['/'],
        network: ['*'],
        treeCacheEntryPathPrefix: options && options.prefix || null
      });

      appTree = merge([appTree, manifestTree]);
    }
  }

  return appTree;
}

GlimmerApp.prototype._configPath = function() {
  return path.join(this.name, 'config', 'environments', this.env + '.json');
}

GlimmerApp.prototype.rewriteConfigEnvironment = function(src) {
  return new ConfigReplace(src, this._configTree(), {
    configPath: this._configPath(),
    files: [ 'config/environment.js' ],
    patterns: this._configReplacePatterns()
  });
}

GlimmerApp.prototype.buildModuleMap = function(src, config) {
  return new ModuleMapCreator(src, this._configTree(), {
    configPath: this._configPath()
  });
}

GlimmerApp.prototype.index = function() {
  var htmlName = this.options.outputPaths.app.html;
  var files = [
    'index.html'
  ];

  var index = new Funnel(this.trees.app + '/ui', {
    files: files,
    getDestinationPath: function(relativePath) {
      if (relativePath === 'index.html') {
        relativePath = htmlName;
      }
      return relativePath;
    },
    annotation: 'Funnel: index.html'
  });

  return new ConfigReplace(index, this._configTree(), {
    configPath: path.join(this.name, 'config', 'environments', this.env + '.json'),
    files: [ htmlName ],
    patterns: this._configReplacePatterns()
  });
};

GlimmerApp.prototype._configTree = function() {
  if (this._cachedConfigTree) {
    return this._cachedConfigTree;
  }

  var configPath = this.project.configPath();
  var configTree = new ConfigLoader(path.dirname(configPath), {
    env: this.env,
    tests: this.tests,
    project: this.project
  });

  this._cachedConfigTree = new Funnel(configTree, {
    srcDir: '/',
    destDir: this.name + '/config',
    annotation: 'Funnel (config)'
  });

  return this._cachedConfigTree;
}

function getNpmDependencies(projectPath) {
  return JSON.parse(fs.readFileSync(path.join(projectPath, 'package.json'))).dependencies;
}

function getBowerDependencies(projectPath) {
  return JSON.parse(fs.readFileSync(path.join(projectPath, 'bower.json'))).dependencies;
}
<commit_msg>Allow js files in source<commit_after>"use strict";

var defaultsDeep = require('ember-cli-lodash-subset').defaultsDeep;
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var ConfigLoader  = require('broccoli-config-loader');
var ConfigReplace = require('broccoli-config-replace');
var Funnel = require('broccoli-funnel');

var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var typescript = require('broccoli-typescript-compiler').typescript;
var concat = require('broccoli-concat');
var merge = require('broccoli-merge-trees');
var stew = require('broccoli-stew');
var compileSass = require('broccoli-sass');
var replace = require('broccoli-string-replace');
var mv = stew.mv;
var find = stew.find;
var map = stew.map;
var babel = require('broccoli-babel-transpiler');
var assetRev = require('broccoli-asset-rev');
var uglify = require('broccoli-uglify-sourcemap');

var RollupWithDependencies = require('./rollup-with-dependencies');
var GlimmerTemplatePrecompiler = require('./glimmer-template-precompiler');
const ModuleMapCreator = require('./module-map-creator');

var DEFAULT_CONFIG = {
  configPath: './config/environment',
  trees: {
    app: 'src',
    styles: 'src/ui/styles'
  },
  jshintrc: {
    tests: 'tests',
    app: 'src'
  }
};

module.exports = GlimmerApp;

/**
 * GlimmerApp provides an interface to a package (app, engine, or addon)
 * compatible with the module unification layout.
 *
 * @class GlimmerApp
 * @extends EmberApp
 * @constructor
 * @param {Object} [defaults]
 * @param {Object} [options={}] Configuration options
 */
function GlimmerApp(defaults, options) {
  if (arguments.length === 0) {
    options = {};
  } else if (arguments.length === 1) {
    options = defaults;
  } else {
    defaultsDeep(options, defaults);
  }

  this.appConstructor(defaultsDeep(options, DEFAULT_CONFIG));
}

GlimmerApp.__proto__ = EmberApp;

GlimmerApp.prototype = Object.create(EmberApp.prototype);
GlimmerApp.prototype.constructor = GlimmerApp;
GlimmerApp.prototype.appConstructor = EmberApp.prototype.constructor;

GlimmerApp.prototype.toTree = function(options) {
  var projectDir = process.cwd();
  var projectFolder = this.projectFolder = (options && options.projectFolder || 'src');
  var srcDir = projectDir + '/' + projectFolder;

  console.log('Building app tree:', srcDir);

  if (process.env.EMBER_ENV !== 'production') {
    rimraf.sync('dist');
  }

  var tsOptions = {
    tsconfig: {
      compilerOptions: {
        target: "es5",
        module: "es2015",
        inlineSourceMap: true,
        inlineSources: true,
        moduleResolution: "node",
        rootDir: '.',
        mapRoot : '/'
      },
      exclude: [
        'node_modules',
        '**/*.d.ts'
      ]
    }
  };

  var srcTree = find(srcDir, {
    destDir: 'src'
  });

  var tsBypassTree = find(srcTree, {
    include: ['**/*.js']
  });

  var nodeModules = find(path.join(projectDir, 'node_modules'), {
    destDir: 'node_modules'
  });

  var tsTree = merge([srcTree, nodeModules]);

  var compiledTS = typescript(tsTree, tsOptions);

  var appTree = merge([compiledTS, tsBypassTree]);

  var jsTree = find(appTree, {
    srcDir: 'src',
    exclude: ['config/**', '**/*.d.ts']
  });

  var hbsTree = find(projectDir, {
    include: ['src/**/*.hbs']
  });

  var resolvableTree = find([appTree, hbsTree], {
    srcDir: 'src',
    include: ['**/*.js', '**/*.hbs'],
    exclude: ['config/**']
  });

  var configEnvironment = find(appTree, {
    srcDir: 'src',
    include: ['config/environment.js']
  });

  var moduleMap = this.buildModuleMap(resolvableTree, configEnvironment);

  configEnvironment = this.rewriteConfigEnvironment(configEnvironment);

  jsTree = merge([
    jsTree,
    moduleMap,
    configEnvironment
  ]);

  hbsTree = find(hbsTree, {
    srcDir: 'src'
  });

  hbsTree = new GlimmerTemplatePrecompiler(hbsTree, {
    rootName: this.project.pkg.name
  });

  jsTree = merge([jsTree,
                  hbsTree]);

  jsTree = new RollupWithDependencies(jsTree, {
    inputFiles: ['**/*.js'],
    rollup: {
      onwarn(message) {
        // Suppress known error message caused by TypeScript compiled code with Rollup
        // https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined
        if (/The \`this\` keyword is equivalent to \`undefined\` at the top level of an ES module, and has been rewritten/.test(message)) {
          return;
        }
        console.error(message);
      },
      entry: 'index.js',
      dest: 'app.js',
      sourceMap: 'inline'
    }
  });

  if (process.env.EMBER_ENV === 'production') {
    jsTree = uglify(jsTree, {
      compress: {
        screw_ie8: true,
      },
      sourceMapConfig: {
        enabled: false
      }
    });
  }

  var htmlTree = this.index();

  var cssTree = compileSass([srcDir + '/ui/styles'],
                            'app.scss', 'app.css');

  var appTree = merge([
    jsTree,
    htmlTree,
    cssTree,
    'public/'
  ]);

  if (process.env.EMBER_ENV === 'production') {
    var extensions = ['js'];
    var replaceExtensions = ['html', 'js'];

    if (!options.preventCssFingerPrinting) {
      extensions.push('css');
      replaceExtensions.push('css');
    }
    appTree = assetRev(appTree, {
      extensions: extensions,
      replaceExtensions: replaceExtensions
    });

    if (!options.disableCache) {
      var manifestTree = appcache(appTree, {
        cache: ['/'],
        network: ['*'],
        treeCacheEntryPathPrefix: options && options.prefix || null
      });

      appTree = merge([appTree, manifestTree]);
    }
  }

  return appTree;
}

GlimmerApp.prototype._configPath = function() {
  return path.join(this.name, 'config', 'environments', this.env + '.json');
}

GlimmerApp.prototype.rewriteConfigEnvironment = function(src) {
  return new ConfigReplace(src, this._configTree(), {
    configPath: this._configPath(),
    files: [ 'config/environment.js' ],
    patterns: this._configReplacePatterns()
  });
}

GlimmerApp.prototype.buildModuleMap = function(src, config) {
  return new ModuleMapCreator(src, this._configTree(), {
    configPath: this._configPath()
  });
}

GlimmerApp.prototype.index = function() {
  var htmlName = this.options.outputPaths.app.html;
  var files = [
    'index.html'
  ];

  var index = new Funnel(this.trees.app + '/ui', {
    files: files,
    getDestinationPath: function(relativePath) {
      if (relativePath === 'index.html') {
        relativePath = htmlName;
      }
      return relativePath;
    },
    annotation: 'Funnel: index.html'
  });

  return new ConfigReplace(index, this._configTree(), {
    configPath: path.join(this.name, 'config', 'environments', this.env + '.json'),
    files: [ htmlName ],
    patterns: this._configReplacePatterns()
  });
};

GlimmerApp.prototype._configTree = function() {
  if (this._cachedConfigTree) {
    return this._cachedConfigTree;
  }

  var configPath = this.project.configPath();
  var configTree = new ConfigLoader(path.dirname(configPath), {
    env: this.env,
    tests: this.tests,
    project: this.project
  });

  this._cachedConfigTree = new Funnel(configTree, {
    srcDir: '/',
    destDir: this.name + '/config',
    annotation: 'Funnel (config)'
  });

  return this._cachedConfigTree;
}

function getNpmDependencies(projectPath) {
  return JSON.parse(fs.readFileSync(path.join(projectPath, 'package.json'))).dependencies;
}

function getBowerDependencies(projectPath) {
  return JSON.parse(fs.readFileSync(path.join(projectPath, 'bower.json'))).dependencies;
}
<|endoftext|>


<commit_before>var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var watchify = require('watchify');

/**
 * Compiles js code using browserify and uglify.
 * @param {Array.<string>} sources List of JS source files.
 * @param {string} outdir Output directory.
 * @param {string} outfile Output file name.
 * @param {Object=} opt_options Options.
 */
function compilejs(sources, outdir, outfile, opt_options) {
  var bundler = browserify({
    entries: sources,
    debug: false
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}

/**
 * Watches JS code for changes and triggers compilation.
 * @param {Array.<string>} sources List of JS source files.
 * @param {string} outdir Output directory.
 * @param {string} outfile Output file name.
 * @param {Object=} opt_options Options.
 */
function watchjs(sources, outdir, outfile, opt_options) {
  var bundler = watchify(browserify({
    entries: sources,
    debug: false,
    // Watchify options:
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  bundler.on('update', function() {
    gutil.log('recompiling js...');
    rebundle_(bundler, outdir, outfile);
    gutil.log('finished recompiling js');
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}

function rebundle_(bundler, outdir, outfile, opt_options) {
  var options = opt_options || {};
  return bundler.bundle()
    .on('error', gutil.log.bind(gutil, 'browserify error'))
    .pipe(source(outfile))
    .pipe(buffer())
    .pipe(uglify(options.uglify))
    .pipe(gulp.dest(outdir));
}

module.exports = {
  compilejs: compilejs,
  watchjs: watchjs
};
<commit_msg>Pass options to rebundle on watchify updates.<commit_after>var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var watchify = require('watchify');

/**
 * Compiles js code using browserify and uglify.
 * @param {Array.<string>} sources List of JS source files.
 * @param {string} outdir Output directory.
 * @param {string} outfile Output file name.
 * @param {Object=} opt_options Options.
 */
function compilejs(sources, outdir, outfile, opt_options) {
  var bundler = browserify({
    entries: sources,
    debug: false
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}

/**
 * Watches JS code for changes and triggers compilation.
 * @param {Array.<string>} sources List of JS source files.
 * @param {string} outdir Output directory.
 * @param {string} outfile Output file name.
 * @param {Object=} opt_options Options.
 */
function watchjs(sources, outdir, outfile, opt_options) {
  var bundler = watchify(browserify({
    entries: sources,
    debug: false,
    // Watchify options:
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  bundler.on('update', function() {
    gutil.log('recompiling js...');
    rebundle_(bundler, outdir, outfile, opt_options);
    gutil.log('finished recompiling js');
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}

function rebundle_(bundler, outdir, outfile, opt_options) {
  var options = opt_options || {};
  return bundler.bundle()
    .on('error', gutil.log.bind(gutil, 'browserify error'))
    .pipe(source(outfile))
    .pipe(buffer())
    .pipe(uglify(options.uglify))
    .pipe(gulp.dest(outdir));
}

module.exports = {
  compilejs: compilejs,
  watchjs: watchjs
};
<|endoftext|>


<commit_before>const request = require('request-promise');

class BrowserstackService {
  before() {
    this.sessionId = global.browser.sessionId;
    this.auth = global.browser.requestHandler.auth || {};
    this.failures = 0;
  }

  afterSuite (suite) {
    if (suite.hasOwnProperty('err')) {
      this.failures++;
    }
  }

  afterTest (test) {
    if (!test.passed) {
      this.failures++;
    }
  }

  after() {
    return this._update(this.sessionId, this._getBody());
  }

  onReload(oldSessionId, newSessionId) {
    this.sessionId = newSessionId;
    return this._update(this.sessionId, this._getBody());
  }

  _update(sessionId, body) {
    return request({
      method: 'PUT',
      uri: `https://www.browserstack.com/automate/sessions/${sessionId}.json`,
      json: true,
      auth: this.auth,
      body
    });
  }

  _getBody() {
    return {
      status: (this.failures === 0) ? 'completed' : 'error'
    };
  }
}

module.exports = BrowserstackService;
<commit_msg>print session url; closes #5<commit_after>const request = require('request-promise');

class BrowserstackService {
  before(capabilities) {
    this.sessionId = global.browser.sessionId;
    this.auth = global.browser.requestHandler.auth || {};
    this.failures = 0;

    return request({
      uri: `https://www.browserstack.com/automate/sessions/${this.sessionId}.json`,
      json: true,
      auth: this.auth
    }, function(error, response, body) {
      if (!error && response.statusCode === 200) {
        const { device, browserName, os, os_version, browser, browser_version } = capabilities;
        const browserString = device ? `${device} ${browserName}` : `${os} ${os_version} ${browser} ${browser_version}`;
        console.log(`[Browserstack] ${browserString} session: ${body.automation_session.browser_url}`);
      }
    });
  }

  afterSuite (suite) {
    if (suite.hasOwnProperty('err')) {
      this.failures++;
    }
  }

  afterTest (test) {
    if (!test.passed) {
      this.failures++;
    }
  }

  after() {
    return this._update(this.sessionId, this._getBody());
  }

  onReload(oldSessionId, newSessionId) {
    this.sessionId = newSessionId;
    return this._update(this.sessionId, this._getBody());
  }

  _update(sessionId, body) {
    return request({
      method: 'PUT',
      uri: `https://www.browserstack.com/automate/sessions/${sessionId}.json`,
      json: true,
      auth: this.auth,
      body
    });
  }

  _getBody() {
    return {
      status: (this.failures === 0) ? 'completed' : 'error'
    };
  }
}

module.exports = BrowserstackService;
<|endoftext|>


<commit_before>import gulp from 'gulp';
import minimist from 'minimist';
import rename from 'gulp-rename';
import path from 'path';
import del from 'del';
import coffee from 'gulp-coffee';
import stream from 'vinyl-source-stream';
import browserify from 'browserify';
import coffeeify from 'coffeeify';
import { Server as Karma } from 'karma';

import { standalone } from './package';
import { filename } from './package';

const source = './src/brainstem.coffee';
const output = './lib';
const gemOutput = './vendor/assets/javascripts/';
const options = minimist(process.argv.slice(2));

// Tasks

gulp.task('prebuild', function () {
  return gulp.src('./src/**/*.coffee')
    .pipe(coffee())
    .pipe(gulp.dest(output));
});

gulp.task('build-gem', function () {
  return browserify(source, {
    standalone,
    transform: [coffeeify],
    extensions: ['.coffee']
  }).bundle()
    .pipe(stream(source))
    .pipe(rename(`${filename}.js`))
    .pipe(gulp.dest(gemOutput));
});

gulp.task('clean-gem', function () {
  return del(`${gemOutput}**/*.js`);
});

var karmaConfigFile = path.join(__dirname, 'karma.conf.js');

gulp.task('test', (done) => {
  new Karma({
    configFile: karmaConfigFile,
    singleRun: true
  }, done).start();
});

gulp.task('test-ci', (done) => {
  new Karma({
    configFile: karmaConfigFile,
    singleRun: true,
    browsers: ['Firefox']
  }, done).start();
});

gulp.task('test-watch', function (done) {
  var config = {
    configFile: karmaConfigFile,
    singleRun: false,
    autoWatch: true
  };

  if (typeof options.browsers === 'string' && options.browsers.length) {
    config.browsers = options.browsers.split();
  }

  new Karma(config, done).start();
});

<commit_msg>Update build output, add shim to gem output<commit_after>import gulp from 'gulp';
import minimist from 'minimist';
import rename from 'gulp-rename';
import path from 'path';
import del from 'del';
import coffee from 'gulp-coffee';
import stream from 'vinyl-source-stream';
import browserify from 'browserify';
import coffeeify from 'coffeeify';
import shim from 'browserify-shim';
import { Server as Karma } from 'karma';

import { standalone } from './package';
import { filename } from './package';

const source = './src/brainstem.coffee';
const options = minimist(process.argv.slice(2));

const moduleOutput = './lib';
const gemOutput = './vendor/assets/javascripts';

// Tasks

gulp.task('prebuild', function () {
  return gulp.src('./src/**/*.coffee')
    .pipe(coffee())
    .pipe(gulp.dest(moduleOutput));
});

gulp.task('build-gem', function () {
  return browserify(source, {
    standalone,
    transform: [coffeeify, shim],
    extensions: ['.coffee']
  }).bundle()
    .pipe(stream(source))
    .pipe(rename(`${filename}.js`))
    .pipe(gulp.dest(gemOutput));
});

gulp.task('clean-module', function () {
  return del(`${moduleOutput}/**/*.js`);
});

gulp.task('clean-gem', function () {
  return del(`${gemOutput}/**/*.js`);
});

var karmaConfigFile = path.join(__dirname, 'karma.conf.js');

gulp.task('test', (done) => {
  new Karma({
    configFile: karmaConfigFile,
    singleRun: true
  }, done).start();
});

gulp.task('test-ci', (done) => {
  new Karma({
    configFile: karmaConfigFile,
    singleRun: true,
    browsers: ['Firefox']
  }, done).start();
});

gulp.task('test-watch', function (done) {
  var config = {
    configFile: karmaConfigFile,
    singleRun: false,
    autoWatch: true
  };

  if (typeof options.browsers === 'string' && options.browsers.length) {
    config.browsers = options.browsers.split();
  }

  new Karma(config, done).start();
});

<|endoftext|>


<commit_before>/* Typewriter text animation */

document.addEventListener("DOMContentLoaded", function () {

  window.typewriter = {
    element: document.getElementById("typewriter"),
    contents: [
      "I write code.",
      "I write apps.",
      "I create experiences."
    ],
    contentIndex: 0,

    /* Find common words that two strings start with. */
    _commonStart: function (a, b) {
      var aWords = a.split(" ");
      var bWords = b.split(" ");

      var commonWords = [];
      for (var i=0; i<aWords.length; i++) {
        if (aWords[i] === bWords[i]) {
          commonWords.push(aWords[i]);
        } else {
          return commonWords.join(" ");
        }
      }
    },

    /* Get instructions for transforming between two strings in the form of
     * number of characters to delete and characters to add.
     */
    _transitionDescription: function(a, b) {
      var common = this._commonStart(a, b);
      var numCharactersToDelete = a.length - common.length;
      var charactersToAdd = b.slice(common.length);
      return {
        del: numCharactersToDelete,
        add: charactersToAdd
      };
    },

    /* Animate advancing to the next phrase */
    next: function(callback) {

    },

    /* Fill the element with the first phrase (non-animated) and set up other
     * miscellaneous details.
     */
    init: function() {
      this.element.textContent = this.contents[0];
      this.element.style.borderRight = "5px solid #fff";
    },

    /* Recursively continue advancing */
    play: function() {
      next(this.play);
    }

  };

  typewriter.init();

});
<commit_msg>Add animated deleting to typewriter<commit_after>/* Typewriter text animation */

document.addEventListener("DOMContentLoaded", function () {

  window.typewriter = {
    element: document.getElementById("typewriter"),
    contents: [
      "I write code.",
      "I write apps.",
      "I create experiences."
    ],
    contentIndex: 0,

    // A random delay in ms will be chosen from this range.
    typingDelay: [100, 200],

    /* Find common words that two strings start with. */
    _commonStart: function (a, b) {
      var aWords = a.split(" ");
      var bWords = b.split(" ");

      var commonWords = [];
      for (var i=0; i<aWords.length; i++) {
        if (aWords[i] === bWords[i]) {
          commonWords.push(aWords[i]);
        } else {
          return commonWords.join(" ");
        }
      }
    },

    /* Get instructions for transforming between two strings in the form of
     * number of characters to delete and characters to add.
     */
    _transitionDescription: function(a, b) {
      var common = this._commonStart(a, b);
      var numCharactersToDelete = a.length - common.length;
      var charactersToAdd = b.slice(common.length);
      return {
        del: numCharactersToDelete,
        add: charactersToAdd
      };
    },

    _getTypingDelay: function() {
      return Math.floor(Math.random() * (this.typingDelay[1] - this.typingDelay[0]) + this.typingDelay[0]);
    },

    /* Animate bacspacing by a given number of characters */
    backspace: function(num, callback) {
      var content, toGo = num;
      callback = callback || function() {};
      this._backspace1 = function() {
        if (toGo === 0) {
          callback();
        } else {
          console.log(this, this.element);
          content = this.element.textContent;
          this.element.textContent = content.slice(0, content.length - 1);
          toGo--;
          setTimeout(function(){typewriter._backspace1();}, this._getTypingDelay());
        }
      };
      this._backspace1();
    },

    /* Animate advancing to the next phrase */
    next: function(callback) {

    },

    /* Fill the element with the first phrase (non-animated) and set up other
     * miscellaneous details.
     */
    init: function() {
      this.element.textContent = this.contents[0];
      this.element.style.borderRight = "5px solid #fff";
    },

    /* Recursively continue advancing */
    play: function() {
      next(this.play);
    }

  };

  typewriter.init();

});
<|endoftext|>


<commit_before>import 'process';
import path from 'path';
import BrowserSync from 'browser-sync';
import cp from 'child_process';
import gulp from 'gulp';
import gutil from 'gulp-util';
import del from 'del';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from './webpack.conf';
import webpackDevConfig from './webpack.conf.dev';

const hugoBin = 'hugo';
const defaultArgs = ['-d', '.tmp', '--config', 'config.yml', '-v', '-t', 'code-troopers'];

const browserSync = BrowserSync.create();

gulp.task('build', ['js']);

gulp.task('serve-prod', ['build'], () => {
  browserSync.init({
    notify: false,
    open: false,
    server: {
      baseDir: './dist'
    }
  });
});

gulp.task('serve-dev', ['hugo-dev'], () => {
  const compiler = webpack(webpackDevConfig());
  const webpackMiddleware = webpackDevMiddleware(compiler, {
    publicPath: '/',
    reporter: webpackReporter
  });

  browserSync.init({
    notify: false,
    open: false,
    server: {
      baseDir: './dist',
      middleware: [
        webpackMiddleware,
        webpackHotMiddleware(compiler)
      ]
    }
  });
  process.env.SKIP_CLEAN = true
  gulp.watch('./site/**/*', ['hugo-dev', () => webpackMiddleware.invalidate()]);
});

gulp.task('hugo-dist', ['clean'], (cb) => buildSite(cb, ['-d', '.tmp']));
gulp.task('hugo-dev', ['clean'], (cb) => buildSite(cb, ['-d', 'dist', '--buildDrafts', '--buildFuture'], { WEBPACK_HOT: true }));

gulp.task('clean', () => {
  if (process.env.SKIP_CLEAN){
    return;
  }
  return del(['dist/**', '.tmp/**', '!dist', '!.tmp']);
});

gulp.task('js', ['hugo-dist'], (cb) => {
  webpack(webpackConfig(), (err, stats) => {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({
      colors: true,
      progress: true
    }));
    cb();
  });
});

function buildSite(cb, options, env = null) {
  const args = options ? defaultArgs.concat(options) : defaultArgs;
  var  nodeEnv = env && Object.assign({}, process.env, env);
  nodeEnv['PATH'] = `${path.join(__dirname, 'scripts')}:${nodeEnv['PATH']}`
  return cp.spawn(hugoBin, args, { stdio: 'inherit', env: nodeEnv }).on('close', (code) => {
    if (code === 0) {
      browserSync.reload();
      cb();
    } else {
      browserSync.notify('Hugo build failed :(');
      cb('Hugo build failed');
    }
  });
}
function webpackReporter(evt) {
  const statsOptions = {
    colors: true,
    progress: true
  };
  if (evt.state) {
    if (evt.stats.hasErrors()) {
      gutil.log('[webpack]', 'Failed to compile.');
    } else if (evt.stats.hasWarnings()) {
      gutil.log('[webpack]', 'Compiled with warnings.');
    }
    gutil.log('[webpack]', evt.stats.toString(statsOptions));
  } else {
    gutil.log('[webpack]', 'Compiling...');
  }
}
<commit_msg>feat(hugoV2): fix building error<commit_after>import 'process';
import path from 'path';
import BrowserSync from 'browser-sync';
import cp from 'child_process';
import gulp from 'gulp';
import gutil from 'gulp-util';
import del from 'del';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from './webpack.conf';
import webpackDevConfig from './webpack.conf.dev';

const hugoBin = 'hugo';
const defaultArgs = ['-d', '.tmp', '--config', 'config.yml', '-v', '-t', 'code-troopers'];

const browserSync = BrowserSync.create();

gulp.task('build', ['js']);

gulp.task('serve-prod', ['build'], () => {
  browserSync.init({
    notify: false,
    open: false,
    server: {
      baseDir: './dist'
    }
  });
});

gulp.task('serve-dev', ['hugo-dev'], () => {
  const compiler = webpack(webpackDevConfig());
  const webpackMiddleware = webpackDevMiddleware(compiler, {
    publicPath: '/',
    reporter: webpackReporter
  });

  browserSync.init({
    notify: false,
    open: false,
    server: {
      baseDir: './dist',
      middleware: [
        webpackMiddleware,
        webpackHotMiddleware(compiler)
      ]
    }
  });
  process.env.SKIP_CLEAN = true
  gulp.watch('./site/**/*', ['hugo-dev', () => webpackMiddleware.invalidate()]);
});

gulp.task('hugo-dist', ['clean'], (cb) => buildSite(cb, ['-d', '.tmp']));
gulp.task('hugo-dev', ['clean'], (cb) => buildSite(cb, ['-d', 'dist', '--buildDrafts', '--buildFuture'], { WEBPACK_HOT: true }));

gulp.task('clean', () => {
  if (process.env.SKIP_CLEAN){
    return;
  }
  return del(['dist/**', '.tmp/**', '!dist', '!.tmp']);
});

gulp.task('js', ['hugo-dist'], (cb) => {
  webpack(webpackConfig(), (err, stats) => {
    if (err) throw new gutil.PluginError('webpack', err);
    gutil.log('[webpack]', stats.toString({
      colors: true,
      progress: true
    }));
    cb();
  });
});

function buildSite(cb, options, env = null) {
  const args = options ? defaultArgs.concat(options) : defaultArgs;
  var  nodeEnv = env && Object.assign({}, process.env, env) || process.env;
  nodeEnv['PATH'] = `${path.join(__dirname, 'scripts')}:${nodeEnv['PATH']}`
  return cp.spawn(hugoBin, args, { stdio: 'inherit', env: nodeEnv }).on('close', (code) => {
    if (code === 0) {
      browserSync.reload();
      cb();
    } else {
      browserSync.notify('Hugo build failed :(');
      cb('Hugo build failed');
    }
  });
}
function webpackReporter(evt) {
  const statsOptions = {
    colors: true,
    progress: true
  };
  if (evt.state) {
    if (evt.stats.hasErrors()) {
      gutil.log('[webpack]', 'Failed to compile.');
    } else if (evt.stats.hasWarnings()) {
      gutil.log('[webpack]', 'Compiled with warnings.');
    }
    gutil.log('[webpack]', evt.stats.toString(statsOptions));
  } else {
    gutil.log('[webpack]', 'Compiling...');
  }
}
<|endoftext|>


<commit_before>/* global describe, before, it, expect, server */

import * as factory from '../../../../test-utils/factory.girl';

describe('Routes /task', () => {
  let token = null;
  let id = null;

  before((done) => {
    factory.getToken(server)
    .then((context) => {
      token = context.token;
      done();
    });
  });

  describe('POST /admin/task', () => {
    it('returns 200 HTTP status code', (done) => {
      const options = {
        method: 'POST',
        url: '/admin/task',
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title'
        }
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);

        id = response.result.id;

        done();
      });
    });
  });

  describe('PUT /admin/task', () => {
    it('returns 200 HTTP status code', (done) => {
      const options = {
        method: 'PUT',
        url: '/admin/task/' + id,
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title alter'
        }
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('return not found', (done) => {
      const options = {
        method: 'PUT',
        url: '/admin/task/100',
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title alter'
        }
      };

      server.inject(options, (response) => {
        expect(response.result).to.have.property('statusCode', 404);
        expect(response.result).to.have.property('error', 'Not Found');
        done();
      });
    });
  });

  describe('DELETE /admin/task/{id}', () => {
    it('returns 200 HTTP status code when record is deleted', (done) => {
      const options = {
        method: 'DELETE',
        url: '/admin/task/' + id,
        headers: {'Authorization': 'Bearer ' + token}
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('return not found', (done) => {
      const options = {
        method: 'DELETE',
        url: '/admin/task/100',
        headers: {'Authorization': 'Bearer ' + token}
      };
      server.inject(options, (response) => {
        expect(response.result).to.have.property('statusCode', 404);
        expect(response.result).to.have.property('error', 'Not Found');
        done();
      });
    });
  });
});
<commit_msg>add test task<commit_after>/* global describe, before, it, expect, server */

import * as factory from '../../../../test-utils/factory.girl';

describe('Routes /task', () => {
  let token = null;
  let id = null;

  before((done) => {
    factory.getToken(server)
    .then((context) => {
      token = context.token;
      done();
    });
  });

  describe('POST /admin/task', () => {
    it('returns 200 HTTP status code', (done) => {
      const options = {
        method: 'POST',
        url: '/admin/task',
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title'
        }
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);

        id = response.result.id;

        done();
      });
    });
  });

  describe('PUT /admin/task', () => {
    it('returns 200 HTTP status code', (done) => {
      const options = {
        method: 'PUT',
        url: '/admin/task/' + id,
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title alter'
        }
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('return not found', (done) => {
      const options = {
        method: 'PUT',
        url: '/admin/task/100',
        headers: {'Authorization': 'Bearer ' + token},
        payload: {
          title: 'title alter'
        }
      };

      server.inject(options, (response) => {
        expect(response.result).to.have.property('statusCode', 404);
        expect(response.result).to.have.property('error', 'Not Found');
        done();
      });
    });
  });

  describe('DELETE /admin/task/{id}', () => {
    it('returns 200 HTTP status code when record is deleted', (done) => {
      const options = {
        method: 'DELETE',
        url: '/admin/task/' + id,
        headers: {'Authorization': 'Bearer ' + token}
      };
      server.inject(options, (response) => {
        expect(response).to.have.property('statusCode', 200);
        expect(response).to.have.property('result');
        expect(response.result).to.have.property('id').to.be.a('number').to.be.above(0);
        done();
      });
    });

    it('return not found', (done) => {
      const options = {
        method: 'DELETE',
        url: '/admin/task/100',
        headers: {'Authorization': 'Bearer ' + token}
      };
      server.inject(options, (response) => {
        expect(response.result).to.have.property('statusCode', 404);
        expect(response.result).to.have.property('error', 'Not Found');
        done();
      });
    });
  });

  describe('GET /admin/task', () => {
    it('return task at a time', (done) => {
      const options = {
        method: 'GET',
        url: '/admin/task',
        headers: {'Authorization': 'Bearer ' + token}
      };
      server.inject(options, (response) => {
        expect(response.result).to.have.property('count', 1);
        expect(response.result.rows).to.contain.a.thing.with.property('id');
        expect(response.result.rows).to.contain.a.thing.with.property('title');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

// Load global config and gulp
var config  = require(__dirname + '/tasks/config/foley.json')
var argv    = require('yargs').argv
var gulp    = require('gulp')
var plumber = require('gulp-plumber')
var debug   = require('gulp-debug')
var gulpif  = require('gulp-if')

// Load modules to run tasks from files
var requireDir   = require('require-dir')
var tasks        = requireDir(__dirname + '/tasks')
var runSequence  = require('run-sequence')

// Specific task modules
var browserSync = require('browser-sync')
var watch       = require('gulp-watch')

// Assets task. Metalsmith needs to run first
gulp.task('assets', function(callback) {
  runSequence(
    'metalsmith',
    ['svgicon', 'scss', 'webpack', 'img', 'copy', 'html'],
    callback
  )
})

// BrowserSync reload task
gulp.task('reload', function(callback) {
  browserSync.reload()
  callback()
})

// Rebuild JS task.
// We need to manually reload BrowserSync after
gulp.task('rebuildJs', function(callback) {
  runSequence(
    'webpack',
    'reload',
    callback
  )
})

// Rebuild Metalsmith task. Needed because Metalsmith doesn't do incremental builds
// We need to manually reload BrowserSync after
gulp.task('rebuildMetalsmith', function(callback) {
  runSequence(
    'assets',
    'reload',
    callback
  )
})

gulp.task('test', function(callback) {
  runSequence(
    'run-jasmine',
    callback
  )
})

// Watch task
gulp.task('watch', function(callback) {
  gulp.watch(config.paths.scss + '**/*.scss', ['scss'])
  gulp.watch(config.paths.js + '**/*.js', ['rebuildJs', 'test'])
  gulp.watch(config.paths.img + '{,**/}*.{png,jpg,gif,svg}', ['img'])
  gulp.watch(config.paths.icons + '**/*.svg', ['svgicon'])
  gulp.watch([config.paths.pages + '**/*.hbs', config.paths.partials + '**/*.hbs'], ['rebuildMetalsmith'])
  gulp.watch(config.paths.tests + '**/*.js', ['test'])
})

// Watch task - just tests
gulp.task('devWatch', function(callback) {
  gulp.watch(config.paths.js + '**/*.js', ['test'])
  gulp.watch(config.paths.tests + '**/*.js', ['test'])
})

// Build website with development assets and run server with live reloading
gulp.task('default', function(callback) {
  runSequence(
    'test',
    'clean',
    'assets',
    'browsersync',
    'watch',
    callback
  )
})

// run tests
gulp.task('dev', function(callback) {
  runSequence(
    'test',
    'devWatch',
    callback
  )
})

// Build website, either with development or minified assets depending on flag
gulp.task('deploy', function(callback) {
  runSequence(
    'test',
    'clean',
    'assets',
    'crticalcss',
    callback
  )
})
<commit_msg>lintin<commit_after>'use strict'

// Load global config and gulp
var config  = require(__dirname + '/tasks/config/foley.json')
var argv    = require('yargs').argv
var gulp    = require('gulp')
var plumber = require('gulp-plumber')
var debug   = require('gulp-debug')
var gulpif  = require('gulp-if')

// Load modules to run tasks from files
var requireDir   = require('require-dir')
var tasks        = requireDir(__dirname + '/tasks')
var runSequence  = require('run-sequence')

// Specific task modules
var browserSync = require('browser-sync')
var watch       = require('gulp-watch')

// Assets task. Metalsmith needs to run first
gulp.task('assets', function (callback) {
  runSequence(
    'metalsmith',
    ['svgicon', 'scss', 'webpack', 'img', 'copy', 'html'],
    callback
  )
})

// BrowserSync reload task
gulp.task('reload', function (callback) {
  browserSync.reload()
  callback()
})

// Rebuild JS task.
// We need to manually reload BrowserSync after
gulp.task('rebuildJs', function (callback) {
  runSequence(
    'webpack',
    'reload',
    callback
  )
})

// Rebuild Metalsmith task. Needed because Metalsmith doesn't do incremental builds
// We need to manually reload BrowserSync after
gulp.task('rebuildMetalsmith', function (callback) {
  runSequence(
    'assets',
    'reload',
    callback
  )
})

gulp.task('test', function (callback) {
  runSequence(
    'run-jasmine',
    callback
  )
})

// Watch task
gulp.task('watch', function (callback) {
  gulp.watch(config.paths.scss + '**/*.scss', ['scss'])
  gulp.watch(config.paths.js + '**/*.js', ['rebuildJs', 'test'])
  gulp.watch(config.paths.img + '{,**/}*.{png,jpg,gif,svg}', ['img'])
  gulp.watch(config.paths.icons + '**/*.svg', ['svgicon'])
  gulp.watch([config.paths.pages + '**/*.hbs', config.paths.partials + '**/*.hbs'], ['rebuildMetalsmith'])
  gulp.watch(config.paths.tests + '**/*.js', ['test'])
})

// Watch task - just tests
gulp.task('devWatch', function (callback) {
  gulp.watch(config.paths.js + '**/*.js', ['test'])
  gulp.watch(config.paths.tests + '**/*.js', ['test'])
})

// Build website with development assets and run server with live reloading
gulp.task('default', function (callback) {
  runSequence(
    'test',
    'clean',
    'assets',
    'browsersync',
    'watch',
    callback
  )
})

// run tests
gulp.task('dev', function (callback) {
  runSequence(
    'test',
    'devWatch',
    callback
  )
})

// Build website, either with development or minified assets depending on flag
gulp.task('deploy', function (callback) {
  runSequence(
    'test',
    'clean',
    'assets',
    'crticalcss',
    callback
  )
})
<|endoftext|>


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

  /**
   * artoo ajaxSpider method
   * ========================
   *
   * A useful method to scrape data from a list of ajax urls.
   */
  var _root = this;

  function loop(list, params, i, acc, lastData) {
    acc = acc || [];
    i = i || 0;

    var o = (typeof list === 'function') ? list(i, lastData) : list[i];

    // Breaking if iterator returns false
    if (o === false)
      return params.done(acc);

    function get(c) {
      if (o.settings || params.settings)
        artoo.$.ajax(
          o.url || o,
          artoo.helpers.extend(
            o.settings || params.settings,
            {
              success: c,
              data: o.data || params.data || {},
              type: o.method || params.method || 'get'
            }
          )
        );
      else
        artoo.$[o.method || params.method || 'get'](
          o.url || o,
          o.data || params.data || {},
          c
        );
    }

    // Getting data with ajax
    if (params.throttle > 0)
      setTimeout(get, !i ? 0 : params.throttle, dataRetrieved);
    else if (typeof params.throttle === 'function')
      setTimeout(get, !i ? 0 : params.throttle(i), dataRetrieved);
    else
      get(dataRetrieved);

    function dataRetrieved(data) {

      // Applying callback on data
      var result = data;

      if (params.scrape || params.jquerify)
        data = artoo.helpers.jquerify(data);

      if (params.scrape) {
        result = artoo.scrape(
          data.find(params.scrape.iterator),
          params.scrape.data,
          params.scrape.params
        );
      }
      else if (typeof params.process === 'function') {
        result = params.process(data, i, acc);
      }

      // If false is returned as the callback, we break
      if (result === false)
        return params.done(acc);

      // Concat or push?
      if (params.concat)
        acc = acc.concat(result);
      else
        acc.push(result);

      // Incrementing
      i++;

      if ((artoo.helpers.isArray(list) && i === list.length) ||
          i === params.limit)
        params.done(acc);
      else
        loop(list, params, i, acc, data);
    }
  }

  // TODO: asynchronous
  artoo.ajaxSpider = function(list, params, cb) {
    var fn,
        p;

    // Default
    params = params || {};

    // If only callback
    if (typeof params === 'function') {
      fn = params;
      params = {};
      params.done = fn;
    }

    // Dealing with callback polymorphism
    if (typeof cb === 'function')
      p = artoo.helpers.extend({done: cb}, params);

    loop(list, artoo.helpers.extend(p || params, {done: artoo.helpers.noop}));
  };
}).call(this);
<commit_msg>Fix #118 adding a url param to ajaxSpider<commit_after>;(function(undefined) {
  'use strict';

  /**
   * artoo ajaxSpider method
   * ========================
   *
   * A useful method to scrape data from a list of ajax urls.
   */
  var _root = this;

  function loop(list, params, i, acc, lastData) {
    acc = acc || [];
    i = i || 0;

    var o = (typeof list === 'function') ? list(i, lastData) : list[i];

    // Breaking if iterator returns false
    if (o === false)
      return params.done(acc);

    function get(c) {
      if (o.settings || params.settings)
        artoo.$.ajax(
          o.url || params.url || o,
          artoo.helpers.extend(
            o.settings || params.settings,
            {
              success: c,
              data: o.data || params.data || {},
              type: o.method || params.method || 'get'
            }
          )
        );
      else
        artoo.$[o.method || params.method || 'get'](
          o.url || params.url || o,
          o.data || params.data || {},
          c
        );
    }

    // Getting data with ajax
    if (params.throttle > 0)
      setTimeout(get, !i ? 0 : params.throttle, dataRetrieved);
    else if (typeof params.throttle === 'function')
      setTimeout(get, !i ? 0 : params.throttle(i), dataRetrieved);
    else
      get(dataRetrieved);

    function dataRetrieved(data) {

      // Applying callback on data
      var result = data;

      if (params.scrape || params.jquerify)
        data = artoo.helpers.jquerify(data);

      if (params.scrape) {
        result = artoo.scrape(
          data.find(params.scrape.iterator),
          params.scrape.data,
          params.scrape.params
        );
      }
      else if (typeof params.process === 'function') {
        result = params.process(data, i, acc);
      }

      // If false is returned as the callback, we break
      if (result === false)
        return params.done(acc);

      // Concat or push?
      if (params.concat)
        acc = acc.concat(result);
      else
        acc.push(result);

      // Incrementing
      i++;

      if ((artoo.helpers.isArray(list) && i === list.length) ||
          i === params.limit)
        params.done(acc);
      else
        loop(list, params, i, acc, data);
    }
  }

  // TODO: asynchronous
  artoo.ajaxSpider = function(list, params, cb) {
    var fn,
        p;

    // Default
    params = params || {};

    // If only callback
    if (typeof params === 'function') {
      fn = params;
      params = {};
      params.done = fn;
    }

    // Dealing with callback polymorphism
    if (typeof cb === 'function')
      p = artoo.helpers.extend({done: cb}, params);

    loop(list, artoo.helpers.extend(p || params, {done: artoo.helpers.noop}));
  };
}).call(this);
<|endoftext|>


<commit_before>/* eslint-disable no-undef, no-console */
import bg from 'gulp-bg';
import eslint from 'gulp-eslint';
import fs from 'fs';
import gulp from 'gulp';
import mocha from 'gulp-mocha';
import os from 'os';
import path from 'path';
import runSequence from 'run-sequence';
import shell from 'gulp-shell';
import webpackBuild from './webpack/build';
import yargs from 'yargs';

const args = yargs
  .alias('p', 'production')
  .argv;

const runEslint = () => {
  return gulp.src([
    'gulpfile.babel.js',
    'src/**/*.js',
    'webpack/*.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format());
};

gulp.task('env', () => {
  process.env.NODE_ENV = args.production ? 'production' : 'development';
});

gulp.task('build-webpack', ['env'], webpackBuild);
gulp.task('build', ['build-webpack']);

gulp.task('eslint', () => {
  return runEslint();
});

gulp.task('eslint-ci', () => {
  // Exit process with an error code (1) on lint error for CI build.
  return runEslint().pipe(eslint.failAfterError());
});

gulp.task('mocha', () => {
  // read: false, not to load file contents
  gulp.src('src/**/__test__/**/*.js', {read: false})
    .pipe(mocha({
      require: ['./test/mochaSetup.js'],
      reporter: 'spec'
    }))
    .on('error', process.exit.bind(process, 1));
});

// Continuous test running
gulp.task('mocha-watch', () => {
  gulp.watch(['test/**/**', 'src/client/**', 'src/common/**'], ['mocha']);
});

gulp.task('test', done => {
  runSequence('eslint-ci', 'mocha', 'build-webpack', done);
});

gulp.task('server-node', bg('node', './src/server'));
gulp.task('server-hot', bg('node', './webpack/server'));
// Shell fixes Windows este/issues/522, bg is still needed for server-hot.
gulp.task('server-nodemon', shell.task(
  // Normalize makes path cross platform.
  path.normalize('node_modules/.bin/nodemon src/server')
));

gulp.task('server', ['env'], done => {
  if (args.production)
    runSequence('build', 'server-node', done);
  else
    runSequence('server-hot', 'server-nodemon', done);
});

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

// React Native

// Fix for custom .babelrc cache issue.
// https://github.com/facebook/react-native/issues/1924#issuecomment-120170512
gulp.task('clear-react-packager-cache', function() {
  // Clear react-packager cache
  const tempDir = os.tmpdir();

  const cacheFiles = fs.readdirSync(tempDir).filter(function(fileName) {
    return fileName.indexOf('react-packager-cache') === 0;
  });

  cacheFiles.forEach(function(cacheFile) {
    const cacheFilePath = path.join(tempDir, cacheFile);
    fs.unlinkSync(cacheFilePath);
    console.log('Deleted cache: ', cacheFilePath);
  });

  if (!cacheFiles.length) {
    console.log('No cache files found!');
  }
});
<commit_msg>Fix mocha watchmode.<commit_after>/* eslint-disable no-undef, no-console */
import bg from 'gulp-bg';
import eslint from 'gulp-eslint';
import fs from 'fs';
import gulp from 'gulp';
import gutil from 'gulp-util';
import mocha from 'gulp-mocha';
import os from 'os';
import path from 'path';
import runSequence from 'run-sequence';
import shell from 'gulp-shell';
import webpackBuild from './webpack/build';
import yargs from 'yargs';

const args = yargs
  .alias('p', 'production')
  .argv;

const runEslint = () => {
  return gulp.src([
    'gulpfile.babel.js',
    'src/**/*.js',
    'webpack/*.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format());
};

gulp.task('env', () => {
  process.env.NODE_ENV = args.production ? 'production' : 'development';
});

gulp.task('build-webpack', ['env'], webpackBuild);
gulp.task('build', ['build-webpack']);

gulp.task('eslint', () => {
  return runEslint();
});

gulp.task('eslint-ci', () => {
  // Exit process with an error code (1) on lint error for CI build.
  return runEslint().pipe(eslint.failAfterError());
});

gulp.task('mocha', () => {
  // read: false, not to load file contents
  gulp.src('src/**/__test__/**/*.js', {read: false})
    .pipe(mocha({
      require: ['./test/mochaSetup.js'],
      reporter: 'spec'
    }))
    // .on('error', process.exit.bind(process, 1));
    .on('error', gutil.log);
});

// Continuous test running
gulp.task('mocha-watch', () => {
  gulp.watch(['test/**/**', 'src/client/**', 'src/common/**'], ['mocha']);
});

gulp.task('test', done => {
  runSequence('eslint-ci', 'mocha', 'build-webpack', done);
});

gulp.task('server-node', bg('node', './src/server'));
gulp.task('server-hot', bg('node', './webpack/server'));
// Shell fixes Windows este/issues/522, bg is still needed for server-hot.
gulp.task('server-nodemon', shell.task(
  // Normalize makes path cross platform.
  path.normalize('node_modules/.bin/nodemon src/server')
));

gulp.task('server', ['env'], done => {
  if (args.production)
    runSequence('build', 'server-node', done);
  else
    runSequence('server-hot', 'server-nodemon', done);
});

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

// React Native

// Fix for custom .babelrc cache issue.
// https://github.com/facebook/react-native/issues/1924#issuecomment-120170512
gulp.task('clear-react-packager-cache', function() {
  // Clear react-packager cache
  const tempDir = os.tmpdir();

  const cacheFiles = fs.readdirSync(tempDir).filter(function(fileName) {
    return fileName.indexOf('react-packager-cache') === 0;
  });

  cacheFiles.forEach(function(cacheFile) {
    const cacheFilePath = path.join(tempDir, cacheFile);
    fs.unlinkSync(cacheFilePath);
    console.log('Deleted cache: ', cacheFilePath);
  });

  if (!cacheFiles.length) {
    console.log('No cache files found!');
  }
});
<|endoftext|>


<commit_before>import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';
import merge from 'merge-stream';
import gulpSequence from 'gulp-sequence';
import minimist from 'minimist';
import browserSyncLib from 'browser-sync';
import yargs from 'yargs';
import packageJSON from './package.json';

let $ = gulpLoadPlugins();
let browserSync = browserSyncLib.create();
let argv = yargs.argv;
let packages = packageJSON.dependencies;
let src = {};
let watch = false;

const RELEASE = argv.release;
const GOOGLE_ANALYTICS_ID = 'UA-XXXXX-X';
const AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

function onError(error) {
  let formatError = $.util.colors.red('Error (' + error.plugin + '): ' + error.message);
  $.util.log(formatError);
  $.util.beep();
  this.emit('end');
  if (!watch) {
    process.exit()
  }
}

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

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

gulp.task('vendor', () => {
  return merge(
    gulp
      .src('node_modules/jquery/dist/*.*')
      .pipe(gulp.dest('dist/vendor/jquery-' + packages.jquery)),
    gulp
      .src('node_modules/modernizr/dist/modernizr-build.min.js')
      .pipe($.plumber(onError))
      .pipe($.rename('modernizr.min.js'))
      .pipe($.uglify())
      .pipe(gulp.dest('dist/vendor/modernizr-' + packages.modernizr))

  );
});

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

gulp.task('images', () => {
  src.images = 'app/images/**/*';
  return gulp.src(src.images)
    .pipe($.plumber(onError))
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', () => {
  src.fonts = 'app/fonts/**';
  return gulp.src([
      src.fonts,
      'node_modules/bootstrap/fonts/**',
      'node_modules/font-awesome/fonts/**'
    ])
    .pipe(gulp.dest('dist/fonts'));
});

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

gulp.task('pages', () => {
  src.pages = [
    'app/pages/**/*',
    'app/layouts/**/*',
    'app/partials/**/*'
  ];
  return gulp.src(src.pages[0])
    .pipe($.plumber(onError))
    .pipe($.if(/\.jade/, $.jade({
      pretty: !RELEASE,
      locals: {
        packages: packages,
        googleAnalyticsID: GOOGLE_ANALYTICS_ID
      }
    })))
    .pipe($.if(RELEASE, $.htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      minifyJS: true,
      minifyCSS: true
    })))
    .pipe(gulp.dest('dist'));
});

gulp.task('styles', () => {
  src.styles = 'app/styles/**/*.{css,less}';
  return gulp.src('app/styles/bootstrap.less')
    .pipe($.plumber(onError))
    .pipe($.if(!RELEASE, $.sourcemaps.init()))
    .pipe($.less())
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe($.csscomb())
    .pipe(RELEASE ? $.cssmin() : $.util.noop())
    .pipe($.rename('style.css'))
    .pipe($.if(!RELEASE, $.sourcemaps.write()))
    .pipe(gulp.dest('dist/css'));
});

gulp.task('scripts', () => {
  src.scripts = [
    'app/scripts/$.js',
    'app/scripts/skillchart.js',
    'app/scripts/main.js'
  ];
  return gulp.src(src.scripts)
    .pipe($.plumber(onError))
    .pipe($.if(!RELEASE, $.sourcemaps.init()))
    .pipe($.concat('bundle.js'))
    .pipe($.if(RELEASE, $.uglify()))
    .pipe($.if(!RELEASE, $.sourcemaps.write()))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('build', gulpSequence(
  'clean', [
    'vendor',
    'assets',
    'images',
    'fonts',
    'pages',
    'styles',
    'scripts',
    'data'
  ]
));

gulp.task('serve', ['build'], () => {
  watch = true;
  browserSync.init({
    server: './dist'
  });
  gulp.watch(src.data, ['data']);
  gulp.watch(src.assets, ['assets']);
  gulp.watch(src.images, ['images']);
  gulp.watch(src.pages, ['pages']);
  gulp.watch(src.styles, ['styles']);
  gulp.watch(src.scripts, ['scripts']);
  gulp.watch('./dist/**/*.*', browserSync.reload);
});

gulp.task('deploy', () => {
  return gulp.src('dist/**/*')
    .pipe($.ghPages());
});
<commit_msg>Added Analytics id<commit_after>import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';
import merge from 'merge-stream';
import gulpSequence from 'gulp-sequence';
import minimist from 'minimist';
import browserSyncLib from 'browser-sync';
import yargs from 'yargs';
import packageJSON from './package.json';

let $ = gulpLoadPlugins();
let browserSync = browserSyncLib.create();
let argv = yargs.argv;
let packages = packageJSON.dependencies;
let src = {};
let watch = false;

const RELEASE = argv.release;
const GOOGLE_ANALYTICS_ID = 'UA-66789892-1';
const AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

function onError(error) {
  let formatError = $.util.colors.red('Error (' + error.plugin + '): ' + error.message);
  $.util.log(formatError);
  $.util.beep();
  this.emit('end');
  if (!watch) {
    process.exit()
  }
}

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

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

gulp.task('vendor', () => {
  return merge(
    gulp
      .src('node_modules/jquery/dist/*.*')
      .pipe(gulp.dest('dist/vendor/jquery-' + packages.jquery)),
    gulp
      .src('node_modules/modernizr/dist/modernizr-build.min.js')
      .pipe($.plumber(onError))
      .pipe($.rename('modernizr.min.js'))
      .pipe($.uglify())
      .pipe(gulp.dest('dist/vendor/modernizr-' + packages.modernizr))

  );
});

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

gulp.task('images', () => {
  src.images = 'app/images/**/*';
  return gulp.src(src.images)
    .pipe($.plumber(onError))
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/images'));
});

gulp.task('fonts', () => {
  src.fonts = 'app/fonts/**';
  return gulp.src([
      src.fonts,
      'node_modules/bootstrap/fonts/**',
      'node_modules/font-awesome/fonts/**'
    ])
    .pipe(gulp.dest('dist/fonts'));
});

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

gulp.task('pages', () => {
  src.pages = [
    'app/pages/**/*',
    'app/layouts/**/*',
    'app/partials/**/*'
  ];
  return gulp.src(src.pages[0])
    .pipe($.plumber(onError))
    .pipe($.if(/\.jade/, $.jade({
      pretty: !RELEASE,
      locals: {
        packages: packages,
        googleAnalyticsID: GOOGLE_ANALYTICS_ID
      }
    })))
    .pipe($.if(RELEASE, $.htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      minifyJS: true,
      minifyCSS: true
    })))
    .pipe(gulp.dest('dist'));
});

gulp.task('styles', () => {
  src.styles = 'app/styles/**/*.{css,less}';
  return gulp.src('app/styles/bootstrap.less')
    .pipe($.plumber(onError))
    .pipe($.if(!RELEASE, $.sourcemaps.init()))
    .pipe($.less())
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe($.csscomb())
    .pipe(RELEASE ? $.cssmin() : $.util.noop())
    .pipe($.rename('style.css'))
    .pipe($.if(!RELEASE, $.sourcemaps.write()))
    .pipe(gulp.dest('dist/css'));
});

gulp.task('scripts', () => {
  src.scripts = [
    'app/scripts/$.js',
    'app/scripts/skillchart.js',
    'app/scripts/main.js'
  ];
  return gulp.src(src.scripts)
    .pipe($.plumber(onError))
    .pipe($.if(!RELEASE, $.sourcemaps.init()))
    .pipe($.concat('bundle.js'))
    .pipe($.if(RELEASE, $.uglify()))
    .pipe($.if(!RELEASE, $.sourcemaps.write()))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('build', gulpSequence(
  'clean', [
    'vendor',
    'assets',
    'images',
    'fonts',
    'pages',
    'styles',
    'scripts',
    'data'
  ]
));

gulp.task('serve', ['build'], () => {
  watch = true;
  browserSync.init({
    server: './dist'
  });
  gulp.watch(src.data, ['data']);
  gulp.watch(src.assets, ['assets']);
  gulp.watch(src.images, ['images']);
  gulp.watch(src.pages, ['pages']);
  gulp.watch(src.styles, ['styles']);
  gulp.watch(src.scripts, ['scripts']);
  gulp.watch('./dist/**/*.*', browserSync.reload);
});

gulp.task('deploy', () => {
  return gulp.src('dist/**/*')
    .pipe($.ghPages());
});
<|endoftext|>