<commit_before>const gulp = require(`gulp`);
const tslint = require(`tslint`);
const gtslint = require(`gulp-tslint`);
const ts = require(`gulp-typescript`);
const mocha = require(`gulp-mocha`);
const sourcemaps = require(`gulp-sourcemaps`);
const plumber = require(`gulp-plumber`);
const transform = require(`gulp-transform`);
const typedoc = require(`gulp-typedoc`);
const rimraf = require(`rimraf`);
const merge = require(`merge2`);
const argv = require(`yargs`).argv;
const {preprocess} = require(`tiny-preprocessor`);

const path = typeof argv.pkg === `string` ? `./packages/${argv.pkg}` : `.`;
const tsproj = {
  commonjs: ts.createProject(`./tsconfig.json`, {declaration: true}),
  module: ts.createProject(`./tsconfig.json`, {declaration: true, module: `es2015`}),
  tests: ts.createProject(`./tsconfig.json`, {rootDir: `${path}/`, noUnusedLocals: false})
};

function preprocessBuffer(buffer) {
  return preprocess(buffer.toString());
}

function replace(a, b) {
  return function(buffer) {
    const src = buffer.toString();
    return src.replace(a, b);
  }
}

function compile() {
  const src = gulp.src(`${path}/.build/ts/**/*.ts`)
    .pipe(plumber())
    .pipe(sourcemaps.init());
  const ts_commonjs = src.pipe(tsproj.commonjs());
  const ts_module = src.pipe(tsproj.module());
  return merge([
    ts_commonjs.js
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/lib/commonjs`)),

    ts_module.js
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/lib/module`)),

    ts_module.dts
      .pipe(gulp.dest(`${path}/lib/typings`)),

    gulp.src(`${path}/.build/tests.ts/**/*.ts`)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(tsproj.tests()).js
      .pipe(transform(replace(/\.\.\/ts/g, `../../lib/commonjs`)))
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/.build/tests`))
  ]);
}

function preprocess() {
  return merge([
    gulp.src(`${path}/src/**/*.ts`)
      .pipe(plumber())
      .pipe(transform(preprocessBuffer))
      .pipe(gulp.dest(`${path}/.build/ts`)),

    gulp.src(`${path}/tests/**/*.ts`)
      .pipe(plumber())
      .pipe(transform(preprocessBuffer))
      .pipe(transform(replace(/\.\.\/src/g, `../ts`)))
      .pipe(gulp.dest(`${path}/.build/tests.ts`)),
  ]);
}

function lint() {
  return gulp.src(`${path}/.build/ts/**/*.ts`)
    .pipe(plumber())
    .pipe(gtslint({formatter: "verbose"}))
    .pipe(gtslint.report());
}

function runTests() {
  require(`source-map-support`).install();
  return gulp
    .src([`${path}/.build/tests/**/*.js`], {read: false})
    .pipe(plumber())
    .pipe(mocha({timeout: 10000, ui: `tdd`}));
}

function clean() {
  const paths = [`${path}/lib`, `${path}/.build`];
  return function(cb) {
    const next = (i = 0) => rimraf(paths[i], done(i + 1));
    const done = i => err => err ? cb(err) : i === paths.length ? cb() : next(i);
    return next();
  }
}

gulp.task(`clean`, clean());
gulp.task(`preprocess`, preprocess);
gulp.task(`compile`, [`preprocess`], compile);
gulp.task(`watch`, () => gulp.watch([`${path}/src/**/*.ts`, `${path}/tests/**/*.ts`], [`build`]));
gulp.task(`test`, [`compile`, `lint`], runTests);
gulp.task(`lint`, [`preprocess`, `compile`], lint);
gulp.task(`build`, [`preprocess`, `compile`, `test`, `lint`]);
gulp.task(`dev`, [`build`, `watch`]);
gulp.task(`default`, [`build`]);<commit_msg>Fixed duplicate declaration in gulpfile<commit_after>const gulp = require(`gulp`);
const tslint = require(`tslint`);
const gtslint = require(`gulp-tslint`);
const ts = require(`gulp-typescript`);
const mocha = require(`gulp-mocha`);
const sourcemaps = require(`gulp-sourcemaps`);
const plumber = require(`gulp-plumber`);
const transform = require(`gulp-transform`);
const typedoc = require(`gulp-typedoc`);
const rimraf = require(`rimraf`);
const merge = require(`merge2`);
const argv = require(`yargs`).argv;
const {preprocess} = require(`tiny-preprocessor`);

const path = typeof argv.pkg === `string` ? `./packages/${argv.pkg}` : `.`;
const tsproj = {
  commonjs: ts.createProject(`./tsconfig.json`, {declaration: true}),
  module: ts.createProject(`./tsconfig.json`, {declaration: true, module: `es2015`}),
  tests: ts.createProject(`./tsconfig.json`, {rootDir: `${path}/`, noUnusedLocals: false})
};

function preprocessBuffer(buffer) {
  return preprocess(buffer.toString());
}

function replace(a, b) {
  return function(buffer) {
    const src = buffer.toString();
    return src.replace(a, b);
  }
}

function compile() {
  const src = gulp.src(`${path}/.build/ts/**/*.ts`)
    .pipe(plumber())
    .pipe(sourcemaps.init());
  const ts_commonjs = src.pipe(tsproj.commonjs());
  const ts_module = src.pipe(tsproj.module());
  return merge([
    ts_commonjs.js
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/lib/commonjs`)),

    ts_module.js
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/lib/module`)),

    ts_module.dts
      .pipe(gulp.dest(`${path}/lib/typings`)),

    gulp.src(`${path}/.build/tests.ts/**/*.ts`)
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(tsproj.tests()).js
      .pipe(transform(replace(/\.\.\/ts/g, `../../lib/commonjs`)))
      .pipe(sourcemaps.write(`./`))
      .pipe(gulp.dest(`${path}/.build/tests`))
  ]);
}

function runPreprocessor() {
  return merge([
    gulp.src(`${path}/src/**/*.ts`)
      .pipe(plumber())
      .pipe(transform(preprocessBuffer))
      .pipe(gulp.dest(`${path}/.build/ts`)),

    gulp.src(`${path}/tests/**/*.ts`)
      .pipe(plumber())
      .pipe(transform(preprocessBuffer))
      .pipe(transform(replace(/\.\.\/src/g, `../ts`)))
      .pipe(gulp.dest(`${path}/.build/tests.ts`)),
  ]);
}

function lint() {
  return gulp.src(`${path}/.build/ts/**/*.ts`)
    .pipe(plumber())
    .pipe(gtslint({formatter: "verbose"}))
    .pipe(gtslint.report());
}

function runTests() {
  require(`source-map-support`).install();
  return gulp
    .src([`${path}/.build/tests/**/*.js`], {read: false})
    .pipe(plumber())
    .pipe(mocha({timeout: 10000, ui: `tdd`}));
}

function clean() {
  const paths = [`${path}/lib`, `${path}/.build`];
  return function(cb) {
    const next = (i = 0) => rimraf(paths[i], done(i + 1));
    const done = i => err => err ? cb(err) : i === paths.length ? cb() : next(i);
    return next();
  }
}

gulp.task(`clean`, clean());
gulp.task(`preprocess`, runPreprocessor);
gulp.task(`compile`, [`preprocess`], compile);
gulp.task(`watch`, () => gulp.watch([`${path}/src/**/*.ts`, `${path}/tests/**/*.ts`], [`build`]));
gulp.task(`test`, [`compile`, `lint`], runTests);
gulp.task(`lint`, [`preprocess`, `compile`], lint);
gulp.task(`build`, [`preprocess`, `compile`, `test`, `lint`]);
gulp.task(`dev`, [`build`, `watch`]);
gulp.task(`default`, [`build`]);<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    mocha = require('gulp-mocha'),
    istanbul = require('gulp-istanbul'),
    exit = require('gulp-exit');

var TESTS = './test/*.js';
var SRC = './lib/**/*.js';
var MOCHA_OPTS = {
  timeout: 20000
};

gulp.task('clean', function() {
  var del = require('del');
  return del(['./coverage/']);
});

gulp.task('lint', function() {
  var eslint = require('gulp-eslint');

  var t = gulp.src([
    SRC,
    TESTS,
    'gulpfile.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
  return t;
});

gulp.task('test', ['lint'], function() {
  return gulp.src([TESTS])
    .pipe(mocha(MOCHA_OPTS))
    .pipe(exit());
});

gulp.task('doc', function() {
  var documentation = require('gulp-documentation');
  return gulp.src([SRC])
    .pipe(documentation({
      format: 'html',
      github: true
    }))
    .pipe(gulp.dest('doc'));
});

gulp.task('doc-deploy', ['doc'], function() {
  var ghPages = require('gulp-gh-pages');
  return gulp.src('./doc/**/*')
    .pipe(ghPages());
});

gulp.task('pre-coverage', ['clean'], function() {
  return gulp.src([SRC])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('coverage', ['pre-coverage'], function() {
  var t = gulp.src([TESTS])
  .pipe(mocha(MOCHA_OPTS).on('error', function(er) {
    gutil.log(er);
    t.end();
  }))
  .pipe(istanbul.writeReports({
    dir: './coverage'
  }));
  // XXX: This line needs to be commented out for `gulp serve` to work, but
  // needs to be enabled for Travis tests to pass (since gulp fails to exit
  // after the tests otherwise).
  //.pipe(exit());
  return t;
});

gulp.task('ci', ['coverage'], function() {
  var coveralls = require('gulp-coveralls');
  gulp.src('./coverage/**/lcov.info')
  .pipe(coveralls());
});

gulp.task('watch', ['coverage'], function() {
  return gulp.watch([SRC, TESTS], ['coverage']);
});

gulp.task('serve', ['watch'], function() {
  var gls = require('gulp-live-server');
  var open = require('open');
  var server = gls['static']('coverage/lcov-report');
  server.start();
  open('http://localhost:3000/');
  return gulp.watch(['coverage/lcov-report/**/*.html'], function(file) {
    return server.notify.apply(server, [file]);
  });
});

gulp.task('default', ['coverage']);
<commit_msg>Revert gulpfile<commit_after>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    mocha = require('gulp-mocha'),
    istanbul = require('gulp-istanbul'),
    exit = require('gulp-exit');

var TESTS = './test/*.js';
var SRC = './lib/**/*.js';
var MOCHA_OPTS = {
  timeout: 20000
};

gulp.task('clean', function() {
  var del = require('del');
  return del(['./coverage/']);
});

gulp.task('lint', function() {
  var eslint = require('gulp-eslint');

  var t = gulp.src([
    SRC,
    TESTS,
    'gulpfile.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
  return t;
});

gulp.task('test', ['lint'], function() {
  return gulp.src([TESTS])
    .pipe(mocha(MOCHA_OPTS))
    .pipe(exit());
});

gulp.task('doc', function() {
  var documentation = require('gulp-documentation');
  return gulp.src([SRC])
    .pipe(documentation({
      format: 'html',
      github: true
    }))
    .pipe(gulp.dest('doc'));
});

gulp.task('doc-deploy', ['doc'], function() {
  var ghPages = require('gulp-gh-pages');
  return gulp.src('./doc/**/*')
    .pipe(ghPages());
});

gulp.task('pre-coverage', ['clean'], function() {
  return gulp.src([SRC])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('coverage', ['pre-coverage'], function() {
  var t = gulp.src([TESTS])
  .pipe(mocha(MOCHA_OPTS).on('error', function(er) {
    gutil.log(er);
    t.end();
  }))
  .pipe(istanbul.writeReports({
    dir: './coverage'
  }))
  // XXX: This line needs to be commented out for `gulp serve` to work, but
  // needs to be enabled for Travis tests to pass (since gulp fails to exit
  // after the tests otherwise).
  .pipe(exit());
  return t;
});

gulp.task('ci', ['coverage'], function() {
  var coveralls = require('gulp-coveralls');
  gulp.src('./coverage/**/lcov.info')
  .pipe(coveralls());
});

gulp.task('watch', ['coverage'], function() {
  return gulp.watch([SRC, TESTS], ['coverage']);
});

gulp.task('serve', ['watch'], function() {
  var gls = require('gulp-live-server');
  var open = require('open');
  var server = gls['static']('coverage/lcov-report');
  server.start();
  open('http://localhost:3000/');
  return gulp.watch(['coverage/lcov-report/**/*.html'], function(file) {
    return server.notify.apply(server, [file]);
  });
});

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


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

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

elixir.config.js.browserify.options.debug=true;

elixir(function(mix) {
    /* PixboPlayer */
    mix
        .sass('PixboPlayer.scss')
        .scripts(
            [
                'jquery-2.1.3.min.js',
                'vegas.min.js',
                'jquery.ticker.js',
                '../PixboPlayer.js'
            ],
            'public/js/PixboPlayer.js',
            'resources/assets/js/vendor'
        );

    /* Fonts */
    mix
        .copy( 'resources/assets/fonts', 'public/fonts' )

    /* Admin GUI */
    mix
        .sass('app.scss')
        .scripts(
            [
                'jquery-2.1.4.min.js',
                '../../../../node_modules/moment/min/moment-with-locales.min.js',
                '../../../../node_modules/bootstrap-select/dist/js/bootstrap-select.js',
                'bootstrap-datetimepicker.min.js',
                'dropzone.js'
            ],
            'public/js/vendor.js',
            'resources/assets/js/vendor'

        )
        .browserify('index.js');
});<commit_msg>Updated gulpfile due to PixboPlayer.js<commit_after>var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');

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

elixir.config.js.browserify.options.debug=true;

elixir(function(mix) {
    /* PixboPlayer */
    mix
        .sass('PixboPlayer.scss')
        .scripts(
            [
                'jquery-2.1.3.min.js',
                'vegas.min.js',
                'jquery.ticker.js',
                '../PixboPlayer/*.js',
                '../PixboPlayer/*/*.js'
            ],
            'public/js/PixboPlayer.js',
            'resources/assets/js/vendor'
        );

    /* Fonts */
    mix
        .copy( 'resources/assets/fonts', 'public/fonts' )

    /* Admin GUI */
    mix
        .sass('app.scss')
        .scripts(
            [
                'jquery-2.1.4.min.js',
                '../../../../node_modules/moment/min/moment-with-locales.min.js',
                '../../../../node_modules/bootstrap-select/dist/js/bootstrap-select.js',
                'bootstrap-datetimepicker.min.js',
                'dropzone.js'
            ],
            'public/js/vendor.js',
            'resources/assets/js/vendor'

        )
        .browserify('index.js');
});<|endoftext|>


<commit_before>const gulp = require('gulp')
const fs = require('fs')
const path = require('path')
const uglify = require('gulp-uglify')
const concat = require('gulp-concat-util')
const del = require('del')
const less = require('gulp-less')
const preprocess = require('gulp-preprocess')

const pushPlayerToGrid = require('./tools/pushPlayerToGrid')

var paths = {
	less: './less/build.less',
	less360: './less/build_threesixty.less',
	js: {
		plugins: './browser/plugins/*.plugin.js',
		engine: [
			'./browser/vendor/when.js',

			'./browser/scripts/event-emitter.js',
			'./browser/scripts/core.js',
			'./browser/scripts/util.js',

			'./browser/scripts/connection.js',
			'./browser/scripts/variables.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/autoSlotGroup.js',

			'./browser/scripts/plugin.js',
			'./browser/scripts/subGraphPlugin.js',
			'./browser/scripts/threeObject3dPlugin.js',
			'./browser/scripts/abstractObjectGazePlugin.js',
			'./browser/scripts/abstractThreeLoaderObjPlugin.js',
			'./browser/scripts/abstractThreeMaterialPlugin.js',
			'./browser/scripts/abstractThreeMeshPlugin.js',
			'./browser/scripts/abstractArrayBlendModulatorPlugin.js',
			'./browser/scripts/abstractAnimateValueOnTriggerPlugin.js',

			'./browser/scripts/blendFunctions.js',

			'./browser/scripts/worldEditor/worldEditor.js',
			'./browser/scripts/worldEditor/worldEditorPerspectiveCamera.js',
			'./browser/scripts/worldEditor/worldEditorOrthographicCamera.js',
			'./browser/scripts/worldEditor/worldEditorCameraSelector.js',
			'./browser/scripts/worldEditor/worldEditorOriginGrid.js',
			'./browser/scripts/worldEditor/worldEditorRadialHelper.js',

			'./browser/scripts/screenshot/ScreenshotRenderer.js',

			'./browser/scripts/loaders/loader.js',
			'./browser/scripts/loaders/imageLoader.js',
			'./browser/scripts/loaders/textureLoader.js',
			'./browser/scripts/loaders/modelLoader.js',
			'./browser/scripts/loaders/sceneLoader.js',
			'./browser/scripts/loaders/assetLoader.js',
			'./browser/scripts/loaders/audioBufferLoader.js',
			'./browser/scripts/loaders/multiObjectLoader.js',

			'./browser/scripts/documentation/pluginDocsCache.js',

			'./browser/vendor/three/three.js',
			'./browser/vendor/three/OBJLoader.js',
			'./browser/vendor/three/OBJMTLLoader.js',
			'./browser/vendor/three/MTLLoader.js',
			'./browser/vendor/three/DDSLoader.js',
			'./browser/vendor/three/VREffect.js',
			'./browser/vendor/three/CardboardEffect.js',
			'./browser/vendor/three/VRControls.js',
			'./browser/vendor/three/OrbitControls.js',
			'./browser/vendor/three/SceneLoader.js',
			'./browser/vendor/three/MorphAnimMesh.js',
			'./browser/vendor/three/FontUtils.js',
			'./browser/vendor/three/fonts/helvetiker_bold.typeface.js',
			'./browser/vendor/three/fonts/helvetiker_regular.typeface.js',

			'./browser/vendor/spite/THREE.MeshLine.js',

			'./browser/vendor/borismus/webvr-polyfill.js',
			'./browser/vendor/borismus/webvr-manager.js',

			'./browser/scripts/noise.js',
			'./browser/vendor/random.min.js',

			'./browser/scripts/datatypes/environmentSettings.js',

			'./browser/scripts/textureCache.js',

			'./browser/scripts/plugin-manager-bundled.js'
		],

		player: [
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
}

function errorHandler(err) {
	console.error(err.message, err.lineNumber, err.stack)
	this.emit('end')
}

gulp.task('clean:js:player', function(cb) {
	del('./browser/dist/player.min.js', cb)
})

gulp.task('clean:js:engine', function(cb) {
	del('./browser/dist/engine.js', cb)
})

gulp.task('clean:less360', function(cb)
{
	del('./browser/style/threesixty.css', cb);
});

gulp.task('clean:less', function(cb) {
	del('./browser/style/less.css', cb)
})

gulp.task('clean:js', ['clean:js:player', 'clean:js:engine'])

gulp.task('clean', ['clean:js'])

gulp.task('js:engine', ['clean:js:engine'], function(done) {
	gulp.src(paths.js.engine)
	.pipe(concat.header(';\n'))
	.pipe(concat('engine.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('js:player', ['clean:js:player', 'js:engine'], function(done) {
	var playerPipe = gulp.src(paths.js.engine.concat(paths.js.player))
		.pipe(concat.header(';\n'))
		.pipe(concat('player.min.js'))

	// only uglify in production
	if (process.env.NODE_ENV === 'production') {
		playerPipe = playerPipe
			.pipe(uglify().on('error', errorHandler))
	}

	playerPipe
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('push', ['js:player'], function(done) {
	pushPlayerToGrid()
		.then(done, errorHandler)
})

gulp.task('js', ['js:player'])

gulp.task('less', ['clean:less'], function() {
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
})

gulp.task('less360', ['clean:less360'], function() {
	gulp.src(paths.less360)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('threesixty.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less', 'less360']);
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('watch:less360', function() {
	gulp.watch('less/threesixty.less', ['less360']);
});

gulp.task('watch:less', function() {
	gulp.watch('less/**/*', ['less'])
})

gulp.task('watch:player', function() {
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('golive', ['less', 'less360', 'js'])

gulp.task('default', ['less', 'less360', 'js', 'push'])

<commit_msg>temporarily remove fontutils from gulpfile while fixing the problem<commit_after>const gulp = require('gulp')
const fs = require('fs')
const path = require('path')
const uglify = require('gulp-uglify')
const concat = require('gulp-concat-util')
const del = require('del')
const less = require('gulp-less')
const preprocess = require('gulp-preprocess')

const pushPlayerToGrid = require('./tools/pushPlayerToGrid')

var paths = {
	less: './less/build.less',
	less360: './less/build_threesixty.less',
	js: {
		plugins: './browser/plugins/*.plugin.js',
		engine: [
			'./browser/vendor/when.js',

			'./browser/scripts/event-emitter.js',
			'./browser/scripts/core.js',
			'./browser/scripts/util.js',

			'./browser/scripts/connection.js',
			'./browser/scripts/variables.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/autoSlotGroup.js',

			'./browser/scripts/plugin.js',
			'./browser/scripts/subGraphPlugin.js',
			'./browser/scripts/threeObject3dPlugin.js',
			'./browser/scripts/abstractObjectGazePlugin.js',
			'./browser/scripts/abstractThreeLoaderObjPlugin.js',
			'./browser/scripts/abstractThreeMaterialPlugin.js',
			'./browser/scripts/abstractThreeMeshPlugin.js',
			'./browser/scripts/abstractArrayBlendModulatorPlugin.js',
			'./browser/scripts/abstractAnimateValueOnTriggerPlugin.js',

			'./browser/scripts/blendFunctions.js',

			'./browser/scripts/worldEditor/worldEditor.js',
			'./browser/scripts/worldEditor/worldEditorPerspectiveCamera.js',
			'./browser/scripts/worldEditor/worldEditorOrthographicCamera.js',
			'./browser/scripts/worldEditor/worldEditorCameraSelector.js',
			'./browser/scripts/worldEditor/worldEditorOriginGrid.js',
			'./browser/scripts/worldEditor/worldEditorRadialHelper.js',

			'./browser/scripts/screenshot/ScreenshotRenderer.js',

			'./browser/scripts/loaders/loader.js',
			'./browser/scripts/loaders/imageLoader.js',
			'./browser/scripts/loaders/textureLoader.js',
			'./browser/scripts/loaders/modelLoader.js',
			'./browser/scripts/loaders/sceneLoader.js',
			'./browser/scripts/loaders/assetLoader.js',
			'./browser/scripts/loaders/audioBufferLoader.js',
			'./browser/scripts/loaders/multiObjectLoader.js',

			'./browser/scripts/documentation/pluginDocsCache.js',

			'./browser/vendor/three/three.js',
			'./browser/vendor/three/OBJLoader.js',
			'./browser/vendor/three/OBJMTLLoader.js',
			'./browser/vendor/three/MTLLoader.js',
			'./browser/vendor/three/DDSLoader.js',
			'./browser/vendor/three/VREffect.js',
			'./browser/vendor/three/CardboardEffect.js',
			'./browser/vendor/three/VRControls.js',
			'./browser/vendor/three/OrbitControls.js',
			'./browser/vendor/three/SceneLoader.js',
			'./browser/vendor/three/MorphAnimMesh.js',
			//'./browser/vendor/three/FontUtils.js',
			//'./browser/vendor/three/fonts/helvetiker_bold.typeface.js',
			//'./browser/vendor/three/fonts/helvetiker_regular.typeface.js',

			'./browser/vendor/spite/THREE.MeshLine.js',

			'./browser/vendor/borismus/webvr-polyfill.js',
			'./browser/vendor/borismus/webvr-manager.js',

			'./browser/scripts/noise.js',
			'./browser/vendor/random.min.js',

			'./browser/scripts/datatypes/environmentSettings.js',

			'./browser/scripts/textureCache.js',

			'./browser/scripts/plugin-manager-bundled.js'
		],

		player: [
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
}

function errorHandler(err) {
	console.error(err.message, err.lineNumber, err.stack)
	this.emit('end')
}

gulp.task('clean:js:player', function(cb) {
	del('./browser/dist/player.min.js', cb)
})

gulp.task('clean:js:engine', function(cb) {
	del('./browser/dist/engine.js', cb)
})

gulp.task('clean:less360', function(cb)
{
	del('./browser/style/threesixty.css', cb);
});

gulp.task('clean:less', function(cb) {
	del('./browser/style/less.css', cb)
})

gulp.task('clean:js', ['clean:js:player', 'clean:js:engine'])

gulp.task('clean', ['clean:js'])

gulp.task('js:engine', ['clean:js:engine'], function(done) {
	gulp.src(paths.js.engine)
	.pipe(concat.header(';\n'))
	.pipe(concat('engine.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('js:player', ['clean:js:player', 'js:engine'], function(done) {
	var playerPipe = gulp.src(paths.js.engine.concat(paths.js.player))
		.pipe(concat.header(';\n'))
		.pipe(concat('player.min.js'))

	// only uglify in production
	if (process.env.NODE_ENV === 'production') {
		playerPipe = playerPipe
			.pipe(uglify().on('error', errorHandler))
	}

	playerPipe
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'dist')))
	.on('error', errorHandler)
	.on('end', done)
})

gulp.task('push', ['js:player'], function(done) {
	pushPlayerToGrid()
		.then(done, errorHandler)
})

gulp.task('js', ['js:player'])

gulp.task('less', ['clean:less'], function() {
	gulp.src(paths.less)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
})

gulp.task('less360', ['clean:less360'], function() {
	gulp.src(paths.less360)
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }).on('error', errorHandler))
	.pipe(concat('threesixty.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')))
	.on('error', errorHandler)
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less', 'less360']);
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('watch:less360', function() {
	gulp.watch('less/threesixty.less', ['less360']);
});

gulp.task('watch:less', function() {
	gulp.watch('less/**/*', ['less'])
})

gulp.task('watch:player', function() {
	gulp.watch(paths.js.player.concat(paths.js.engine), ['js:player', 'push'])
})

gulp.task('golive', ['less', 'less360', 'js'])

gulp.task('default', ['less', 'less360', 'js', 'push'])

<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const path = require('path');
const runSequence = require('run-sequence');

const babel = require('gulp-babel');
const concat = require('gulp-concat');
const foreach = require('gulp-foreach');
const plumber = require('gulp-plumber');
const rollup = require('gulp-rollup');
const sourcemaps = require('gulp-sourcemaps');

const rollupPlugins = {
  babel: require('rollup-plugin-babel'),
  uglify: require('rollup-plugin-uglify'),
};

const JS_PATHS = {
  dest: 'dist',
  entryPoint: path.join('lib', 'rouge.js'),
  srcGlob: path.join('lib', '*.js'),
};

function stripFlowTypes(s) {
  return s.pipe(plumber())
          .pipe(sourcemaps.init())
          .pipe(babel({
            babelrc: false,
            comments: process.env.NODE_ENV === 'production' ? true : false,
            compact: process.env.NODE_ENV === 'production' ? true : false,
            plugins: ['transform-flow-strip-types'],
            sourceMaps: process.env.NODE_ENV === 'production' ? true : false,
          }))
          .pipe(sourcemaps.write('.'))
          .pipe(plumber.stop())
          .pipe(gulp.dest(path.join(JS_PATHS.dest, 'es6')));
}

gulp.task('bundleJS_es5', () => {
  let plugins = [rollupPlugins.babel()];

  if (process.env.NODE_ENV === 'production') plugins.push(rollupPlugins.uglify());

  gulp.src(JS_PATHS.entryPoint, { read: false })
      .pipe(plumber())
      .pipe(rollup({
        format: 'cjs',
        sourceMap: process.env.NODE_ENV === 'production' ? true : false,
        plugins: plugins,
      }))
      .pipe(plumber.stop())
      .pipe(gulp.dest(path.join(JS_PATHS.dest, 'es5')));
});

gulp.task('bundleJS_es6', () => {
  gulp.src(JS_PATHS.srcGlob).pipe(foreach(stripFlowTypes));
});

gulp.task('watch', () => {
  gulp.watch(JS_PATHS.srcGlob, ['bundleJS_es5', 'bundleJS_es6']);
});

gulp.task('default', () => {
  runSequence(['bundleJS_es5', 'bundleJS_es6'], 'watch');
});
<commit_msg>Fix bug in gulpfile causing sourcemaps to not be generated in development builds<commit_after>'use strict';

const gulp = require('gulp');
const path = require('path');
const runSequence = require('run-sequence');

const babel = require('gulp-babel');
const concat = require('gulp-concat');
const foreach = require('gulp-foreach');
const plumber = require('gulp-plumber');
const rollup = require('gulp-rollup');
const sourcemaps = require('gulp-sourcemaps');

const rollupPlugins = {
  babel: require('rollup-plugin-babel'),
  uglify: require('rollup-plugin-uglify'),
};

const JS_PATHS = {
  dest: 'dist',
  entryPoint: path.join('lib', 'rouge.js'),
  srcGlob: path.join('lib', '*.js'),
};

function stripFlowTypes(s) {
  return s.pipe(plumber())
          .pipe(sourcemaps.init())
          .pipe(babel({
            babelrc: false,
            comments: process.env.NODE_ENV === 'development' ? true : false,
            compact: process.env.NODE_ENV === 'development' ? false : true,
            plugins: ['transform-flow-strip-types'],
            sourceMaps: true,
          }))
          .pipe(sourcemaps.write('.'))
          .pipe(plumber.stop())
          .pipe(gulp.dest(path.join(JS_PATHS.dest, 'es6')));
}

gulp.task('bundleJS_es5', () => {
  let plugins = [rollupPlugins.babel()];

  if (process.env.NODE_ENV === 'production') {
    plugins.push(rollupPlugins.uglify());
  }

  gulp.src(JS_PATHS.entryPoint, { read: false })
      .pipe(plumber())
      .pipe(sourcemaps.init())
      .pipe(rollup({
        format: 'cjs',
        sourceMap: true,
        plugins: plugins,
      }))
      .pipe(sourcemaps.write('.'))
      .pipe(plumber.stop())
      .pipe(gulp.dest(path.join(JS_PATHS.dest, 'es5')));
});

gulp.task('bundleJS_es6', () => {
  gulp.src(JS_PATHS.srcGlob).pipe(foreach(stripFlowTypes));
});

gulp.task('watch', () => {
  gulp.watch(JS_PATHS.srcGlob, ['bundleJS_es5', 'bundleJS_es6']);
});

gulp.task('default', () => {
  runSequence(['bundleJS_es5', 'bundleJS_es6'], 'watch');
});
<|endoftext|>


<commit_before>(function () {

    // gulp
    var gulp = require('gulp');
    var plugins = require('gulp-load-plugins')();
    var runSequence = require('run-sequence');
    var del = require('del');
    var addStream = require('add-stream');
    var config = require('./gulpfile.config.js');

    // main tasks
    gulp.task('default', function (callback) {
        runSequence('clean',
                    'lint',
                    ['process-js', 'process-styles', 'move-fonts', 'move-static-content'],
                    'run-server',
                    'watch')
    });

    gulp.task('build', function (callback) {
        runSequence('clean',
                    'lint',
                    ['process-js-dist', 'process-styles-dist', 'move-fonts-dist', 'move-static-content-dist', 'run-server-dist']);
    });

    //component tasks
    gulp.task('watch', watch);
    gulp.task('lint', lint);
    gulp.task('clean', clean);
    gulp.task('run-server', runServer);
    gulp.task('process-styles', processStyles);
    gulp.task('process-styles-dist', processStylesDist);
    gulp.task('process-js', processJs);
    gulp.task('process-js-dist', processJsDist);
    gulp.task('move-fonts', moveFonts);
    gulp.task('move-fonts-dist', moveFontsDist);
    gulp.task('move-static-content', moveStaticContent);
    gulp.task('move-static-content-dist', moveStaticContentDist);
    gulp.task('run-server-dist', runServerDist);

    function processJs() {
        return gulp.src(config.jsFiles)
            .pipe(plugins.ngAnnotate())
            .pipe(addStream.obj(prepareTemplates()))
            .pipe(plugins.concat('app.js'))
            .pipe(gulp.dest('dev/js/'))
            .on('error', plugins.util.log);
    }

    function processJsDist() {
        return gulp.src(config.jsFiles)
            .pipe(plugins.ngAnnotate())
            .pipe(addStream.obj(prepareTemplates()))
            .pipe(plugins.concat('app.js'))
            .pipe(plugins.uglify())
            .pipe(gulp.dest('dist/js/'))
            .on('error', plugins.util.log);
    }

    function prepareTemplates() {
        return gulp.src(['src/app/**/*.html', '!src/app/common/templates/index.html'])
            .pipe(plugins.angularTemplatecache())
            .on('error', plugins.util.log);
    }

    function processStyles() {
        return gulp.src(config.lessFiles)
            .pipe(plugins.less())
            .pipe(plugins.addSrc.prepend(config.cssFiles))
            .pipe(plugins.concat('app.css'))
            .pipe(gulp.dest('dev/css/'))
            .on('error', plugins.util.log);
    }

    function processStylesDist() {
        return gulp.src(config.lessFiles)
            .pipe(plugins.less())
            .pipe(plugins.addSrc.append(config.cssFiles))
            .pipe(plugins.concat('app.css'))
            .pipe(plugins.minifyCss({ keepSpecialComments: 0 }))
            .pipe(gulp.dest('dist/css/'))
            .on('error', plugins.util.log);
    }

    function moveFonts() {
        return gulp.src(config.fontFiles)
            .pipe(gulp.dest('dev/fonts'))
            .on('error', plugins.util.log);
    }

    function moveFontsDist() {
        return gulp.src(config.fontFiles)
            .pipe(gulp.dest('dist/fonts'))
            .on('error', plugins.util.log);
    }

    function moveStaticContent() {
        return gulp.src(['src/assets/**/*', 'src/app/common/templates/index.html'])
            .pipe(gulp.dest('dev/'))
            .on('error', plugins.util.log);
    }

    function moveStaticContentDist() {
        return gulp.src(['src/assets/**/*', 'src/app/common/templates/index.html'])
            .pipe(gulp.dest('dist/'))
            .on('error', plugins.util.log);
    }

    function runServer() {
        return plugins.connect.server({
            root: 'dev/',
            port: 8888,
            livereload: false,
            fallback: 'dev/index.html',
            host: 'localhost'
        });
    }

    function runServerDist() {
        return plugins.connect.server({
            root: 'dist/',
            port: 9999
        });
    }

    function lint() {
        return gulp.src('src/app/**/*.js')
            .pipe(plugins.jshint())
            .pipe(plugins.jshint.reporter('jshint-stylish'))
            .pipe(plugins.jshint.reporter('fail'))
            .on('error', plugins.util.log);
    }

    function clean() {
        process.on('uncaughtException', function (err) {
            console.log(err);
        })

        return del([
            'dist/*',
            'dev/*'
        ]);
    }

    function watch() {
        return gulp
            .watch('src/**/*.*', ['build-dev'])
            .on('error', plugins.util.log);
    }

}());<commit_msg>fixed some bugs with the new gulp process<commit_after>(function () {

    // gulp
    var gulp = require('gulp');
    var plugins = require('gulp-load-plugins')();
    var runSequence = require('run-sequence');
    var del = require('del');
    var addStream = require('add-stream');
    var config = require('./gulpfile.config.js');

    // main tasks
    gulp.task('default', function (callback) {
        runSequence('clean',
                    'lint',
                    ['process-js', 'process-styles', 'move-fonts', 'move-static-content'],
                    'run-server',
                    'watch')
    });

    gulp.task('build', function (callback) {
        runSequence('clean',
                    'lint',
                    ['process-js-dist', 'process-styles-dist', 'move-fonts-dist', 'move-static-content-dist']);
    });

    gulp.task('run', function (callback) {
        runSequence('clean',
                    'lint',
                    ['process-js', 'process-styles', 'move-fonts', 'move-static-content']);
    });

    //component tasks
    gulp.task('watch', watch);
    gulp.task('lint', lint);
    gulp.task('clean', clean);
    gulp.task('run-server', runServer);
    gulp.task('process-styles', processStyles);
    gulp.task('process-styles-dist', processStylesDist);
    gulp.task('process-js', processJs);
    gulp.task('process-js-dist', processJsDist);
    gulp.task('move-fonts', moveFonts);
    gulp.task('move-fonts-dist', moveFontsDist);
    gulp.task('move-static-content', moveStaticContent);
    gulp.task('move-static-content-dist', moveStaticContentDist);
    gulp.task('run-server-dist', runServerDist);

    function processJs() {
        return gulp.src(config.jsFiles)
            .pipe(plugins.ngAnnotate())
            .pipe(addStream.obj(prepareTemplates()))
            .pipe(plugins.concat('app.js'))
            .pipe(gulp.dest('dev/js/'))
            .on('error', plugins.util.log);
    }

    function processJsDist() {
        return gulp.src(config.jsFiles)
            .pipe(plugins.ngAnnotate())
            .pipe(addStream.obj(prepareTemplates()))
            .pipe(plugins.concat('app.js'))
            .pipe(plugins.uglify())
            .pipe(gulp.dest('dist/js/'))
            .on('error', plugins.util.log);
    }

    function prepareTemplates() {
        return gulp.src(['src/app/**/*.html', '!src/app/common/templates/index.html'])
            .pipe(plugins.angularTemplatecache())
            .on('error', plugins.util.log);
    }

    function processStyles() {
        return gulp.src(config.lessFiles)
            .pipe(plugins.less())
            .pipe(plugins.addSrc.prepend(config.cssFiles))
            .pipe(plugins.concat('app.css'))
            .pipe(gulp.dest('dev/css/'))
            .on('error', plugins.util.log);
    }

    function processStylesDist() {
        return gulp.src(config.lessFiles)
            .pipe(plugins.less())
            .pipe(plugins.addSrc.append(config.cssFiles))
            .pipe(plugins.concat('app.css'))
            .pipe(plugins.minifyCss({ keepSpecialComments: 0 }))
            .pipe(gulp.dest('dist/css/'))
            .on('error', plugins.util.log);
    }

    function moveFonts() {
        return gulp.src(config.fontFiles)
            .pipe(gulp.dest('dev/fonts'))
            .on('error', plugins.util.log);
    }

    function moveFontsDist() {
        return gulp.src(config.fontFiles)
            .pipe(gulp.dest('dist/fonts'))
            .on('error', plugins.util.log);
    }

    function moveStaticContent() {
        return gulp.src(['src/assets/**/*', 'src/app/common/templates/index.html'])
            .pipe(gulp.dest('dev/'))
            .on('error', plugins.util.log);
    }

    function moveStaticContentDist() {
        return gulp.src(['src/assets/**/*', 'src/app/common/templates/index.html'])
            .pipe(gulp.dest('dist/'))
            .on('error', plugins.util.log);
    }

    function runServer() {
        return plugins.connect.server({
            root: 'dev/',
            port: 8888,
            livereload: false,
            fallback: 'dev/index.html',
            host: 'localhost'
        });
    }

    function runServerDist() {
        return plugins.connect.server({
            root: 'dist/',
            port: 9999
        });
    }

    function lint() {
        return gulp.src('src/app/**/*.js')
            .pipe(plugins.jshint())
            .pipe(plugins.jshint.reporter('jshint-stylish'))
            .pipe(plugins.jshint.reporter('fail'))
            .on('error', plugins.util.log);
    }

    function clean() {
        process.on('uncaughtException', function (err) {
            console.log(err);
        })

        return del([
            'dist/*',
            'dev/*'
        ]);
    }

    function watch() {
        return gulp
            .watch('src/**/*.*', ['run'])
            .on('error', plugins.util.log);
    }

}());<|endoftext|>


<commit_before>const browserSync = require('browser-sync').create('browserSync');
const _merge = require('lodash.merge');
const { series, parallel, watch } = require('gulp');
const path = require('path');
const yargs = require('yargs');

const generateTaskInfo = require('./lib/documentation.js');
const timer = require('./lib/timer.js');

const defaultConfig = {
    src: {
        dir: 'src/',
        fonts: 'fonts/**/*.{woff,woff2,ttf,otf,svg}',
        images: 'img/**/*.{png,jpg,jpeg,gif,svg,ico,json,xml}',
        js: 'js/**/*.js',
        sass: 'scss/**/*.scss',
        views: ''
    },
    dist: {
        dir: 'dist/',
        fonts: 'fonts',
        images: 'img',
        js: 'js',
        css: 'css'
    },
    options: {
        autoprefixer: {},
        browsersync: {
            open: false,
            notify: false,
            proxy: ''
        },
        csscomb: path.resolve(__dirname, '.csscomb.json'),
        cssnano: {
            preset: 'default'
        },
        hash: {
            hashLength: 20,
            template: '<%= name %>.<%= hash %><%= ext %>'
        },
        rucksack: {
            responsiveType: true,
            shorthandPosition: false,
            quantityQueries: false,
            inputPseudo: false,
            clearFix: false,
            fontPath: false,
            hexRGBA: false,
            easings: false,
            fallbacks: false,
            autoprefixer: false,
            reporter: false
        },
        sass: {
            includePaths: ['node_modules']
        },
        webpack: {
            // Generated by webpack task
        }
    }
};

function prettyLog(json) {
    console.log(JSON.stringify(json, null, 4));
}

function lynchburg(projectConfig) {
    const config = _merge({}, defaultConfig, projectConfig);

    // Set different flags based on command line arguments
    config.flags = {};
    config.flags.analyze = !!yargs.argv.analyze;
    config.flags.production = !!yargs.argv.production;

    // Build list of resolved paths to pass to tasks
    config.paths = {
        src: {},
        dist: {}
    };

    ['src', 'dist'].forEach(group => {
        Object.keys(config[group]).forEach(dirName => {
            if(dirName == 'dir' || dirName == 'views') {
                return;
            }
            config.paths[group][dirName] = path.resolve(config[group].dir, config[group][dirName])
        });
    });

    // prettyLog(config);

    const tasks = {};

    const clean = require('./tasks/clean.js');

    tasks.clean = clean(config.dist.dir);
    tasks.cleancss = clean(config.paths.dist.css);
    tasks.csscomb = require('./tasks/csscomb.js')(config);
    tasks.fonts = require('./tasks/fonts.js')(config);
    tasks.images = require('./tasks/images.js')(config);
    tasks.sass = series(
        tasks.cleancss,
        require('./tasks/sass.js')(config)
    );
    tasks.webpack = series(
        clean(config.paths.dist.js),
        require('./tasks/webpack.js')(config)
    );

    tasks.reload = cb => {
        browserSync.reload();
        cb();
    };

    // Watchers are passed timed tasks to show output when watched task fires
    tasks.watch = cb => {
        watch(config.paths.src.fonts, tasks.fonts);

        watch(config.paths.src.images, tasks.images);

        watch(config.paths.src.js, series(
            clean(config.paths.dist.js),
            tasks.webpack,
            tasks.reload
        ));

        // Sass watcher is paused during CSScomb and Sass to avoid infinite loop
        const sassWatcher = watch(config.paths.src.sass, series(
            cb => {
                sassWatcher.unwatch(config.paths.src.sass);
                cb();
            },
            tasks.csscomb,
            tasks.sass,
            cb => {
                sassWatcher.add(config.paths.src.sass);
                cb();
            }
        ));

        watch(config.src.views, tasks.reload);
    }

    tasks.serve = cb => {
        browserSync.init(config.options.browsersync);
    }

    // Gulp doesn't show output for tasks in series/parallel when exported via Lynchburg, so force output with timer
    tasks.build = series(
        tasks.clean,
        parallel(
            tasks.fonts,
            tasks.images,
            series(
                tasks.csscomb,
                tasks.sass
            ),
            tasks.webpack
        )
    );

    tasks.default = series(tasks.build, parallel(tasks.serve, tasks.watch));

    // Generate name and description for each task for `gulp --tasks`
    Object.keys(tasks).forEach(taskName => {
        generateTaskInfo(tasks[taskName], taskName);
    });

    return tasks;
};

module.exports = lynchburg;
<commit_msg>Test task display name<commit_after>const browserSync = require('browser-sync').create('browserSync');
const _merge = require('lodash.merge');
const { series, parallel, watch } = require('gulp');
const path = require('path');
const yargs = require('yargs');

const generateTaskInfo = require('./lib/documentation.js');
const timer = require('./lib/timer.js');

const defaultConfig = {
    src: {
        dir: 'src/',
        fonts: 'fonts/**/*.{woff,woff2,ttf,otf,svg}',
        images: 'img/**/*.{png,jpg,jpeg,gif,svg,ico,json,xml}',
        js: 'js/**/*.js',
        sass: 'scss/**/*.scss',
        views: ''
    },
    dist: {
        dir: 'dist/',
        fonts: 'fonts',
        images: 'img',
        js: 'js',
        css: 'css'
    },
    options: {
        autoprefixer: {},
        browsersync: {
            open: false,
            notify: false,
            proxy: ''
        },
        csscomb: path.resolve(__dirname, '.csscomb.json'),
        cssnano: {
            preset: 'default'
        },
        hash: {
            hashLength: 20,
            template: '<%= name %>.<%= hash %><%= ext %>'
        },
        rucksack: {
            responsiveType: true,
            shorthandPosition: false,
            quantityQueries: false,
            inputPseudo: false,
            clearFix: false,
            fontPath: false,
            hexRGBA: false,
            easings: false,
            fallbacks: false,
            autoprefixer: false,
            reporter: false
        },
        sass: {
            includePaths: ['node_modules']
        },
        webpack: {
            // Generated by webpack task
        }
    }
};

function prettyLog(json) {
    console.log(JSON.stringify(json, null, 4));
}

function lynchburg(projectConfig) {
    const config = _merge({}, defaultConfig, projectConfig);

    // Set different flags based on command line arguments
    config.flags = {};
    config.flags.analyze = !!yargs.argv.analyze;
    config.flags.production = !!yargs.argv.production;

    // Build list of resolved paths to pass to tasks
    config.paths = {
        src: {},
        dist: {}
    };

    ['src', 'dist'].forEach(group => {
        Object.keys(config[group]).forEach(dirName => {
            if(dirName == 'dir' || dirName == 'views') {
                return;
            }
            config.paths[group][dirName] = path.resolve(config[group].dir, config[group][dirName])
        });
    });

    // prettyLog(config);

    const tasks = {};

    const clean = require('./tasks/clean.js');

    tasks.clean = clean(config.dist.dir);
    tasks.cleancss = clean(config.paths.dist.css);
    tasks.cleancss.displayName = 'cleancss';
    tasks.csscomb = require('./tasks/csscomb.js')(config);
    tasks.fonts = require('./tasks/fonts.js')(config);
    tasks.images = require('./tasks/images.js')(config);
    tasks.sass = series(
        tasks.cleancss,
        require('./tasks/sass.js')(config)
    );
    tasks.webpack = series(
        clean(config.paths.dist.js),
        require('./tasks/webpack.js')(config)
    );

    tasks.reload = cb => {
        browserSync.reload();
        cb();
    };

    // Watchers are passed timed tasks to show output when watched task fires
    tasks.watch = cb => {
        watch(config.paths.src.fonts, tasks.fonts);

        watch(config.paths.src.images, tasks.images);

        watch(config.paths.src.js, series(
            clean(config.paths.dist.js),
            tasks.webpack,
            tasks.reload
        ));

        // Sass watcher is paused during CSScomb and Sass to avoid infinite loop
        const sassWatcher = watch(config.paths.src.sass, series(
            cb => {
                sassWatcher.unwatch(config.paths.src.sass);
                cb();
            },
            tasks.csscomb,
            tasks.sass,
            cb => {
                sassWatcher.add(config.paths.src.sass);
                cb();
            }
        ));

        watch(config.src.views, tasks.reload);
    }

    tasks.serve = cb => {
        browserSync.init(config.options.browsersync);
    }

    // Gulp doesn't show output for tasks in series/parallel when exported via Lynchburg, so force output with timer
    tasks.build = series(
        tasks.clean,
        parallel(
            tasks.fonts,
            tasks.images,
            series(
                tasks.csscomb,
                tasks.sass
            ),
            tasks.webpack
        )
    );

    tasks.default = series(tasks.build, parallel(tasks.serve, tasks.watch));

    // Generate name and description for each task for `gulp --tasks`
    Object.keys(tasks).forEach(taskName => {
        generateTaskInfo(tasks[taskName], taskName);
    });

    return tasks;
};

module.exports = lynchburg;
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    markdown = require('gulp-markdown'),
    convert = require('gulp-convert'),
    imagemin = require('gulp-imagemin'),
    replace = require('gulp-replace'),
    jsoncombine = require("gulp-jsoncombine"),
    fs = require('fs'),
    del = require('del'),
    config = require('./src/scripts/config.js');

var jsMain = [
    'bower_components/jquery/dist/jquery.js',
    'bower_components/bootstrap/js/transition.js',
    'bower_components/bootstrap/js/button.js',
    'bower_components/bootstrap/js/collapse.js',
    'bower_components/bootstrap/js/dropdown.js',
    'bower_components/bootstrap/js/tooltip.js',
    'bower_components/bootstrap/js/popover.js',
    'bower_components/d3/d3.js',
    'bower_components/leaflet/dist/leaflet.js',
    'bower_components/leaflet.locatecontrol/src/L.Control.Locate.js',
    'bower_components/jquery.scrollTo/jquery.scrollTo.js',
    'bower_components/chosen-build/chosen.jquery.js',
    'bower_components/lodash/lodash.js',
    'bower_components/topojson/topojson.js',
    'bower_components/L.EasyButton/easy-button.js',
    'src/scripts/vendor/log.js',
    'src/scripts/vendor/Object.observe.poly.js',
    'src/scripts/vendor/jquery-ui-1.10.3.custom.min.js',
    'src/scripts/vendor/table2CSV.js',
    'src/scripts/vendor/Chart.js',
    'src/scripts/vendor/typeahead.js',
    'src/scripts/vendor/jquery-tourbus.js',
    'src/scripts/functions/*.js',
    'src/scripts/config.js',
    'src/scripts/main.js'
];

var jsReport = [
    'bower_components/jquery/dist/jquery.js',
    'bower_components/bootstrap/js/button.js',
    'bower_components/leaflet/dist/leaflet.js',
    'bower_components/Leaflet.label/dist/leaflet.label.js',
    'bower_components/topojson/topojson.js',
    'bower_components/lodash/lodash.js',
    'src/scripts/vendor/Chart.js',
    'src/scripts/functions/generics.js',
    'src/scripts/functions/calculations.js',
    'src/scripts/config.js',
    'src/scripts/report.js'
];

// Web server
gulp.task('browser-sync', function() {
    browserSync(['./dist/**/*.css', './dist/**/*.js', './dist/**/*.html'], {
        server: {
            baseDir: "./dist"
        }
    });
});

// Less processing
gulp.task('less', function() {
    return gulp.src(['src/less/main.less', 'src/less/report.less'])
        .pipe(less())
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(gulp.dest('dist/css'));
});
gulp.task('less-build', function() {
    return gulp.src(['src/less/main.less', 'src/less/report.less'])
        .pipe(less())
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/css'));
});

// JavaScript
gulp.task('js', function() {
    gulp.src(jsMain)
        .pipe(concat('main.js'))
        .pipe(gulp.dest('dist/js'));
    return gulp.src(jsReport)
        .pipe(concat('report.js'))
        .pipe(gulp.dest('dist/js'));
});
gulp.task('js-build', function() {
    gulp.src(jsReport)
        .pipe(concat('report.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));
    return gulp.src(jsMain)
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));
});

// markdown
gulp.task('markdown', ['clean'], function() {
    return gulp.src('src/data/meta/*.md')
        .pipe(markdown())
        .pipe(gulp.dest('dist/data/meta/'));
});

// CSV to JSON
gulp.task('convert', ['clean'], function() {
    return gulp.src('src/data/metric/*.csv')
        .pipe(convert({
            from: 'csv',
            to: 'json'
        }))
        .pipe(gulp.dest('dist/data/metric/'));
});

// merge json
gulp.task('merge-json', ['clean', 'convert'], function() {
    return gulp.src("dist/data/metric/*.json")
        .pipe(jsoncombine("merge.json", function(data){ return new Buffer(JSON.stringify(data)); }))
        .pipe(gulp.dest("dist/data"));
});

// image processing
gulp.task('imagemin', function() {
    return gulp.src('src/images/build/*')
        .pipe(imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest('dist/images'));
});

// cache busting
gulp.task('replace', function() {
    return gulp.src('src/*.html')
        .pipe(replace("{{cachebuster}}", Math.floor((Math.random() * 100000) + 1)))
        .pipe(replace("{{neighborhoodDescriptor}}", config.neighborhoodDescriptor))
        .pipe(replace("{{gaKey}}", config.gaKey))
        .pipe(gulp.dest('dist/'));
});

// watch
gulp.task('watch', function () {
    gulp.watch(['./src/*.html'], ['replace']);
    gulp.watch(['./src/less/**/*.less'], ['less']);
    gulp.watch('src/scripts/**/*.js', ['js']);
});

// rename files for basic setup
gulp.task('init', function() {
    // make sure people don't run this twice and end up with no search.js
    fs.exists('src/scripts/functions/search.js.basic', function(exists) {
        if (exists) {
            console.log("renaming search files...");
            // rename mecklenburg search file to search.js.meck
            fs.rename('src/scripts/functions/search.js', 'src/scripts/functions/search.js.advanced', function(err) {
                if ( err ) { console.log('ERROR: ' + err); }
            });
            // rename default search file to search.js
            fs.rename('src/scripts/functions/search.js.basic', 'src/scripts/functions/search.js', function(err) {
                if ( err ) { console.log('ERROR: ' + err); }
            });
        }
  });
});

// clean junk before build
gulp.task('clean', function(cb) {
    del([
    'dist/data/meta/*.html',
    'dist/data/metric/*.json',
    'dist/data/merge.json'
  ], cb);
});

// controller tasks
gulp.task('default', ['less', 'js', 'replace', 'watch', 'browser-sync']);
gulp.task('build', ['less-build', 'js-build', 'replace']);
gulp.task('datagen', ['clean', 'markdown', 'convert', 'merge-json']);
gulp.task('imageshrink', ['imagemin']);
<commit_msg>added data cleaner to gulp file<commit_after>var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    markdown = require('gulp-markdown'),
    convert = require('gulp-convert'),
    imagemin = require('gulp-imagemin'),
    replace = require('gulp-replace'),
    jsoncombine = require("gulp-jsoncombine"),
    fs = require('fs'),
    del = require('del'),
    config = require('./src/scripts/config.js');

var jsMain = [
    'bower_components/jquery/dist/jquery.js',
    'bower_components/bootstrap/js/transition.js',
    'bower_components/bootstrap/js/button.js',
    'bower_components/bootstrap/js/collapse.js',
    'bower_components/bootstrap/js/dropdown.js',
    'bower_components/bootstrap/js/tooltip.js',
    'bower_components/bootstrap/js/popover.js',
    'bower_components/d3/d3.js',
    'bower_components/leaflet/dist/leaflet.js',
    'bower_components/leaflet.locatecontrol/src/L.Control.Locate.js',
    'bower_components/jquery.scrollTo/jquery.scrollTo.js',
    'bower_components/chosen-build/chosen.jquery.js',
    'bower_components/lodash/lodash.js',
    'bower_components/topojson/topojson.js',
    'bower_components/L.EasyButton/easy-button.js',
    'src/scripts/vendor/log.js',
    'src/scripts/vendor/Object.observe.poly.js',
    'src/scripts/vendor/jquery-ui-1.10.3.custom.min.js',
    'src/scripts/vendor/table2CSV.js',
    'src/scripts/vendor/Chart.js',
    'src/scripts/vendor/typeahead.js',
    'src/scripts/vendor/jquery-tourbus.js',
    'src/scripts/functions/*.js',
    'src/scripts/config.js',
    'src/scripts/main.js'
];

var jsReport = [
    'bower_components/jquery/dist/jquery.js',
    'bower_components/bootstrap/js/button.js',
    'bower_components/leaflet/dist/leaflet.js',
    'bower_components/Leaflet.label/dist/leaflet.label.js',
    'bower_components/topojson/topojson.js',
    'bower_components/lodash/lodash.js',
    'src/scripts/vendor/Chart.js',
    'src/scripts/functions/generics.js',
    'src/scripts/functions/calculations.js',
    'src/scripts/config.js',
    'src/scripts/report.js'
];

// Web server
gulp.task('browser-sync', function() {
    browserSync(['./dist/**/*.css', './dist/**/*.js', './dist/**/*.html'], {
        server: {
            baseDir: "./dist"
        }
    });
});

// Less processing
gulp.task('less', function() {
    return gulp.src(['src/less/main.less', 'src/less/report.less'])
        .pipe(less())
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(gulp.dest('dist/css'));
});
gulp.task('less-build', function() {
    return gulp.src(['src/less/main.less', 'src/less/report.less'])
        .pipe(less())
        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(minifycss())
        .pipe(gulp.dest('dist/css'));
});

// JavaScript
gulp.task('js', function() {
    gulp.src(jsMain)
        .pipe(concat('main.js'))
        .pipe(gulp.dest('dist/js'));
    return gulp.src(jsReport)
        .pipe(concat('report.js'))
        .pipe(gulp.dest('dist/js'));
});
gulp.task('js-build', function() {
    gulp.src(jsReport)
        .pipe(concat('report.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));
    return gulp.src(jsMain)
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/js'));
});

// markdown
gulp.task('markdown', ['clean'], function() {
    return gulp.src('src/data/meta/*.md')
        .pipe(markdown())
        .pipe(gulp.dest('dist/data/meta/'));
});

// CSV to JSON
gulp.task('convert', ['clean'], function() {
    return gulp.src('src/data/metric/*.csv')
        .pipe(convert({
            from: 'csv',
            to: 'json'
        }))
        .pipe(gulp.dest('dist/data/metric/'));
});

// merge json
gulp.task('merge-json', ['clean', 'convert'], function() {
    return gulp.src("dist/data/metric/*.json")
        .pipe(jsoncombine("merge.json", function(data){ return new Buffer(JSON.stringify(data)); }))
        .pipe(gulp.dest("dist/data"));
});

// image processing
gulp.task('imagemin', function() {
    return gulp.src('src/images/build/*')
        .pipe(imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest('dist/images'));
});

// cache busting
gulp.task('replace', function() {
    return gulp.src('src/*.html')
        .pipe(replace("{{cachebuster}}", Math.floor((Math.random() * 100000) + 1)))
        .pipe(replace("{{neighborhoodDescriptor}}", config.neighborhoodDescriptor))
        .pipe(replace("{{gaKey}}", config.gaKey))
        .pipe(gulp.dest('dist/'));
});

// watch
gulp.task('watch', function () {
    gulp.watch(['./src/*.html'], ['replace']);
    gulp.watch(['./src/less/**/*.less'], ['less']);
    gulp.watch('src/scripts/**/*.js', ['js']);
});

// rename files for basic setup
gulp.task('init', function() {
    // make sure people don't run this twice and end up with no search.js
    fs.exists('src/scripts/functions/search.js.basic', function(exists) {
        if (exists) {
            console.log("renaming search files...");
            // rename mecklenburg search file to search.js.meck
            fs.rename('src/scripts/functions/search.js', 'src/scripts/functions/search.js.advanced', function(err) {
                if ( err ) { console.log('ERROR: ' + err); }
            });
            // rename default search file to search.js
            fs.rename('src/scripts/functions/search.js.basic', 'src/scripts/functions/search.js', function(err) {
                if ( err ) { console.log('ERROR: ' + err); }
            });
        }
  });
});

// clean junk before build
gulp.task('clean', function(cb) {
    del([
    'dist/data/meta/*.html',
    'dist/data/metric/*.json',
    'dist/data/merge.json'
  ], cb);
});

// clean data out for new location
gulp.task('clean-data', function(cb) {
    del([
    'src/data/meta/*.md',
    'src/data/metric/*.csv',
    'dist/data/geography.topo.json'
  ], cb);
});

// controller tasks
gulp.task('default', ['less', 'js', 'replace', 'watch', 'browser-sync']);
gulp.task('build', ['less-build', 'js-build', 'replace']);
gulp.task('datagen', ['clean', 'markdown', 'convert', 'merge-json']);
gulp.task('imageshrink', ['imagemin']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var config = {
  'src': '',
  'dest': 'dist/',
  'minify': true,
  'sourcemaps': false
};

// HTML
gulp.task('html', function() {
  return gulp.src('*.html')
    .pipe(browserSync.stream());
});

// Compile and autoprefix stylesheets
gulp.task('styles', function() {
  return gulp.src(config.src + 'scss/*.scss')
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.sass({
      precision: 8,
      outputStyle: 'expanded'
    }).on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe($.postcss([
      autoprefixer()
    ]))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe(gulp.dest(config.dest + 'css'))
    .pipe(browserSync.stream())
    .pipe($.cleanCss({compatibility: 'ie9'}))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.rename({suffix: '.min'}))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'css')))
    .pipe(browserSync.stream());
});

// Lint stylesheets
gulp.task('stylelint', function() {
  return gulp.src(config.src + 'scss/**/*.scss')
    .pipe($.postcss([
      require('stylelint')
    ], {
      syntax: require('postcss-scss')
    }));
});

// Compile javascript
gulp.task('scripts', function() {
  return gulp.src(config.src + 'js/*.js')
    .pipe($.include().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe(gulp.dest(config.dest + 'js'))
    .pipe(browserSync.stream())
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.uglify().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.rename({suffix: '.min'}))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'js')))
    .pipe(browserSync.stream());
});

// Lint javascript
gulp.task('eslint', function() {
  return gulp.src(config.src + 'js/**/*.js')
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

// Optimize images
gulp.task('images', function() {
  return gulp.src(config.src + 'img/**/*.{gif,jpg,png,svg}')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest(config.dest + 'img'))
    .pipe(browserSync.stream());
});

// Build production files
gulp.task('build', ['html', 'styles', 'scripts', 'images']);

// Serve compiled files
gulp.task('serve', ['build'], function() {
  browserSync.init({
    server: true,
    notify: false,
    snippetOptions: {
      rule: {
        match: /<\/body>/i
      }
    }
    /*
    proxy: 'example.com',
    files: config.dest,
    serveStatic: [{
      route: '', // remote path
      dir: config.dest // local path
    }],
    */
  });
});

// Watch files for changes
gulp.task('watch', function() {
  gulp.watch(config.src + '*.html', ['html']);
  gulp.watch(config.src + 'scss/**/*.scss', ['styles']);
  gulp.watch(config.src + 'js/**/*.js', ['scripts']);
  gulp.watch(config.src + 'img/**/*.{gif,jpg,png,svg}', ['images']);
});

// Run all tasks
gulp.task('default', ['serve', 'watch']);
<commit_msg>Only execute minify steps if config enabled<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var config = {
  'src': '',
  'dest': 'dist/',
  'minify': true,
  'sourcemaps': false
};

// HTML
gulp.task('html', function() {
  return gulp.src('*.html')
    .pipe(browserSync.stream());
});

// Compile and autoprefix stylesheets
gulp.task('styles', function() {
  return gulp.src(config.src + 'scss/*.scss')
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.sass({
      precision: 8,
      outputStyle: 'expanded'
    }).on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe($.postcss([
      autoprefixer()
    ]))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe(gulp.dest(config.dest + 'css'))
    .pipe(browserSync.stream())
    .pipe($.if(config.minify, $.cleanCss({compatibility: 'ie9'})))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.if(config.minify, $.rename({suffix: '.min'})))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'css')))
    .pipe(browserSync.stream());
});

// Lint stylesheets
gulp.task('stylelint', function() {
  return gulp.src(config.src + 'scss/**/*.scss')
    .pipe($.postcss([
      require('stylelint')
    ], {
      syntax: require('postcss-scss')
    }));
});

// Compile javascript
gulp.task('scripts', function() {
  return gulp.src(config.src + 'js/*.js')
    .pipe($.include().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    }))
    .pipe(gulp.dest(config.dest + 'js'))
    .pipe(browserSync.stream())
    .pipe($.if(config.sourcemaps, $.sourcemaps.init()))
    .pipe($.if(config.minify, $.uglify().on('error', function(error) {
      $.util.log($.util.colors.red(error.message));
      this.emit('end');
    })))
    .pipe($.if(config.sourcemaps, $.sourcemaps.write()))
    .pipe($.if(config.minify, $.rename({suffix: '.min'})))
    .pipe($.if(config.minify, gulp.dest(config.dest + 'js')))
    .pipe(browserSync.stream());
});

// Lint javascript
gulp.task('eslint', function() {
  return gulp.src(config.src + 'js/**/*.js')
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

// Optimize images
gulp.task('images', function() {
  return gulp.src(config.src + 'img/**/*.{gif,jpg,png,svg}')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest(config.dest + 'img'))
    .pipe(browserSync.stream());
});

// Build production files
gulp.task('build', ['html', 'styles', 'scripts', 'images']);

// Serve compiled files
gulp.task('serve', ['build'], function() {
  browserSync.init({
    server: true,
    notify: false,
    snippetOptions: {
      rule: {
        match: /<\/body>/i
      }
    }
    /*
    proxy: 'example.com',
    files: config.dest,
    serveStatic: [{
      route: '', // remote path
      dir: config.dest // local path
    }],
    */
  });
});

// Watch files for changes
gulp.task('watch', function() {
  gulp.watch(config.src + '*.html', ['html']);
  gulp.watch(config.src + 'scss/**/*.scss', ['styles']);
  gulp.watch(config.src + 'js/**/*.js', ['scripts']);
  gulp.watch(config.src + 'img/**/*.{gif,jpg,png,svg}', ['images']);
});

// Run all tasks
gulp.task('default', ['serve', 'watch']);
<|endoftext|>


<commit_before>var bump = require('gulp-bump');
var exec = require('child_process').exec;
var fs = require('fs-extra');
var git = require('gulp-git');
var syncToGitHub = require('sync-to-github');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var tagVersion = require('gulp-tag-version');
var template = require('gulp-template');
var util = require('util');
var yaml = require('js-yaml');
var resource = require('./src/resource');
var helpers = require('./src/helpers');
var _ = require('lodash');
var Bluebird = require('bluebird');
var GitHubApi = require('github');
var dateFormat = require('dateformat');

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

/**
 * Environment
 */
var languages = {
  js: {
    repo: 'Asana/node-asana',
    outputPath: 'lib/resources/gen',
    preserveRepoFiles: false
  },
  php: {
    repo: 'Asana/php-asana',
    outputPath: 'src/Asana/Resources/Gen',
    preserveRepoFiles: false
  },
  java: {
    repo: 'Asana/java-asana',
    outputPath: 'src/main/java/com/asana/resources/gen',
    preserveRepoFiles: false
  },
  python: {
    repo: 'Asana/python-asana',
    outputPath: 'asana/resources/gen',
    // Keep the __init__.py file there
    preserveRepoFiles: true
  },
  ruby: {
    repo: 'Asana/ruby-asana',
    outputPath: 'lib/asana/resources',
    preserveRepoFiles: false,
    skip: ['event']
  },
  api_explorer: {
    repo: 'Asana/api-explorer',
    outputPath: 'src/resources/gen',
    preserveRepoFiles: false
  },
  api_reference: {
    repo: 'Asana/asanastatic',
    outputPath: '_content/developers/02-api-reference',
    // Keep the other markdown pages and metadata there
    preserveRepoFiles: true
  }
};

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

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

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

/**
 * High-level tasks
 */

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

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

// Store a single timestamp representing right now.
var nowTimestamp = dateFormat('yyyymmdd-HHMMss');

/**
 * Generate build and deploy rules for each language
 */
var resourceNames = resource.names();
Object.keys(languages).forEach(function(lang) {
  var config = languages[lang];
  var token = process.env.ASANA_GITHUB_TOKEN || null;
  var isProd = (process.env.PROD == '1');

  function echoAndExec(command, options) {
    if (process.env.GULP_DEBUG) {
      console.log('+ ' + arguments[0]);
    }

    return new Bluebird(function(resolve, reject) {
      return exec(command, options, function(err, stdout, stderr) {
        if (err) {
          reject(err);
        } else {
          resolve(stdout);
        }
      });
    });
  }

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

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

  /**
   * Build rules, per resource.
   */
  var resourcesToSkip = config.skip || [];
  var resourcesToBuild = _.difference(resourceNames, resourcesToSkip);
  resourcesToBuild.forEach(function(resourceName) {
    gulp.task(resTaskName(resourceName), function() {
      // Support only local templates
      var templatePath = 'src/templates/' + lang;
      var resourceTemplateInfo = require('./' + templatePath).resource;

      // Load the resource yaml into a variable
      var resourceInstance = resource.load(resourceName);
      var templateHelpers = helpers(lang);
      templateHelpers.resources = resourceNames;
      // Load the resource file
      return gulp.src(templatePath + '/' + resourceTemplateInfo.template)
          .pipe( //Pipe it through a templating path with the language-specific helpers
              template(resourceInstance, {
                imports: templateHelpers,
                variable: 'resource'
              }))
          .pipe( //Pipe it through a file renaming step, i.e. resource.ejs becomes project.rb
              rename(resourceTemplateInfo.filename(resourceInstance, templateHelpers)))
          .pipe( //Pipe it to the output destination
              gulp.dest(paths.dist(lang)));
    });
  });
  gulp.task(
      'build-' + lang,
      resourcesToBuild.map(resTaskName));

  /**
   * Deploy
   */

  /**
   * @returns {Promise<String>} The commit message to provide for a deployment.
   */
  function createCommitMessage(user) {
    var version = readPackage().version;
    var revParse = Bluebird.promisify(git.revParse, git);

    var githubUserName = user.login;
    return revParse({args: '--abbrev-ref HEAD'}).then(function(branchName) {
      return revParse({args: '--short HEAD'}).then(function(commitHash) {
        var commitDesc = branchName.trim() ?
            util.format("%s/%s", commitHash, branchName.trim()) :
            commitHash;
        return util.format(
            "Deploy from asana-api-meta v%s (%s) by %s",
            version, commitDesc, githubUserName);
      });
    });
  }

  function getGitHubUser() {
    var github = githubClient(token);
    var getUser = Bluebird.promisify(github.user.get, github.user);
    return getUser({});
  }

  function deployWithGithubApi() {
    return getGitHubUser().then(function(user) {
      var branchName = isProd ?
          'api-meta-incoming' :
          (user.login + '-' + nowTimestamp);
      return createCommitMessage(user).then(function(commitMessage) {
        var repoParts = config.repo.split('/');
        return syncToGitHub({
          oauthToken: token,
          user: repoParts[0],
          repo: repoParts[1],
          localPath: paths.dist(lang),
          repoPath: paths.repoOutputRelative(lang),
          branch: branchName,
          baseBranch: 'master',
          createBranch: true,
          message: commitMessage,
          preserveRepoFiles: !!config.preserveRepoFiles,
          createPullRequest: isProd,
          debug: !!process.env.GULP_DEBUG
        });
      });
    });
  }

  function githubClient(token) {
    var github = new GitHubApi({
      version: '3.0.0',
      protocol: 'https',
      host: 'api.github.com'
    });
    github.authenticate({
      type: 'oauth',
      token: token
    });
    return github;
  }

  gulp.task(
      'deploy-' + lang,
      ['ensure-git-clean', 'build-' + lang],
      deployWithGithubApi);
});

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

/**
 * Ensure that the git working directory is clean.
 */
gulp.task('ensure-git-clean', function() {
  git.status(function(err, out) {
    if (err) { throw err; }
    if (!/working directory clean/.exec(out)) {
      // Working directory must be clean for some operations.
      // For bumping the version, this prevents accidental commits of
      // unintended or partial changes.
      // For deployment, this ensures that the deploy is tagged with a commit
      // and that can be used to reference the exact state of the repo (if we
      // allowed changes then the commit would not tell us what the code
      // actually looked like).
      throw new Error('Git working directory not clean, will not proceed.');
    }
  });
});

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

/**
 * Copy the documents for api-reference to a sibling static site installation.
 * TODO: it appears that the convention might be to do all of those repos in
 * subdirs (as opposed to sibling dirs), based on paths.repoOutputRelative
 */

gulp.task('local-copy-api-reference', ['build-api_reference'], function(callback) {
  fs.copySync(paths.dist('api_reference'), "../vagrant-php7/asanastatic/" + paths.repoOutputRelative('api_reference'));
  callback()
});

/**
 * Setup gulp to watch the metadata and depoly to a working copy
 * of the static site. The only assumptions are that asana-api-meta
 * and the static site repo are in the same directory.
 */
gulp.task('watch-documents', function(callback) {
  gulp.watch("src/**/*.{js,yaml,ejs}", ['local-copy-api-reference']);
});

gulp.task('default', ['build', 'local-copy-api-reference']);
<commit_msg>Change regex for ensuring clean git dir.<commit_after>var bump = require('gulp-bump');
var exec = require('child_process').exec;
var fs = require('fs-extra');
var git = require('gulp-git');
var syncToGitHub = require('sync-to-github');
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var tagVersion = require('gulp-tag-version');
var template = require('gulp-template');
var util = require('util');
var yaml = require('js-yaml');
var resource = require('./src/resource');
var helpers = require('./src/helpers');
var _ = require('lodash');
var Bluebird = require('bluebird');
var GitHubApi = require('github');
var dateFormat = require('dateformat');

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

/**
 * Environment
 */
var languages = {
  js: {
    repo: 'Asana/node-asana',
    outputPath: 'lib/resources/gen',
    preserveRepoFiles: false
  },
  php: {
    repo: 'Asana/php-asana',
    outputPath: 'src/Asana/Resources/Gen',
    preserveRepoFiles: false
  },
  java: {
    repo: 'Asana/java-asana',
    outputPath: 'src/main/java/com/asana/resources/gen',
    preserveRepoFiles: false
  },
  python: {
    repo: 'Asana/python-asana',
    outputPath: 'asana/resources/gen',
    // Keep the __init__.py file there
    preserveRepoFiles: true
  },
  ruby: {
    repo: 'Asana/ruby-asana',
    outputPath: 'lib/asana/resources',
    preserveRepoFiles: false,
    skip: ['event']
  },
  api_explorer: {
    repo: 'Asana/api-explorer',
    outputPath: 'src/resources/gen',
    preserveRepoFiles: false
  },
  api_reference: {
    repo: 'Asana/asanastatic',
    outputPath: '_content/developers/02-api-reference',
    // Keep the other markdown pages and metadata there
    preserveRepoFiles: true
  }
};

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

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

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

/**
 * High-level tasks
 */

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

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

// Store a single timestamp representing right now.
var nowTimestamp = dateFormat('yyyymmdd-HHMMss');

/**
 * Generate build and deploy rules for each language
 */
var resourceNames = resource.names();
Object.keys(languages).forEach(function(lang) {
  var config = languages[lang];
  var token = process.env.ASANA_GITHUB_TOKEN || null;
  var isProd = (process.env.PROD == '1');

  function echoAndExec(command, options) {
    if (process.env.GULP_DEBUG) {
      console.log('+ ' + arguments[0]);
    }

    return new Bluebird(function(resolve, reject) {
      return exec(command, options, function(err, stdout, stderr) {
        if (err) {
          reject(err);
        } else {
          resolve(stdout);
        }
      });
    });
  }

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

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

  /**
   * Build rules, per resource.
   */
  var resourcesToSkip = config.skip || [];
  var resourcesToBuild = _.difference(resourceNames, resourcesToSkip);
  resourcesToBuild.forEach(function(resourceName) {
    gulp.task(resTaskName(resourceName), function() {
      // Support only local templates
      var templatePath = 'src/templates/' + lang;
      var resourceTemplateInfo = require('./' + templatePath).resource;

      // Load the resource yaml into a variable
      var resourceInstance = resource.load(resourceName);
      var templateHelpers = helpers(lang);
      templateHelpers.resources = resourceNames;
      // Load the resource file
      return gulp.src(templatePath + '/' + resourceTemplateInfo.template)
          .pipe( //Pipe it through a templating path with the language-specific helpers
              template(resourceInstance, {
                imports: templateHelpers,
                variable: 'resource'
              }))
          .pipe( //Pipe it through a file renaming step, i.e. resource.ejs becomes project.rb
              rename(resourceTemplateInfo.filename(resourceInstance, templateHelpers)))
          .pipe( //Pipe it to the output destination
              gulp.dest(paths.dist(lang)));
    });
  });
  gulp.task(
      'build-' + lang,
      resourcesToBuild.map(resTaskName));

  /**
   * Deploy
   */

  /**
   * @returns {Promise<String>} The commit message to provide for a deployment.
   */
  function createCommitMessage(user) {
    var version = readPackage().version;
    var revParse = Bluebird.promisify(git.revParse, git);

    var githubUserName = user.login;
    return revParse({args: '--abbrev-ref HEAD'}).then(function(branchName) {
      return revParse({args: '--short HEAD'}).then(function(commitHash) {
        var commitDesc = branchName.trim() ?
            util.format("%s/%s", commitHash, branchName.trim()) :
            commitHash;
        return util.format(
            "Deploy from asana-api-meta v%s (%s) by %s",
            version, commitDesc, githubUserName);
      });
    });
  }

  function getGitHubUser() {
    var github = githubClient(token);
    var getUser = Bluebird.promisify(github.user.get, github.user);
    return getUser({});
  }

  function deployWithGithubApi() {
    return getGitHubUser().then(function(user) {
      var branchName = isProd ?
          'api-meta-incoming' :
          (user.login + '-' + nowTimestamp);
      return createCommitMessage(user).then(function(commitMessage) {
        var repoParts = config.repo.split('/');
        return syncToGitHub({
          oauthToken: token,
          user: repoParts[0],
          repo: repoParts[1],
          localPath: paths.dist(lang),
          repoPath: paths.repoOutputRelative(lang),
          branch: branchName,
          baseBranch: 'master',
          createBranch: true,
          message: commitMessage,
          preserveRepoFiles: !!config.preserveRepoFiles,
          createPullRequest: isProd,
          debug: !!process.env.GULP_DEBUG
        });
      });
    });
  }

  function githubClient(token) {
    var github = new GitHubApi({
      version: '3.0.0',
      protocol: 'https',
      host: 'api.github.com'
    });
    github.authenticate({
      type: 'oauth',
      token: token
    });
    return github;
  }

  gulp.task(
      'deploy-' + lang,
      ['ensure-git-clean', 'build-' + lang],
      deployWithGithubApi);
});

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

/**
 * Ensure that the git working directory is clean.
 */
gulp.task('ensure-git-clean', function() {
  git.status(function(err, out) {
    if (err) { throw err; }
    if (!/working tree clean/.exec(out)) {
      // Working directory must be clean for some operations.
      // For bumping the version, this prevents accidental commits of
      // unintended or partial changes.
      // For deployment, this ensures that the deploy is tagged with a commit
      // and that can be used to reference the exact state of the repo (if we
      // allowed changes then the commit would not tell us what the code
      // actually looked like).
      throw new Error('Git working directory not clean, will not proceed.');
    }
  });
});

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

/**
 * Copy the documents for api-reference to a sibling static site installation.
 * TODO: it appears that the convention might be to do all of those repos in
 * subdirs (as opposed to sibling dirs), based on paths.repoOutputRelative
 */

gulp.task('local-copy-api-reference', ['build-api_reference'], function(callback) {
  fs.copySync(paths.dist('api_reference'), "../vagrant-php7/asanastatic/" + paths.repoOutputRelative('api_reference'));
  callback()
});

/**
 * Setup gulp to watch the metadata and depoly to a working copy
 * of the static site. The only assumptions are that asana-api-meta
 * and the static site repo are in the same directory.
 */
gulp.task('watch-documents', function(callback) {
  gulp.watch("src/**/*.{js,yaml,ejs}", ['local-copy-api-reference']);
});

gulp.task('default', ['build', 'local-copy-api-reference']);
<|endoftext|>


<commit_before>var path = require('path')
var gulp = require('gulp')
var runSequence = require('run-sequence')
var gutil = require('gulp-util')
var webpack = require('webpack')
var del = require('del')
var babel = require("gulp-babel")

var PATH = {
  SRC: path.join(__dirname, './src'),
  DIST: path.join(__dirname, './dist')
}

gulp.task('build:clean', function() {
  return del(path.join(PATH.DIST, './**/*'))
})

gulp.task('build:client:compile', function(callback) {
  webpack(require('./webpack.prod.config'), function(err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack', err)
    }
    gutil.log('[webpack]', stats.toString({ colors: true }))
    callback()
  })
})

gulp.task('build:client:copy', function() {
  return gulp.src(path.join(PATH.SRC, './server/public/**/*'))
  .pipe(gulp.dest(path.join(PATH.DIST, './public')))
})

gulp.task('build:client', function(callback) {
  runSequence(
    'build:client:compile',
    'build:client:copy',
    callback
  )
})

gulp.task('build:server', function() {
  return gulp.src([
    path.join(PATH.SRC, './server/**/*.js'),
    '!' + path.join(PATH.SRC, './server/public/**/*'),
    '!' + path.join(PATH.SRC, './server/index.dev.js')
  ])
  .pipe(babel())
  .pipe(gulp.dest(PATH.DIST))
})

gulp.task('build:copy-package', function() {
  return gulp.src(path.join(__dirname, './package.json'))
  .pipe(gulp.dest(PATH.DIST))
})

gulp.task('build:copy-views', function() {
  return gulp.src(path.join(PATH.SRC, './server/views/**/*'))
  .pipe(gulp.dest(path.join(PATH.DIST, './views')))
})

gulp.task('build', function(callback) {
  runSequence(
    'build:clean',
    ['build:client', 'build:server'],
    ['build:copy-package', 'build:copy-views'],
    callback
  )
})
<commit_msg>修改gulpfile，增加build后删除生成的前端文件，要不然webpack总是用build出来的文件而不用hotloader里的<commit_after>var path = require('path')
var gulp = require('gulp')
var runSequence = require('run-sequence')
var gutil = require('gulp-util')
var webpack = require('webpack')
var del = require('del')
var babel = require("gulp-babel")

var PATH = {
  SRC: path.join(__dirname, './src'),
  DIST: path.join(__dirname, './dist')
}

gulp.task('build:clean', function() {
  return del(path.join(PATH.DIST, './**/*'))
})

gulp.task('build:client:compile', function(callback) {
  webpack(require('./webpack.prod.config'), function(err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack', err)
    }
    gutil.log('[webpack]', stats.toString({ colors: true }))
    callback()
  })
})

gulp.task('build:client:copy', function() {
  return gulp.src(path.join(PATH.SRC, './server/public/**/*'))
  .pipe(gulp.dest(path.join(PATH.DIST, './public')))
})

gulp.task('build:client:del', function() {
  return del([
    path.join(PATH.SRC, './server/public/javascripts/main-app.js'),
    path.join(PATH.SRC, './server/public/javascripts/share-app.js')
  ])
})

gulp.task('build:client', function(callback) {
  runSequence(
    'build:client:compile',
    'build:client:copy',
    'build:client:del',
    callback
  )
})

gulp.task('build:server', function() {
  return gulp.src([
    path.join(PATH.SRC, './server/**/*.js'),
    '!' + path.join(PATH.SRC, './server/public/**/*'),
    '!' + path.join(PATH.SRC, './server/index.dev.js')
  ])
  .pipe(babel())
  .pipe(gulp.dest(PATH.DIST))
})

gulp.task('build:copy-package', function() {
  return gulp.src(path.join(__dirname, './package.json'))
  .pipe(gulp.dest(PATH.DIST))
})

gulp.task('build:copy-views', function() {
  return gulp.src(path.join(PATH.SRC, './server/views/**/*'))
  .pipe(gulp.dest(path.join(PATH.DIST, './views')))
})

gulp.task('build', function(callback) {
  runSequence(
    'build:clean',
    ['build:client', 'build:server'],
    ['build:copy-package', 'build:copy-views'],
    callback
  )
})
<|endoftext|>