<commit_before>// Public search interface
//

'use strict';

const _         = require('lodash');
const assert    = require('assert');
const Promise   = require('bluebird');
const http      = require('http');
const fs        = require('mz/fs');
const path      = require('path');
const serialize = require('serialize-error');
const url       = require('url');
const Daemon    = require('./daemon');
const mkdirp    = Promise.promisify(require('mkdirp'));
const rimraf    = Promise.promisify(require('rimraf'));
const write     = Promise.promisify(require('write-file-atomic'));

const methods = [
  'status',
  'config',
  'execute',
  'execute_shadow',
  'reindex_start',
  'reindex_done',
  'reindex_abort'
];

function Server(root) {
  // make sure root is always an absolute path
  this.root = path.resolve(root);

  // State structure:
  //
  //  - active      (Number)  - active node id (1 or 2)
  //  - initialized (Boolean) - whether active node is configured or not
  //  - reindex     (Boolean) - whether shadow node is configured or not
  //
  this.state = null;
  this.state_file = path.join(this.root, 'state.json');

  // http server
  this.http = null;

  // daemons
  this.active = null;
  this.shadow = null;
}

Server.prototype.start = Promise.coroutine(function* (listen_url) {
  try {
    this.state = JSON.parse(yield fs.readFile(this.state_file, 'utf8'));

    assert(_.isPlainObject(this.state));
  } catch (err) {
    this.state = { active: 1, initialized: false, reindex: false };

    // make sure it's writable, avoids unreachable directories and such
    yield mkdirp(this.root);
    yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
  }

  this.active = new Daemon(this.__get_daemon_path__(true));
  this.shadow = new Daemon(this.__get_daemon_path__(false));

  if (this.state.initialized) {
    try {
      yield this.active.start();
    } catch (err) {
      if (err.code === 'EBADCONFIG') {
        // If config file doesn't exist or invalid, mark the server
        // as uninitialized (so it'll receive new config from nodeca);
        // it could happen if someone manually removes nodeX folder
        this.state.initialized = false;
        yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
      } // otherwise ignore the error (it'll try to start server next time)
    }
  }

  if (this.state.reindex) {
    try {
      yield this.shadow.start();
    } catch (err) {
      if (err.code === 'EBADCONFIG') {
        // If config file doesn't exist or invalid, stop reindex;
        // it could happen if someone manually removes nodeX folder
        this.state.reindex = false;
        yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
      } // otherwise ignore the error (it'll try to start server next time)
    }
  }

  this.http = http.createServer((req, res) => {
    Promise.resolve().then(() => {
      assert.equal(req.method, 'POST', 'Method not supported, use POST');
    }).then(() => new Promise((resolve, reject) => {
      //
      // Buffer all incoming data (arbitrarily large amount), then
      // parse it all at once. No length checks because we don't expect
      // this server to be receiving connections from untrusted sources.
      //
      let buffers = [];

      req.on('data', d => buffers.push(d));

      req.on('end', () => resolve(Buffer.concat(buffers)));

      req.on('error', err => reject(err));
    })).then(buf => {
      let data = JSON.parse(buf.toString('utf8'));

      assert(_.has(data, 'method'), "'method' is required");
      assert.notEqual(methods.indexOf(data.method), -1, 'No such rpc method');

      return this[data.method].apply(this, data.args || []);
    }).then(result => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(result) + '\n');
    }, err => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: serialize(err) }) + '\n');
    });
  });

  let url_parts = url.parse(listen_url);

  let wait_for_server = new Promise((resolve, reject) => {
    let on_listen, on_error;

    on_listen = () => {
      this.http.removeListener('listening', on_listen);
      this.http.removeListener('error', on_error);
      resolve();
    };

    on_error = err => {
      this.http.removeListener('listening', on_listen);
      this.http.removeListener('error', on_error);
      reject(err);
    };

    this.http.once('listening', on_listen);
    this.http.once('error', on_error);

    this.http.listen(url_parts.port, url_parts.hostname);
  });

  try {
    yield wait_for_server;
  } catch (err) {
    // if server is failed to start (it's the only error that happens in this
    // function), stop the server and re-throw the original error
    try { yield this.stop(); } catch (__) {}
    throw err;
  }
});

Server.prototype.stop = Promise.coroutine(function* () {
  yield Promise.map([ this.active, this.shadow ], daemon => daemon && daemon.stop());

  if (this.http) {
    yield Promise.fromCallback(callback => this.http.close(callback));
  }
});

Server.prototype.status = function () {
  return Promise.resolve({ initialized: !!this.state.initialized });
};

Server.prototype.config = Promise.coroutine(function* (config) {
  if (this.state.initialized) {
    throw new Error('Server is already configured');
  }

  this.state.active = 1;
  this.state.initialized = true;

  let daemon_path = this.__get_daemon_path__(true);

  yield mkdirp(daemon_path);
  yield write(path.join(daemon_path, 'config.json'), JSON.stringify(config, null, 2) + '\n');
  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  this.active = new Daemon(daemon_path);
  yield this.active.start();

  return { ok: 'config written' };
});

Server.prototype.reindex_start = Promise.coroutine(function* (config) {
  // if it's already started, restart it silently

  if (this.shadow) {
    yield this.shadow.stop();
    this.shadow = null;
  }

  let daemon_path = this.__get_daemon_path__(false);

  // remove old shadow daemon directory
  yield rimraf(daemon_path);

  this.state.reindex = true;

  yield mkdirp(daemon_path);
  yield write(path.join(daemon_path, 'config.json'), JSON.stringify(config, null, 2) + '\n');
  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  this.shadow = new Daemon(daemon_path);
  yield this.shadow.start();

  return { ok: 're-index started' };
});

Server.prototype.reindex_done = Promise.coroutine(function* () {
  if (!this.state.reindex) {
    return { ok: 're-index finished' };
  }

  // restart sphinx after reindex is completed to flush binlog
  yield this.shadow.stop();
  yield this.shadow.start();

  let old_active = this.active;
  let old_path = this.__get_daemon_path__(true);

  this.state.reindex = false;

  /* eslint-disable no-bitwise */
  this.active = this.shadow;
  this.state.active = 3 ^ (this.state.active || 1);

  this.state.reindex = false;

  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  if (old_active) {
    yield old_active.stop();
  }

  yield rimraf(old_path);

  return { ok: 're-index finished' };
});

Server.prototype.reindex_abort = Promise.coroutine(function* () {
  if (!this.state.reindex) {
    return { ok: 're-index aborted' };
  }

  if (this.shadow) {
    yield this.shadow.stop();
    this.shadow = null;
  }

  // remove shadow daemon directory
  yield rimraf(this.__get_daemon_path__(false));

  this.state.reindex = false;

  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  return { ok: 're-index aborted' };
});

// Search query (starts with SELECT or SHOW):
//  - execute only on `active` node
//  - return result from `active` node
//
// Update query:
//  - execute on both `active` and `shadow` nodes
//  - return result from `shadow` node
//
Server.prototype.execute = Promise.coroutine(function* (queries) {
  let first_query = Array.isArray(queries) ? queries[0] : queries;

  if (first_query.match(/^(SELECT|SHOW)\s/i)) {
    return this.active.execute(queries);
  }

  let daemons = [];

  if (this.state.reindex) {
    daemons.push(this.shadow);
  }

  daemons.push(this.active);

  let results = yield Promise.map(daemons.filter(Boolean), (daemon, idx) => {
    let promise = daemon.execute(queries);

    // only handle errors on the shadow instance if writing to both
    if (idx !== 0) promise = promise.catch(() => {});

    return promise;
  });

  return results[0] ? results[0] : null;
});

// Execute update query on `shadow` node
//
Server.prototype.execute_shadow = function (queries) {
  return this.shadow.execute(queries);
};

// Returns path to daemon root directory,
//  - for active node it's `node1` or `node2` depending on `state.active`
//  - for shadow node it's the opposite (`node2` or `node1` respectively)
//
Server.prototype.__get_daemon_path__ = function (is_active) {
  /* eslint-disable no-bitwise */
  let daemon_id = is_active ?
                  (this.state.active || 1) :
                  (3 ^ (this.state.active || 1));

  return path.join(this.root, 'node' + daemon_id);
};

module.exports = Server;
module.exports.methods = methods;
<commit_msg>Fix search interface<commit_after>// Public search interface
//

'use strict';

const _         = require('lodash');
const assert    = require('assert');
const Promise   = require('bluebird');
const http      = require('http');
const fs        = require('mz/fs');
const path      = require('path');
const serialize = require('serialize-error');
const url       = require('url');
const Daemon    = require('./daemon');
const mkdirp    = Promise.promisify(require('mkdirp'));
const rimraf    = Promise.promisify(require('rimraf'));
const write     = Promise.promisify(require('write-file-atomic'));

const methods = [
  'status',
  'config',
  'execute',
  'execute_shadow',
  'reindex_start',
  'reindex_done',
  'reindex_abort'
];

function Server(root) {
  // make sure root is always an absolute path
  this.root = path.resolve(root);

  // State structure:
  //
  //  - active      (Number)  - active node id (1 or 2)
  //  - initialized (Boolean) - whether active node is configured or not
  //  - reindex     (Boolean) - whether shadow node is configured or not
  //
  this.state = null;
  this.state_file = path.join(this.root, 'state.json');

  // http server
  this.http = null;

  // daemons
  this.active = null;
  this.shadow = null;
}

Server.prototype.start = Promise.coroutine(function* (listen_url) {
  try {
    this.state = JSON.parse(yield fs.readFile(this.state_file, 'utf8'));

    assert(_.isPlainObject(this.state));
  } catch (err) {
    this.state = { active: 1, initialized: false, reindex: false };

    // make sure it's writable, avoids unreachable directories and such
    yield mkdirp(this.root);
    yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
  }

  this.active = new Daemon(this.__get_daemon_path__(true));
  this.shadow = new Daemon(this.__get_daemon_path__(false));

  if (this.state.initialized) {
    try {
      yield this.active.start();
    } catch (err) {
      if (err.code === 'EBADCONFIG') {
        // If config file doesn't exist or invalid, mark the server
        // as uninitialized (so it'll receive new config from nodeca);
        // it could happen if someone manually removes nodeX folder
        this.state.initialized = false;
        yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
      } // otherwise ignore the error (it'll try to start server next time)
    }
  }

  if (this.state.reindex) {
    try {
      yield this.shadow.start();
    } catch (err) {
      if (err.code === 'EBADCONFIG') {
        // If config file doesn't exist or invalid, stop reindex;
        // it could happen if someone manually removes nodeX folder
        this.state.reindex = false;
        yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');
      } // otherwise ignore the error (it'll try to start server next time)
    }
  }

  this.http = http.createServer((req, res) => {
    Promise.resolve().then(() => {
      assert.equal(req.method, 'POST', 'Method not supported, use POST');
    }).then(() => new Promise((resolve, reject) => {
      //
      // Buffer all incoming data (arbitrarily large amount), then
      // parse it all at once. No length checks because we don't expect
      // this server to be receiving connections from untrusted sources.
      //
      let buffers = [];

      req.on('data', d => buffers.push(d));

      req.on('end', () => resolve(Buffer.concat(buffers)));

      req.on('error', err => reject(err));
    })).then(buf => {
      let data = JSON.parse(buf.toString('utf8'));

      assert(_.has(data, 'method'), "'method' is required");
      assert.notEqual(methods.indexOf(data.method), -1, 'No such rpc method');

      return this[data.method].apply(this, data.args || []);
    }).then(result => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(result) + '\n');
    }, err => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: serialize(err) }) + '\n');
    });
  });

  let url_parts = url.parse(listen_url);

  let wait_for_server = new Promise((resolve, reject) => {
    let on_listen, on_error;

    on_listen = () => {
      this.http.removeListener('listening', on_listen);
      this.http.removeListener('error', on_error);
      resolve();
    };

    on_error = err => {
      this.http.removeListener('listening', on_listen);
      this.http.removeListener('error', on_error);
      reject(err);
    };

    this.http.once('listening', on_listen);
    this.http.once('error', on_error);

    this.http.listen(url_parts.port, url_parts.hostname);
  });

  try {
    yield wait_for_server;
  } catch (err) {
    // if server is failed to start (it's the only error that happens in this
    // function), stop the server and re-throw the original error
    try { yield this.stop(); } catch (__) {}
    throw err;
  }
});

Server.prototype.stop = Promise.coroutine(function* () {
  yield Promise.map([ this.active, this.shadow ], daemon => daemon && daemon.stop());

  if (this.http) {
    yield Promise.fromCallback(callback => this.http.close(callback));
  }
});

Server.prototype.status = function () {
  return Promise.resolve({ initialized: !!this.state.initialized });
};

Server.prototype.config = Promise.coroutine(function* (config) {
  if (this.state.initialized) {
    throw new Error('Server is already configured');
  }

  this.state.active = 1;
  this.state.initialized = true;

  let daemon_path = this.__get_daemon_path__(true);

  yield mkdirp(daemon_path);
  yield write(path.join(daemon_path, 'config.json'), JSON.stringify(config, null, 2) + '\n');
  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  this.active = new Daemon(daemon_path);
  yield this.active.start();

  return { ok: 'config written' };
});

Server.prototype.reindex_start = Promise.coroutine(function* (config) {
  // if it's already started, restart it silently

  if (this.shadow) {
    yield this.shadow.stop();
    this.shadow = null;
  }

  let daemon_path = this.__get_daemon_path__(false);

  // remove old shadow daemon directory
  yield rimraf(daemon_path);

  this.state.reindex = true;

  yield mkdirp(daemon_path);
  yield write(path.join(daemon_path, 'config.json'), JSON.stringify(config, null, 2) + '\n');
  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  this.shadow = new Daemon(daemon_path);
  yield this.shadow.start();

  return { ok: 're-index started' };
});

Server.prototype.reindex_done = Promise.coroutine(function* () {
  if (!this.state.reindex) {
    return { ok: 're-index finished' };
  }

  // restart sphinx after reindex is completed to flush binlog
  yield this.shadow.stop();
  yield this.shadow.start();

  let old_active = this.active;
  let old_path = this.__get_daemon_path__(true);

  this.state.reindex = false;

  /* eslint-disable no-bitwise */
  this.active = this.shadow;
  this.state.active = 3 ^ (this.state.active || 1);

  this.state.reindex = false;

  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  if (old_active) {
    yield old_active.stop();
  }

  yield rimraf(old_path);

  return { ok: 're-index finished' };
});

Server.prototype.reindex_abort = Promise.coroutine(function* () {
  if (!this.state.reindex) {
    return { ok: 're-index aborted' };
  }

  if (this.shadow) {
    yield this.shadow.stop();
    this.shadow = null;
  }

  // remove shadow daemon directory
  yield rimraf(this.__get_daemon_path__(false));

  this.state.reindex = false;

  yield write(this.state_file, JSON.stringify(this.state, null, 2) + '\n');

  return { ok: 're-index aborted' };
});

// Search query (starts with SELECT or SHOW):
//  - execute only on `active` node
//  - return result from `active` node
//
// Update query:
//  - execute on both `active` and `shadow` nodes
//  - return result from `shadow` node
//
Server.prototype.execute = Promise.coroutine(function* (queries, args) {
  let first_query = Array.isArray(queries) ? queries[0] : queries;

  if (first_query.match(/^(SELECT|SHOW)\s/i)) {
    return this.active.execute(queries, args);
  }

  let daemons = [];

  if (this.state.reindex) {
    daemons.push(this.shadow);
  }

  daemons.push(this.active);

  let results = yield Promise.map(daemons.filter(Boolean), (daemon, idx) => {
    let promise = daemon.execute(queries, args);

    // only handle errors on the shadow instance if writing to both
    if (idx !== 0) promise = promise.catch(() => {});

    return promise;
  });

  return results[0] ? results[0] : null;
});

// Execute update query on `shadow` node
//
Server.prototype.execute_shadow = function (queries, args) {
  return this.shadow.execute(queries, args);
};

// Returns path to daemon root directory,
//  - for active node it's `node1` or `node2` depending on `state.active`
//  - for shadow node it's the opposite (`node2` or `node1` respectively)
//
Server.prototype.__get_daemon_path__ = function (is_active) {
  /* eslint-disable no-bitwise */
  let daemon_id = is_active ?
                  (this.state.active || 1) :
                  (3 ^ (this.state.active || 1));

  return path.join(this.root, 'node' + daemon_id);
};

module.exports = Server;
module.exports.methods = methods;
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');

    //Serve Dependencies
var connect = require('gulp-connect');
var del = require('del');
var gutil = require('gulp-util');

    //Build Dependencies
var requirejsOptimize = require('gulp-requirejs-optimize');
var minifyHTML = require('gulp-minify-html');

    //Style Dependencies
var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');
var ghPages = require('gulp-gh-pages');

    //Dev Dependancies
var jshint = require('gulp-jshint');

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

gulp.task('connect', function() {
  connect.server({
     root: 'ungentry',
  	 livereload: true
  });
});

gulp.task('html', function (){
  gulp.src('index.html')
    .pipe(connect.reload());
});

gulp.task('watch', function (){
  gulp.watch(['index.html'], ['html']);
})

gulp.task('scripts', function () {
    return gulp.src('src/main.js')
        .pipe(requirejsOptimize())
        .pipe(gulp.dest('dist'));
});

gulp.task('minify-html', function() {
  var opts = {
    conditionals: true,
    spare:true
  };
  return gulp.src('./static/html/*.html')
    .pipe(minifyHTML(opts))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('minify-css', function() {
  return gulp.src('styles/*.css')
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist'));
});

gulp.task('deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe(ghPages());
});

gulp.task('default', ['connect', 'watch'], function(){
   return gutil.log('Gulp is running!')
});
<commit_msg>gulpfile<commit_after>'use strict';

var gulp = require('gulp');

    //Serve Dependencies
var connect = require('gulp-connect');
var del = require('del');
var gutil = require('gulp-util');

    //Build Dependencies
var requirejsOptimize = require('gulp-requirejs-optimize');
var minifyHTML = require('gulp-minify-html');

    //Style Dependencies
var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');
var ghPages = require('gulp-gh-pages');

    //Dev Dependancies
var jshint = require('gulp-jshint');

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

gulp.task('connect', function() {
  connect.server({
     //root: 'ungentry',
  	 livereload: true
  });
});

gulp.task('html', function (){
  gulp.src('index.html')
    .pipe(connect.reload());
});

gulp.task('watch', function (){
  gulp.watch(['index.html'], ['html']);
})

gulp.task('scripts', function () {
    return gulp.src('src/main.js')
        .pipe(requirejsOptimize())
        .pipe(gulp.dest('dist'));
});

gulp.task('minify-html', function() {
  var opts = {
    conditionals: true,
    spare:true
  };
  return gulp.src('./static/html/*.html')
    .pipe(minifyHTML(opts))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('minify-css', function() {
  return gulp.src('styles/*.css')
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist'));
});

gulp.task('deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe(ghPages());
});

gulp.task('default', ['connect', 'watch'], function(){
   return gutil.log('Gulp is running!')
});
<|endoftext|>


<commit_before>/**
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 *
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 *
 * Copyright (C) Open-Xchange Inc., 2011
 * Mail: info@open-xchange.com
 *
 * @author Viktor Pracht <viktor.pracht@open-xchange.com>
 * @author Julian Bäume <julian.baeume@open-xchange.com>
 */

function create(options) {
    var fs = require('fs');
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var path = require('path');
    var escape = require('./common').escape;
    var normalizePath = require('./common').normalizePath;

    var verbose = (options.verbose || []).reduce(function (opt, val) {
        if (val === 'all') {
            opt.local = opt.remote = opt.proxy = true;
        } else {
            opt[val] = true;
        }
            return opt;
    }, {});
    var prefixes = options.prefixes || [];
    var manifests = options.manifests || [];

    var tzModule = 'io.ox/core/date/tz/zoneinfo/';
    var tzPath = [normalizePath(options.zoneinfo || '/usr/share/zoneinfo/')];

    var appsLoadPath = '/api/apps/load/';
    var manifestsPath = '/api/apps/manifests';
    var urlPath = normalizePath(options.path || '/appsuite');

    if (options.server) {
        options.server = normalizePath(options.server);
        var server = url.parse(options.server);
        var protocol = server.protocol === 'https:' ? https : http;
        appsLoadPath = urlPath + appsLoadPath.slice(1);
        manifestsPath = urlPath + manifestsPath.slice(1);
    }

    function httpDate(d) {
        function pad(n) { return n < 10 ? '0' + n : String(n); }
        return [
            ['Sun,', 'Mon,', 'Tue,', 'Wed,', 'Thu,', 'Fri,', 'Sat,'][d.getUTCDay()],
            pad(d.getUTCDate()),
            ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getUTCMonth()],
            d.getUTCFullYear(),
            [pad(d.getUTCHours()),
             pad(d.getUTCMinutes()),
             pad(d.getUTCSeconds())].join(':'),
            'GMT'
        ].join(' ');
    }

    http.createServer(function (request, response) {
        var URL = url.parse(request.url, true);
        if (request.method === 'GET') {
            if (URL.pathname.slice(0, appsLoadPath.length) === appsLoadPath) {
                return load(request, response);
            } else if (URL.pathname === manifestsPath &&
                       URL.query.action === 'config')
            {
                return injectManifests(request, response);
            }
        }
        if (request.url.slice(-3) === '.js') {
            return loadLocal(request, response) || proxy(request, response);
        }
        return proxy(request, response);
    }).listen(options.port || 8337);

    function load(request, response) {

        // parse request URL
        var list = url.parse(request.url).pathname.split(',');
        var version = list.shift();
        version = version.slice(version.lastIndexOf('v='));

        // find local files, request unknown files from server
        var files = [], remoteCounter = 0;
        for (var i in list) {
            var m = /^(?:\/(text|raw);)?([\w\/+-]+(?:\.[\w\/+-]+)*)$/.exec(list[i]);
            if (!m) {
                files.push(invalid(list[i]));
                continue;
            }
            if (m[2].slice(0, tzModule.length) === tzModule) {
                var paths = tzPath;
                var name = m[2].slice(tzModule.length);
            } else {
                var paths = prefixes;
                var name = m[2];
            }
            for (var j = 0; j < paths.length; j++) {
                var filename = path.join(paths[j], name);
                if (path.existsSync(filename) && fs.statSync(filename).isFile()) {
                    break;
                }
            }
            files.push(j >= paths.length ? remote(filename, list[i], m[2]) :
                       !m[1]             ? module(filename, list[i]) :
                       m[1] === 'raw'    ? raw(filename, list[i]) :
                                           text(filename, list[i]));
        }
        if (!remoteCounter) complete();

        // invalid module name
        function invalid(fullName) {
            return function () {
                console.log('Invalid module name: ' + fullName);
                response.write("console.log('Invalid module name: \"" +
                               escape(fullName) + "\"');\n");
            };
        }

        // remote file
        function remote(filename, fullName, name) {
            if (!options.server) {
                return function() {
                    console.log('Could not read', filename);
                    response.write(
                        "define('" + escape(fullName) + "', function () {\n" +
                        "  if (ox.debug) console.log(\"Could not read '" +
                            escape(name) + "'\");\n" +
                        "  throw new Error(\"Could not read '" +
                            escape(name) + "'\");\n" +
                        "});\n");
                };
            }
            remoteCounter++;
            var chunks = [];
            var URL = url.resolve(options.server,
                                  'api/apps/load/' + version + ',' + fullName);
            protocol.get(url.parse(URL), ok).on('error', error);
            return function () {
                if (verbose.remote) console.log(URL);
                for (var i = 0; i < chunks.length; i++) response.write(chunks[i]);
            };
            function ok(res) {
                if (res.statusCode === 200) {
                    res.on('data', chunk).on('end', end);
                } else {
                    res.resume();
                    console.log('HTTP error ' + res.statusCode + ' for ' + URL);
                    chunk("console.log('HTTP error " + res.statusCode + "');\n");
                    end();
                }
            }
            function error(e) {
                console.log('Server error for ' + URL + ' : ' + e.message);
                chunk("console.log('Server error: " + e.message + "');\n");
                end();
            }
            function chunk(data) { chunks.push(data); }
            function end() { if (!--remoteCounter) complete(); }
        }

        // normal RequireJS module
        function module(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                response.write(fs.readFileSync(filename) + "\n/*:oxsep:*/\n");
            };
        }

        // raw data as string (e.g. timezones)
        function raw(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                var data = fs.readFileSync(filename), s = [];
                for (var j = 0; j < data.length; j++) s.push(data[j]);
                s = String.fromCharCode.apply(String, s);
                response.write("define('" + escape(fullName) + "','" + escape(s) +
                    "');\n/*:oxsep:*/\n");
            };
        }

        // text file as a string (e.g. CSS)
        function text(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                var s = fs.readFileSync(filename, 'utf8');
                response.write("define('" + escape(fullName) + "','" + escape(s) +
                    "');\n/*:oxsep:*/\n");
            };
        }

        // send reply
        function complete() {

            // set headers
            response.setHeader('Content-Type', 'text/javascript;charset=UTF-8');
            response.setHeader('Expires', '0');

            // send data
            for (var i = 0; i < files.length; i++) files[i]();

            // all done
            response.end();
            if (verbose.local || verbose.remote) console.log();
        }
    }

    function lock() {
        var counter = 1, cb;
        var L = function (f) {
            counter++;
            return function () {
                var retval = f.apply(this, arguments);
                if (!--counter) cb();
                return retval;
            };
        };
        L.done = function (callback) {
            cb = callback;
            if (!--counter) cb();
        };
        return L;
    };

    function injectManifests(request, response) {
        if (!options.server) {
            console.error('Manifests require --server');
            response.writeHead(501, 'Manifests require --server',
                { 'Content-Type': 'text/plain' });
            response.end('Manifests require --server');
            return;
        }
        var URL = url.resolve(options.server, request.url.slice(urlPath.length));
        var opt = url.parse(URL, true);
        opt.headers = request.headers;
        opt.headers.host = opt.host;
        delete opt.headers['accept-encoding'];
        protocol.request(opt, function (res) {
            if (res.statusCode !== 200) {
                response.writeHead(res.statusCode, res.headers);
                res.pipe(response);
                return;
            }
            var reply = [], map = {}, L = lock();
            res.on('data', data).on('end', end);
            function data(chunk) { reply.push(chunk); }
            function end() {
                reply = JSON.parse(reply.join(''));
                if (reply.error) {
                    response.end(JSON.stringify(reply, null, 4));
                    return;
                }
                var list = reply.data.manifests;
                for (var i in list) map[list[i].path] = list[i];
                manifests.forEach(readDir);
                L.done(sendReply);
            }
            function readDir(dir) {
                fs.readdir(dir, L(function (err, files) {
                    if (err) return console.error(err.message);
                    files.forEach(function (file) {
                        file = path.join(dir, file);
                        if (verbose.local) console.log(file);
                        fs.readFile(file, 'utf8', L(addManifest));
                    });
                }));
            }
            function addManifest(err, manifest) {
                if (err) return console.error(err.message);
                manifest = Function('return (' + manifest + ')')();
                if (!(manifest instanceof Array)) manifest = [manifest];
                for (var i in manifest) map[manifest[i].path] = manifest[i];
            }
            function sendReply() {
                var list = reply.data.manifests = [];
                for (var i in map) {
                    if (opt.query.session || /signin/.test(map[i].namespace)) {
                        list.push(map[i]);
                    }
                }
                response.end(JSON.stringify(reply, null, 4));
                if (verbose.local) console.log();
            }
        }).end();
    }

    function loadLocal(request, response) {
        var pathname = url.parse(request.url).pathname,
            filename;
        pathname = pathname.slice(pathname.indexOf('/apps/') + 6);
        filename = prefixes.map(function (p) {
            return p + pathname;
        })
        .filter(function (filename) {
            return (path.existsSync(filename) && fs.statSync(filename).isFile());
        })[0];
        if (!filename) return false;

        // set headers
        if (verbose.local) console.log(filename);
        response.setHeader('Content-Type', 'text/javascript;charset=UTF-8');
        response.setHeader('Expires', '0');
        response.write(fs.readFileSync(filename) + "\n/*:oxsep:*/\n");
        response.end();
        return true;
    }

    function proxy(request, response) {
        var URL = request.url;
        if (!options.server) {
            console.log('No --server specified to forward', URL);
            response.writeHead(501, 'No --server specified',
                { 'Content-Type': 'text/plain' });
            response.end('No --server specified');
            return;
        }
        if (URL.slice(0, urlPath.length) === urlPath) {
            URL = URL.slice(urlPath.length);
        }
        URL = url.resolve(options.server, URL);
        if (verbose.proxy) {
            console.log(URL);
            console.log();
        }
        var opt = url.parse(URL);
        opt.method = request.method;
        opt.headers = request.headers;
        opt.headers.host = opt.host;
        request.pipe(protocol.request(opt, function (res) {
            var cookies = res.headers['set-cookie'];
            if (cookies) {
                if (typeof cookies === 'string') cookies = [cookies];
                res.headers['set-cookie'] = cookies.map(function (s) {
                    return s.replace(/;\s*secure/i, '');
                });
            }
            response.writeHead(res.statusCode, res.headers);
            res.pipe(response);
        }));
    }
}

module.exports = {
    create: create
};
<commit_msg>remove unused code<commit_after>/**
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 *
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 *
 * Copyright (C) Open-Xchange Inc., 2011
 * Mail: info@open-xchange.com
 *
 * @author Viktor Pracht <viktor.pracht@open-xchange.com>
 * @author Julian Bäume <julian.baeume@open-xchange.com>
 */

function create(options) {
    var fs = require('fs');
    var http = require('http');
    var https = require('https');
    var url = require('url');
    var path = require('path');
    var escape = require('./common').escape;
    var normalizePath = require('./common').normalizePath;

    var verbose = (options.verbose || []).reduce(function (opt, val) {
        if (val === 'all') {
            opt.local = opt.remote = opt.proxy = true;
        } else {
            opt[val] = true;
        }
            return opt;
    }, {});
    var prefixes = options.prefixes || [];
    var manifests = options.manifests || [];

    var tzModule = 'io.ox/core/date/tz/zoneinfo/';
    var tzPath = [normalizePath(options.zoneinfo || '/usr/share/zoneinfo/')];

    var appsLoadPath = '/api/apps/load/';
    var manifestsPath = '/api/apps/manifests';
    var urlPath = normalizePath(options.path || '/appsuite');

    if (options.server) {
        options.server = normalizePath(options.server);
        var server = url.parse(options.server);
        var protocol = server.protocol === 'https:' ? https : http;
        appsLoadPath = urlPath + appsLoadPath.slice(1);
        manifestsPath = urlPath + manifestsPath.slice(1);
    }

    http.createServer(function (request, response) {
        var URL = url.parse(request.url, true);
        if (request.method === 'GET') {
            if (URL.pathname.slice(0, appsLoadPath.length) === appsLoadPath) {
                return load(request, response);
            } else if (URL.pathname === manifestsPath &&
                       URL.query.action === 'config')
            {
                return injectManifests(request, response);
            }
        }
        if (request.url.slice(-3) === '.js') {
            return loadLocal(request, response) || proxy(request, response);
        }
        return proxy(request, response);
    }).listen(options.port || 8337);

    function load(request, response) {

        // parse request URL
        var list = url.parse(request.url).pathname.split(',');
        var version = list.shift();
        version = version.slice(version.lastIndexOf('v='));

        // find local files, request unknown files from server
        var files = [], remoteCounter = 0;
        for (var i in list) {
            var m = /^(?:\/(text|raw);)?([\w\/+-]+(?:\.[\w\/+-]+)*)$/.exec(list[i]);
            if (!m) {
                files.push(invalid(list[i]));
                continue;
            }
            if (m[2].slice(0, tzModule.length) === tzModule) {
                var paths = tzPath;
                var name = m[2].slice(tzModule.length);
            } else {
                var paths = prefixes;
                var name = m[2];
            }
            for (var j = 0; j < paths.length; j++) {
                var filename = path.join(paths[j], name);
                if (path.existsSync(filename) && fs.statSync(filename).isFile()) {
                    break;
                }
            }
            files.push(j >= paths.length ? remote(filename, list[i], m[2]) :
                       !m[1]             ? module(filename, list[i]) :
                       m[1] === 'raw'    ? raw(filename, list[i]) :
                                           text(filename, list[i]));
        }
        if (!remoteCounter) complete();

        // invalid module name
        function invalid(fullName) {
            return function () {
                console.log('Invalid module name: ' + fullName);
                response.write("console.log('Invalid module name: \"" +
                               escape(fullName) + "\"');\n");
            };
        }

        // remote file
        function remote(filename, fullName, name) {
            if (!options.server) {
                return function() {
                    console.log('Could not read', filename);
                    response.write(
                        "define('" + escape(fullName) + "', function () {\n" +
                        "  if (ox.debug) console.log(\"Could not read '" +
                            escape(name) + "'\");\n" +
                        "  throw new Error(\"Could not read '" +
                            escape(name) + "'\");\n" +
                        "});\n");
                };
            }
            remoteCounter++;
            var chunks = [];
            var URL = url.resolve(options.server,
                                  'api/apps/load/' + version + ',' + fullName);
            protocol.get(url.parse(URL), ok).on('error', error);
            return function () {
                if (verbose.remote) console.log(URL);
                for (var i = 0; i < chunks.length; i++) response.write(chunks[i]);
            };
            function ok(res) {
                if (res.statusCode === 200) {
                    res.on('data', chunk).on('end', end);
                } else {
                    res.resume();
                    console.log('HTTP error ' + res.statusCode + ' for ' + URL);
                    chunk("console.log('HTTP error " + res.statusCode + "');\n");
                    end();
                }
            }
            function error(e) {
                console.log('Server error for ' + URL + ' : ' + e.message);
                chunk("console.log('Server error: " + e.message + "');\n");
                end();
            }
            function chunk(data) { chunks.push(data); }
            function end() { if (!--remoteCounter) complete(); }
        }

        // normal RequireJS module
        function module(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                response.write(fs.readFileSync(filename) + "\n/*:oxsep:*/\n");
            };
        }

        // raw data as string (e.g. timezones)
        function raw(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                var data = fs.readFileSync(filename), s = [];
                for (var j = 0; j < data.length; j++) s.push(data[j]);
                s = String.fromCharCode.apply(String, s);
                response.write("define('" + escape(fullName) + "','" + escape(s) +
                    "');\n/*:oxsep:*/\n");
            };
        }

        // text file as a string (e.g. CSS)
        function text(filename, fullName) {
            return function () {
                if (verbose.local) console.log(filename);
                var s = fs.readFileSync(filename, 'utf8');
                response.write("define('" + escape(fullName) + "','" + escape(s) +
                    "');\n/*:oxsep:*/\n");
            };
        }

        // send reply
        function complete() {

            // set headers
            response.setHeader('Content-Type', 'text/javascript;charset=UTF-8');
            response.setHeader('Expires', '0');

            // send data
            for (var i = 0; i < files.length; i++) files[i]();

            // all done
            response.end();
            if (verbose.local || verbose.remote) console.log();
        }
    }

    function lock() {
        var counter = 1, cb;
        var L = function (f) {
            counter++;
            return function () {
                var retval = f.apply(this, arguments);
                if (!--counter) cb();
                return retval;
            };
        };
        L.done = function (callback) {
            cb = callback;
            if (!--counter) cb();
        };
        return L;
    };

    function injectManifests(request, response) {
        if (!options.server) {
            console.error('Manifests require --server');
            response.writeHead(501, 'Manifests require --server',
                { 'Content-Type': 'text/plain' });
            response.end('Manifests require --server');
            return;
        }
        var URL = url.resolve(options.server, request.url.slice(urlPath.length));
        var opt = url.parse(URL, true);
        opt.headers = request.headers;
        opt.headers.host = opt.host;
        delete opt.headers['accept-encoding'];
        protocol.request(opt, function (res) {
            if (res.statusCode !== 200) {
                response.writeHead(res.statusCode, res.headers);
                res.pipe(response);
                return;
            }
            var reply = [], map = {}, L = lock();
            res.on('data', data).on('end', end);
            function data(chunk) { reply.push(chunk); }
            function end() {
                reply = JSON.parse(reply.join(''));
                if (reply.error) {
                    response.end(JSON.stringify(reply, null, 4));
                    return;
                }
                var list = reply.data.manifests;
                for (var i in list) map[list[i].path] = list[i];
                manifests.forEach(readDir);
                L.done(sendReply);
            }
            function readDir(dir) {
                fs.readdir(dir, L(function (err, files) {
                    if (err) return console.error(err.message);
                    files.forEach(function (file) {
                        file = path.join(dir, file);
                        if (verbose.local) console.log(file);
                        fs.readFile(file, 'utf8', L(addManifest));
                    });
                }));
            }
            function addManifest(err, manifest) {
                if (err) return console.error(err.message);
                manifest = Function('return (' + manifest + ')')();
                if (!(manifest instanceof Array)) manifest = [manifest];
                for (var i in manifest) map[manifest[i].path] = manifest[i];
            }
            function sendReply() {
                var list = reply.data.manifests = [];
                for (var i in map) {
                    if (opt.query.session || /signin/.test(map[i].namespace)) {
                        list.push(map[i]);
                    }
                }
                response.end(JSON.stringify(reply, null, 4));
                if (verbose.local) console.log();
            }
        }).end();
    }

    function loadLocal(request, response) {
        var pathname = url.parse(request.url).pathname,
            filename;
        pathname = pathname.slice(pathname.indexOf('/apps/') + 6);
        filename = prefixes.map(function (p) {
            return p + pathname;
        })
        .filter(function (filename) {
            return (path.existsSync(filename) && fs.statSync(filename).isFile());
        })[0];
        if (!filename) return false;

        // set headers
        if (verbose.local) console.log(filename);
        response.setHeader('Content-Type', 'text/javascript;charset=UTF-8');
        response.setHeader('Expires', '0');
        response.write(fs.readFileSync(filename) + "\n/*:oxsep:*/\n");
        response.end();
        return true;
    }

    function proxy(request, response) {
        var URL = request.url;
        if (!options.server) {
            console.log('No --server specified to forward', URL);
            response.writeHead(501, 'No --server specified',
                { 'Content-Type': 'text/plain' });
            response.end('No --server specified');
            return;
        }
        if (URL.slice(0, urlPath.length) === urlPath) {
            URL = URL.slice(urlPath.length);
        }
        URL = url.resolve(options.server, URL);
        if (verbose.proxy) {
            console.log(URL);
            console.log();
        }
        var opt = url.parse(URL);
        opt.method = request.method;
        opt.headers = request.headers;
        opt.headers.host = opt.host;
        request.pipe(protocol.request(opt, function (res) {
            var cookies = res.headers['set-cookie'];
            if (cookies) {
                if (typeof cookies === 'string') cookies = [cookies];
                res.headers['set-cookie'] = cookies.map(function (s) {
                    return s.replace(/;\s*secure/i, '');
                });
            }
            response.writeHead(res.statusCode, res.headers);
            res.pipe(response);
        }));
    }
}

module.exports = {
    create: create
};
<|endoftext|>


<commit_before>'use strict';

/**
 * A server that listens to requests and serves them using pg.
 * (C) 2015 Alex Fernández.
 */

// requires
var pooled = require('./pooled.js');
var net = require('net');
var Log = require('log');
var testing = require('testing');
var profiler = require('microprofiler');
var EventEmitter = require('events').EventEmitter;

// globals
var log = new Log('info');

/**
 * Start a pg server.
 */
exports.start = function(options, callback)
{
	if (options.silent)
	{
		log = new Log('notice');
		pooled.setLogLevel('notice');
	}
	else if (options.debug)
	{
		log = new Log('debug');
		pooled.setLogLevel('debug');
	}
	var server = new Server(options);
	server.start(callback);
	return server;
};

var Server = function(options)
{
	// self-reference
	var self = this;

	// attributes
	var server;
	var connections = [];

	self.start = function(callback)
	{
		server = net.createServer(function(socket)
		{
			var connection = new Connection(options);
			connections.push(connection);
			connection.init(socket);
		});
		server.listen(options.port, function(error)
		{
			if (error)
			{
				return callback(error);
			}
			return callback(null, self);
		});
	};

	self.close = function(callback)
	{
		connections.forEach(function(connection)
		{
			connection.close();
		});
		server.close(callback);
	};
};

function testStart(callback)
{
	var options = {
		port: 5445,
		test: true,
	};
	exports.start(options, function(error, server)
	{
		testing.check(error, 'Could not start server', callback);
		server.close(function(error)
		{
			testing.check(error, 'Could not close server', callback);
			testing.success(callback);
		});
	});
}

var Connection = function(options)
{
	// self-reference
	var self = this;

	// attributes
	self.socket = null;

	self.init = function(socket)
	{
		socket.setNoDelay();
		socket.on('data', receive);
		socket.on('error', handle);
		self.socket = socket;
	};

	function receive(data)
	{
		var start = profiler.start();
		var message = JSON.parse(data);
		send(message, function(error, result)
		{
			if (error)
			{
				log.error('Could not run query %s (%s): %s', message.query, message.params, error);
				return self.socket.write('{"error": "' + error + '"}');
			}
			var response = JSON.stringify(result);
			profiler.measureFrom(start, 'server', 1000);
			self.socket.write(response);
		});
	}

	function send(message, callback)
	{
		var address = message.address || options.address;
		if (options.test)
		{
			address = 'test';
		}
		pooled.pooledConnect(address, function(error, client, done)
		{
			if (error)
			{
				return callback(error);
			}
			client.query(message.query, message.params, function(error, result)
			{
				done();
				callback(error, result);
			});
		});
	}

	function handle(error)
	{
		log.error('Error %s', error);
		self.close();
	}

	self.close = function()
	{
		self.socket.end();
		pooled.end();
	};
};

function testConnection(callback)
{
	var connection = new Connection({test: true});
	var socket = new EventEmitter();
	socket.setNoDelay = function() {};
	connection.init(socket);
	socket.write = function(message)
	{
		log.debug('Sending %s', message);
		connection.close();
	};
	socket.end = function()
	{
		testing.success(callback);
	};
	socket.emit('data', '{"query":"select current_user;"}');
}

/**
 * Run package tests.
 */
exports.test = function(callback)
{
	var tests = [
		testStart,
		testConnection,
	];
	testing.run(tests, callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	exports.test(testing.show);
}

<commit_msg>Debug messages.<commit_after>'use strict';

/**
 * A server that listens to requests and serves them using pg.
 * (C) 2015 Alex Fernández.
 */

// requires
var pooled = require('./pooled.js');
var net = require('net');
var Log = require('log');
var testing = require('testing');
var profiler = require('microprofiler');
var EventEmitter = require('events').EventEmitter;

// globals
var log = new Log('info');

/**
 * Start a pg server.
 */
exports.start = function(options, callback)
{
	if (options.silent)
	{
		log = new Log('notice');
		pooled.setLogLevel('notice');
	}
	else if (options.debug)
	{
		log = new Log('debug');
		pooled.setLogLevel('debug');
	}
	var server = new Server(options);
	server.start(callback);
	return server;
};

var Server = function(options)
{
	// self-reference
	var self = this;

	// attributes
	var server;
	var connections = [];

	self.start = function(callback)
	{
		server = net.createServer(function(socket)
		{
			var connection = new Connection(options);
			connections.push(connection);
			connection.init(socket);
		});
		server.listen(options.port, function(error)
		{
			if (error)
			{
				return callback(error);
			}
			return callback(null, self);
		});
	};

	self.close = function(callback)
	{
		connections.forEach(function(connection)
		{
			connection.close();
		});
		server.close(callback);
	};
};

function testStart(callback)
{
	var options = {
		port: 5445,
		test: true,
	};
	exports.start(options, function(error, server)
	{
		testing.check(error, 'Could not start server', callback);
		server.close(function(error)
		{
			testing.check(error, 'Could not close server', callback);
			testing.success(callback);
		});
	});
}

var Connection = function(options)
{
	// self-reference
	var self = this;

	// attributes
	self.socket = null;

	self.init = function(socket)
	{
		log.debug('Initing socket');
		socket.setNoDelay();
		socket.on('data', receive);
		socket.on('error', handle);
		self.socket = socket;
	};

	function receive(data)
	{
		log.debug('Received %s', data);
		var start = profiler.start();
		var message = JSON.parse(data);
		send(message, function(error, result)
		{
			if (error)
			{
				log.error('Could not run query %s (%s): %s', message.query, message.params, error);
				return self.socket.write('{"error": "' + error + '"}');
			}
			var response = JSON.stringify(result);
			profiler.measureFrom(start, 'server', 1000);
			self.socket.write(response);
		});
	}

	function send(message, callback)
	{
		var address = message.address || options.address;
		if (options.test)
		{
			address = 'test';
		}
		pooled.pooledConnect(address, function(error, client, done)
		{
			if (error)
			{
				return callback(error);
			}
			client.query(message.query, message.params, function(error, result)
			{
				done();
				callback(error, result);
			});
		});
	}

	function handle(error)
	{
		log.error('Error %s', error);
		self.close();
	}

	self.close = function()
	{
		self.socket.end();
		pooled.end();
	};
};

function testConnection(callback)
{
	var connection = new Connection({test: true});
	var socket = new EventEmitter();
	socket.setNoDelay = function() {};
	connection.init(socket);
	socket.write = function(message)
	{
		log.debug('Sending %s', message);
		connection.close();
	};
	socket.end = function()
	{
		testing.success(callback);
	};
	socket.emit('data', '{"query":"select current_user;"}');
}

/**
 * Run package tests.
 */
exports.test = function(callback)
{
	var tests = [
		testStart,
		testConnection,
	];
	testing.run(tests, callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	exports.test(testing.show);
}

<|endoftext|>


<commit_before>const gulp = require('gulp');
const globby = require('globby');
const path = require('path');
const fs = require('fs');
const index = require('create-index');
const shelljs = require('shelljs');

gulp.task('compile', () => {
    shelljs.exec('yarn run build');
});

gulp.task('create-index', () => {
    console.log('Creating indexing files ...');

    globby(['engine/**/', '!engine/'], {}).then((matches) => {
        matches.map((dir) => {
            globby([dir + '*.ts'], {}).then((files) => {
                generateExports(files, dir, false);
            });
        })
    });

    globby(['engine/**/', '!engine/'], {}).then((matches) => {
        generateExports(matches, 'engine', true);
    });

});

gulp.task('publish', ['create-index', 'compile'], () => {

    console.log(`Patching new version ...`);
    shelljs.exec('npm version patch --force');

    console.log(`Writing publish package.json ...`);
    const package = fs.readFileSync('./package.json');
    const packageConfig = JSON.parse(package);

    const distPackageConfig = {};

    distPackageConfig.name = packageConfig.name;
    distPackageConfig.version = packageConfig.version;
    distPackageConfig.author = packageConfig.author;
    distPackageConfig.license = packageConfig.license;
    distPackageConfig.repository = packageConfig.repository;
    distPackageConfig.dependencies = packageConfig.dependencies;
    distPackageConfig.main = './engine/index.js';

    fs.writeFileSync('dist/package.json', JSON.stringify(distPackageConfig, null, 2));

    shelljs.exec('cd dist && npm publish');
});

function generateExports(files, saveDir, isDir = false) {
    let exportData = '';

    files.map((file) => {

        let parsedData = path.parse(file);
        let filename = '';
        if (isDir) {
            let dir = parsedData.dir.replace(saveDir + '/', '') || dir;
            dir = dir.replace(saveDir, '') || '';

            filename = path.join(dir, parsedData.name) + parsedData.ext;
        } else {
            filename = parsedData.name;
        }

        if (parsedData.base !== 'index.ts') {
            exportData += `export * from './${filename}';\n`;
        }
    })

    let fullData = `//@ Auto-Generated indexing files for avg.engine\n\n${exportData}`;
    fs.writeFileSync(path.join(saveDir, 'index.ts'), fullData);
}<commit_msg>copy readme when publish<commit_after>const gulp = require('gulp');
const globby = require('globby');
const path = require('path');
const fs = require('fs');
const index = require('create-index');
const shelljs = require('shelljs');

gulp.task('compile', () => {
    shelljs.exec('yarn run build');
});

gulp.task('create-index', () => {
    console.log('Creating indexing files ...');

    globby(['engine/**/', '!engine/'], {}).then((matches) => {
        matches.map((dir) => {
            globby([dir + '*.ts'], {}).then((files) => {
                generateExports(files, dir, false);
            });
        })
    });

    globby(['engine/**/', '!engine/'], {}).then((matches) => {
        generateExports(matches, 'engine', true);
    });

});

gulp.task('publish', ['create-index', 'compile'], () => {

    console.log(`Patching new version ...`);
    shelljs.exec('npm version patch --force');

    console.log(`Writing publish package.json ...`);
    const package = fs.readFileSync('./package.json');
    const packageConfig = JSON.parse(package);

    const distPackageConfig = {};

    distPackageConfig.name = packageConfig.name;
    distPackageConfig.version = packageConfig.version;
    distPackageConfig.author = packageConfig.author;
    distPackageConfig.license = packageConfig.license;
    distPackageConfig.repository = packageConfig.repository;
    distPackageConfig.dependencies = packageConfig.dependencies;
    distPackageConfig.main = './engine/index.js';

    fs.writeFileSync('dist/package.json', JSON.stringify(distPackageConfig, null, 2));

    shelljs.exec('cp README.md dist/');
    shelljs.exec('cd dist && npm publish');
});

function generateExports(files, saveDir, isDir = false) {
    let exportData = '';

    files.map((file) => {

        let parsedData = path.parse(file);
        let filename = '';
        if (isDir) {
            let dir = parsedData.dir.replace(saveDir + '/', '') || dir;
            dir = dir.replace(saveDir, '') || '';

            filename = path.join(dir, parsedData.name) + parsedData.ext;
        } else {
            filename = parsedData.name;
        }

        if (parsedData.base !== 'index.ts') {
            exportData += `export * from './${filename}';\n`;
        }
    })

    let fullData = `//@ Auto-Generated indexing files for avg.engine\n\n${exportData}`;
    fs.writeFileSync(path.join(saveDir, 'index.ts'), fullData);
}<|endoftext|>


<commit_before>// server.js

    // set up ========================
    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    // configuration =================

    app.use(express.static(__dirname + '/app'));                 // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                                         // log every request to the console
    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
    app.use(bodyParser.json());                                     // parse application/json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
    app.use(methodOverride());

    // listen (start app with node server.js) ======================================
    app.listen(8020);
    console.log("App listening on port 8020");
<commit_msg>cleaning up<commit_after>// server.js

    // set up ========================
    var express  = require('express');
    var app      = express();                               // create our app w/ express
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    // configuration =================

    app.use(express.static(__dirname + '/app'));                 // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                                         // log every request to the console
    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
    app.use(bodyParser.json());                                     // parse application/json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
    app.use(methodOverride());

    // listen (start app with node server.js) ======================================
    app.listen(8020);
    console.log("App listening on port 8000");
<|endoftext|>


<commit_before>(function () {
    var http = require('http');
    var serverClass = function (sys, api, utils) {
        this.sys = sys;
        this.api = api;
        this.utils = utils;
    };

    serverClass.prototype.runServer = function () {
        var api = this.api;
        var sys = this.sys;
        var utils = this.utils;
        var oops = this.utils.apiError;
        http.createServer(function (request, response) {
            if(request.method == "OPTIONS"){
                var nowdate = new Date();
                response.writeHead(200, {
                    'Date': nowdate.toUTCString(),
                    'Allow': 'GET,POST,OPTIONS',
                    'Content-Length': 0,
                    'Content-Type': 'text/plain',
                });
                response.end('');
                return;
            }

            var fs = require('fs');
            var qs = require('querystring');
            var url = require('url');
            var uriObj = url.parse(request.url);
            var params = qs.parse(uriObj.query);
            params.pathname = uriObj.pathname;

            if (sys.admin[params.admin]
                && params.cmd === 'upload') {

                var form = new sys.multiparty.Form();
                form.parse(request, function(err, fields, files) {
                    // Put it where you will.
                    var adminID = sys.admin[params.admin];

                    var touchDate = parseInt(fields.pageDate,10);
                    var pageDate = null;
                    if (!fields.searchableTitle) {
                        pageDate = parseInt(fields.pageDate,10);
                    }
                    var attachmentTitle = fields.attachmentTitle[0];
                    var docTxt = fs.readFileSync(files.attachmentDocument[0].path);
                    var mimeType = fields.mimeType[0];
                    var filenameExtension = fields.filenameExtension[0];
                    var dateFlag = !fields.searchableTitle;

                    if (dateFlag) {
                        checkUniqueDocument();
                    } else {
                        checkSearchableDocument();
                    }

                    function checkSearchableDocument () {
                        //console.log("checkSearchableDocument()");
                        var sql = 'SELECT documentID '
                            + 'FROM documents '
                            + 'JOIN titles USING(titleID) '
                            + 'WHERE title=? '
                            + 'AND uploadDate IS NULL;';
                        sys.db.get(sql,[attachmentTitle],function(err,row){
                            if (err) {return oops(response,err,'upload(1)')};
                            if (row && row.documentID) {
                                updateDocument(row.documentID);
                            } else {
                                checkTitle(attachmentTitle);
                            }
                        });
                    };

                    function checkUniqueDocument () {
                        //console.log("checkUniqueDocument() with "+pageDate);
                        var sql = 'SELECT documentID '
                            + 'FROM documents '
                            + 'JOIN titles USING(titleID) '
                            + 'WHERE title=? '
                            + 'AND uploadDate=?;';
                        sys.db.get(sql,[attachmentTitle,pageDate],function(err,row){
                            if (err) {return oops(response,err,'upload(2)')};
                            if (row && row.documentID) {
                                updateDocument(row.documentID);
                            } else {
                                checkTitle(attachmentTitle);
                            }
                        });
                    };

                    function updateDocument(documentID) {
                        //console.log("updateDocument();");
                        // Replace existing file with upload (filesystem operation)
                        fs.writeFileSync(sys.document_path + '/' + documentID,docTxt);
                        var sql = 'UPDATE documents SET mimeType=?,filenameExtension=?,touchDate=? WHERE documentID=?;';
                        sys.db.run(sql,[mimeType,filenameExtension,touchDate,documentID],function(err){
                            if (err) {return oops(response,err,'upload(3)')};
                            finishUpload(documentID);
                        });
                    };

                    function checkTitle (attachmentTitle) {
                        //console.log("checkTitle();");
                        var sql = 'SELECT titleID FROM titles WHERE title=?;';
                        sys.db.get(sql,[attachmentTitle],function(err,row){
                            if (err) {return oops(response,err,'upload(4)')};
                            if (row && row.titleID) {
                                addDocument(row.titleID);
                            } else {
                                addTitle(attachmentTitle);
                            }
                        });
                    };

                    function addTitle(attachmentTitle) {
                        //console.log("addTitle();");
                        var sql = 'INSERT INTO titles VALUES (NULL,?);';
                        sys.db.run(sql,[attachmentTitle],function(err){
                            if (err) {return oops(response,err,'upload(5)')};
                            addDocument(this.lastID);
                        });
                    };

                    function addDocument (titleID) {
                        //console.log("addDocument();");
                        // Insert database row and get ID
                        var sql = 'INSERT INTO documents VALUES (NULL,?,?,?,?,?);';
                        sys.db.run(sql,[titleID,mimeType,filenameExtension,touchDate,pageDate],function(err){
                            if (err) {return oops(response,err,'upload(6)')};
                            saveDocument(this.lastID)
                        });
                    };

                    function saveDocument (documentID) {
                        //console.log("saveDocument();");
                        // Add a document under database ID
                        fs.writeFileSync(sys.document_path + '/' + documentID, docTxt);
                        finishUpload(documentID);
                    };

                    function finishUpload(documentID) {
                        //console.log("finishUpload();");
                        // Send back documentID, so browser can update page
                        response.writeHead(200, {'Content-Type': 'application/json'});
                        response.end(JSON.stringify({documentID:documentID,documentTitle:attachmentTitle}));
                    }
                })
            } else {
                serveMe();
            }
            function serveMe() {
                request.on('data', function(data){
                    if(typeof this.POSTDATA === "undefined"){
                        this.POSTDATA = "";
                    }
                    this.POSTDATA += data;
                    if(this.POSTDATA.length > 1e6) {
                        this.POSTDATA = "";
                        response.writeHead(413, {'Content-Type': 'text/plain'}).end();
                        request.connection.destroy();
                    }
                });
                request.on('end', function(){
                    //console.log("this.url="+this.url);

                    if (this.POSTDATA) {
                        var payload;
                        if (!request.headers['content-type'].match(/multipart\/form-data/)) {
                            payload = JSON.parse(this.POSTDATA);
                            for (var key in payload) {
                                params[key] = payload[key];
                            }
                        }
                    }

                    if (uriObj.href.match(/\/attachments\/[0-9]+$/)) {
                        var m = uriObj.href.match(/attachments\/([0-9]+)$/);
                        var documentID = m[1];
                        var docTxt = fs.readFileSync('./attachments/' + documentID);
                        // XXX Response is governed by a database lookup
                        var sql = 'SELECT title,filenameExtension,mimeType FROM documents JOIN titles USING(titleID) WHERE documentID=?;';
                        sys.db.get(sql,[documentID],function(err,row){
                            if (err) {return oops(response,err,'download(1)')};
                            if (row && row.title) {
                                // Get mime type, title and file extension from the DB
                                var filenameExtension = row.filenameExtension;
                                if (filenameExtension && filenameExtension.slice(0,1) !== '.') {
                                    filenameExtension = '.' + filenameExtension;
                                }
                                response.writeHead(200, {'Content-Type': row.mimeType,
                                                         "Content-Disposition": "attachment; filename='" + row.title + filenameExtension + "'"
                                                        });
                                response.end(docTxt);
                            } else {
                                response.writeHead(404, {'Content-Type': 'text/plain'});
                                response.end('File not found in database');
                            }
                        });
                        return;
                    } else if ('.js' === uriObj.href.slice(-3)) {
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(js|node_modules)\/(.*)/, '$1/$2'));
                        response.writeHead(200, {'Content-Type': 'text/javascript'});
                        response.end(myxml);
                        return;
                    } else if ('.css' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(css\/.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'text/css'});
                        response.end(myxml);
                        return;
                    } else if ('.png' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'image/png'});
                        response.end(myxml);
                        return;
                    } else if ('.ico' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*\/(.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'image/x-icon'});
                        response.end(myxml);
                        return;
                    } else {
                        api(params,request,response);
                    }
                });
            }
        }).listen(this.sys.real_port);
    }
    exports.serverClass = serverClass;
})();
<commit_msg>Do a better job with download filenames. I think.<commit_after>(function () {
    var http = require('http');
    var serverClass = function (sys, api, utils) {
        this.sys = sys;
        this.api = api;
        this.utils = utils;
    };

    serverClass.prototype.runServer = function () {
        var api = this.api;
        var sys = this.sys;
        var utils = this.utils;
        var oops = this.utils.apiError;
        http.createServer(function (request, response) {
            if(request.method == "OPTIONS"){
                var nowdate = new Date();
                response.writeHead(200, {
                    'Date': nowdate.toUTCString(),
                    'Allow': 'GET,POST,OPTIONS',
                    'Content-Length': 0,
                    'Content-Type': 'text/plain',
                });
                response.end('');
                return;
            }

            var fs = require('fs');
            var qs = require('querystring');
            var url = require('url');
            var uriObj = url.parse(request.url);
            var params = qs.parse(uriObj.query);
            params.pathname = uriObj.pathname;

            if (sys.admin[params.admin]
                && params.cmd === 'upload') {

                var form = new sys.multiparty.Form();
                form.parse(request, function(err, fields, files) {
                    // Put it where you will.
                    var adminID = sys.admin[params.admin];

                    var touchDate = parseInt(fields.pageDate,10);
                    var pageDate = null;
                    if (!fields.searchableTitle) {
                        pageDate = parseInt(fields.pageDate,10);
                    }
                    var attachmentTitle = fields.attachmentTitle[0];
                    var docTxt = fs.readFileSync(files.attachmentDocument[0].path);
                    var mimeType = fields.mimeType[0];
                    var filenameExtension = fields.filenameExtension[0];
                    var dateFlag = !fields.searchableTitle;

                    if (dateFlag) {
                        checkUniqueDocument();
                    } else {
                        checkSearchableDocument();
                    }

                    function checkSearchableDocument () {
                        //console.log("checkSearchableDocument()");
                        var sql = 'SELECT documentID '
                            + 'FROM documents '
                            + 'JOIN titles USING(titleID) '
                            + 'WHERE title=? '
                            + 'AND uploadDate IS NULL;';
                        sys.db.get(sql,[attachmentTitle],function(err,row){
                            if (err) {return oops(response,err,'upload(1)')};
                            if (row && row.documentID) {
                                updateDocument(row.documentID);
                            } else {
                                checkTitle(attachmentTitle);
                            }
                        });
                    };

                    function checkUniqueDocument () {
                        //console.log("checkUniqueDocument() with "+pageDate);
                        var sql = 'SELECT documentID '
                            + 'FROM documents '
                            + 'JOIN titles USING(titleID) '
                            + 'WHERE title=? '
                            + 'AND uploadDate=?;';
                        sys.db.get(sql,[attachmentTitle,pageDate],function(err,row){
                            if (err) {return oops(response,err,'upload(2)')};
                            if (row && row.documentID) {
                                updateDocument(row.documentID);
                            } else {
                                checkTitle(attachmentTitle);
                            }
                        });
                    };

                    function updateDocument(documentID) {
                        //console.log("updateDocument();");
                        // Replace existing file with upload (filesystem operation)
                        fs.writeFileSync(sys.document_path + '/' + documentID,docTxt);
                        var sql = 'UPDATE documents SET mimeType=?,filenameExtension=?,touchDate=? WHERE documentID=?;';
                        sys.db.run(sql,[mimeType,filenameExtension,touchDate,documentID],function(err){
                            if (err) {return oops(response,err,'upload(3)')};
                            finishUpload(documentID);
                        });
                    };

                    function checkTitle (attachmentTitle) {
                        //console.log("checkTitle();");
                        var sql = 'SELECT titleID FROM titles WHERE title=?;';
                        sys.db.get(sql,[attachmentTitle],function(err,row){
                            if (err) {return oops(response,err,'upload(4)')};
                            if (row && row.titleID) {
                                addDocument(row.titleID);
                            } else {
                                addTitle(attachmentTitle);
                            }
                        });
                    };

                    function addTitle(attachmentTitle) {
                        //console.log("addTitle();");
                        var sql = 'INSERT INTO titles VALUES (NULL,?);';
                        sys.db.run(sql,[attachmentTitle],function(err){
                            if (err) {return oops(response,err,'upload(5)')};
                            addDocument(this.lastID);
                        });
                    };

                    function addDocument (titleID) {
                        //console.log("addDocument();");
                        // Insert database row and get ID
                        var sql = 'INSERT INTO documents VALUES (NULL,?,?,?,?,?);';
                        sys.db.run(sql,[titleID,mimeType,filenameExtension,touchDate,pageDate],function(err){
                            if (err) {return oops(response,err,'upload(6)')};
                            saveDocument(this.lastID)
                        });
                    };

                    function saveDocument (documentID) {
                        //console.log("saveDocument();");
                        // Add a document under database ID
                        fs.writeFileSync(sys.document_path + '/' + documentID, docTxt);
                        finishUpload(documentID);
                    };

                    function finishUpload(documentID) {
                        //console.log("finishUpload();");
                        // Send back documentID, so browser can update page
                        response.writeHead(200, {'Content-Type': 'application/json'});
                        response.end(JSON.stringify({documentID:documentID,documentTitle:attachmentTitle}));
                    }
                })
            } else {
                serveMe();
            }
            function serveMe() {
                request.on('data', function(data){
                    if(typeof this.POSTDATA === "undefined"){
                        this.POSTDATA = "";
                    }
                    this.POSTDATA += data;
                    if(this.POSTDATA.length > 1e6) {
                        this.POSTDATA = "";
                        response.writeHead(413, {'Content-Type': 'text/plain'}).end();
                        request.connection.destroy();
                    }
                });
                request.on('end', function(){
                    //console.log("this.url="+this.url);

                    if (this.POSTDATA) {
                        var payload;
                        if (!request.headers['content-type'].match(/multipart\/form-data/)) {
                            payload = JSON.parse(this.POSTDATA);
                            for (var key in payload) {
                                params[key] = payload[key];
                            }
                        }
                    }

                    if (uriObj.href.match(/\/attachments\/[0-9]+$/)) {
                        var m = uriObj.href.match(/attachments\/([0-9]+)$/);
                        var documentID = m[1];
                        var docTxt = fs.readFileSync('./attachments/' + documentID);
                        // XXX Response is governed by a database lookup
                        var sql = 'SELECT title,filenameExtension,mimeType FROM documents JOIN titles USING(titleID) WHERE documentID=?;';
                        sys.db.get(sql,[documentID],function(err,row){
                            if (err) {return oops(response,err,'download(1)')};
                            if (row && row.title) {
                                // Get mime type, title and file extension from the DB
                                var filenameExtension = row.filenameExtension;
                                if (filenameExtension && filenameExtension.slice(0,1) !== '.') {
                                    filenameExtension = '.' + filenameExtension;
                                }
                                response.writeHead(200, {'Content-Type': row.mimeType,
                                                         "Content-Disposition": "attachment; filename=" + encodeURIComponent(row.title + filenameExtension)
                                                        });
                                response.end(docTxt);
                            } else {
                                response.writeHead(404, {'Content-Type': 'text/plain'});
                                response.end('File not found in database');
                            }
                        });
                        return;
                    } else if ('.js' === uriObj.href.slice(-3)) {
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(js|node_modules)\/(.*)/, '$1/$2'));
                        response.writeHead(200, {'Content-Type': 'text/javascript'});
                        response.end(myxml);
                        return;
                    } else if ('.css' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(css\/.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'text/css'});
                        response.end(myxml);
                        return;
                    } else if ('.png' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'image/png'});
                        response.end(myxml);
                        return;
                    } else if ('.ico' === uriObj.href.slice(-4)) {
                        //console.log(__dirname + '/' + uriObj.href.replace(/^.*?\/(css\/images\/.*)/, '$1'));
                        var myxml = fs.readFileSync(__dirname + '/../' + uriObj.href.replace(/^.*\/(.*)/, '$1'));
                        response.writeHead(200, {'Content-Type': 'image/x-icon'});
                        response.end(myxml);
                        return;
                    } else {
                        api(params,request,response);
                    }
                });
            }
        }).listen(this.sys.real_port);
    }
    exports.serverClass = serverClass;
})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var notify = require('gulp-notify');
//var codecept = require('gulp-codeception');
var phpspec = require('gulp-phpspec');
var phpunit = require('gulp-phpunit');

gulp.task('phpunit', function() {
	gulp.src('./tests/phpunit/Grandadevans/GenerateForm/Command/FormGenerateCommandTest.php')
		.pipe(phpunit('./vendor/bin/phpunit', {
				"clear": true,
				"configurationFile": "./phpunit.xml"

			}))
});

gulp.task('phpspec', function() {
	var options = {
		notify: true,
		clear: true,
		noInteraction: true,
		formatter: "pretty"
	};
	gulp.src(['tests/spec/**/*Spec.php','src/**/*'])
		.pipe(phpspec('./vendor/bin/phpspec run', options))
		.on('error', notify.onError({
			title: "Testing Failed",
			message: "Error(s) occurred during test..."
		}))
		.pipe(notify({
			title: "Testing Passed",
			message: "All tests have passed..."
		}));
});

// set watch task to look for changes in test files
gulp.task('watch-phpspec', function () {
	gulp.watch(['tests/spec/**/*Spec.php','src/**/*'], ['phpspec']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['phpspec', 'watch-phpspec']);
<commit_msg>Updated the gulp file to make sure that phpspec and phpunit tests are now run automatically<commit_after>var gulp = require('gulp');
var notify = require('gulp-notify');
//var codecept = require('gulp-codeception');
var phpspec = require('gulp-phpspec');
var phpunit = require('gulp-phpunit');

gulp.task('phpunit', function() {
	var options = {
		notify: true,
		clear: true,
		noInteraction: true,
		formatter: "pretty",
		"configurationFile": "./phpunit.xml"
	};
	gulp.src([
		'src/Grandadevans/GenerateForm/Command/FormGeneratorCommand.php',
		'tests/phpunit/Grandadevans/GenerateForm/Command/FormGenerateCommandTest.php'
		])
		.pipe(phpunit('phpunit', options))
		.on('error', notify.onError({
			title: "Testing Failed",
			message: "Error(s) occurred during test..."
		}))
		.pipe(notify({
			title: "Testing Passed",
			message: "All tests have passed..."
		})
	);
});

gulp.task('phpspec', function() {
	var options = {
		notify: true,
		clear: true,
		noInteraction: true,
		formatter: "pretty"
	};
	gulp.src(['tests/spec/**/*Spec.php','src/**/*'])
		.pipe(phpspec('./vendor/bin/phpspec run', options))
		.on('error', notify.onError({
			title: "Testing Failed",
			message: "Error(s) occurred during test..."
		}))
		.pipe(notify({
			title: "Testing Passed",
			message: "All tests have passed..."
		}));
});

// set watch task to look for changes in test files
gulp.task('watch-phpunit', function () {
	gulp.watch([
		'src/Grandadevans/GenerateForm/Command/FormGeneratorCommand.php',
		'tests/phpunit/Grandadevans/GenerateForm/Command/FormGenerateCommandTest.php'
	], ['phpunit']);
});

// set watch task to look for changes in test files
gulp.task('watch-phpspec', function () {
	gulp.watch([
		'src/**/*',
		'tests/spec/**/*'
	], ['phpspec']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['notify-watching', 'watch-phpspec', 'watch-phpspec']);

gulp.task('notify-watching', function() {
	gulp.src('./')
		.pipe(notify({
			title: 'Automatic testing ACTIVE',
			message: 'Automatic testing for PHPUnit/PHPSpec files is ACTIVE.'
		}));
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

!function (express) {
    'use strict';

    require('./publish')({ clean: true }, function () {
        var app = express(),
            port = process.env.port || process.argv[2] || 1337;

        app.use(express.static('publish'));
        app.listen(port, function () {
            console.log('Cottontail server listening to port ' + port);
        });
    });
}(require('express'));<commit_msg>Remove publish when starting server<commit_after>#!/usr/bin/env node

!function (express) {
    'use strict';

    var app = express(),
        port = process.env.port || process.argv[2] || 1337;

    app.use(express.static('publish'));
    app.listen(port, function () {
        console.log('Cottontail server listening to port ' + port);
    });
}(require('express'));<|endoftext|>