<commit_before>/* eslint-disable */
var gulp = require('gulp'),
  path = require('path'),
  ngc = require('@angular/compiler-cli/src/main').main,
  rollup = require('gulp-rollup'),
  del = require('del'),
  runSequence = require('run-sequence'),
  inlineResources = require('./tools/gulp/inline-resources');

const rootFolder = path.join(__dirname);
const srcFolder = path.join(rootFolder, 'src');
const tmpFolder = path.join(rootFolder, '.tmp');
const buildFolder = path.join(rootFolder, 'build');
const distFolder = path.join(rootFolder, 'dist');

/**
 * 1. Delete /dist folder
 */
gulp.task('clean:dist', function () {
  return deleteFolders([distFolder]);
});

/**
 * 2. Clone the /src folder into /.tmp. If an npm link inside /src has been made,
 *    then it's likely that a node_modules folder exists. Ignore this folder
 *    when copying to /.tmp.
 */
gulp.task('copy:source', function () {
  return gulp.src([`${srcFolder}/**/*`, `!${srcFolder}/node_modules`])
    .pipe(gulp.dest(tmpFolder));
});

/**
 * 3. Inline template (.html) and style (.css) files into the the component .ts files.
 *    We do this on the /.tmp folder to avoid editing the original /src files
 */
gulp.task('inline-resources', function () {
  return Promise.resolve()
    .then(() => inlineResources(tmpFolder));
});

/**
 * 4. Run the Angular compiler, ngc, on the /.tmp folder. This will output all
 *    compiled modules to the /build folder.
 */
gulp.task('ngc', function () {
  return ngc({
    project: `${tmpFolder}/tsconfig.es5.json`
  })
    .then((exitCode) => {
      if (exitCode === 1) {
        // This error is caught in the 'compile' task by the runSequence method callback
        // so that when ngc fails to compile, the whole compile process stops running
        throw new Error('ngc compilation failed');
      }
  });
});

/**
 * 5. Run rollup inside the /build folder to generate our Flat ES module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({
      // any option supported by Rollup can be set here.
      input: `${buildFolder}/index.js`,
      output: {
        format: 'es',
      },
      external: [
        '@angular/core',
        '@angular/common'
      ]
    }))
    .pipe(gulp.dest(distFolder));
});

/**
 * 6. Copy all the files from /build to /dist, except .js files. We ignore all .js from /build
 *    because with don't need individual modules anymore, just the Flat ES module generated
 *    on step 5.
 */
gulp.task('copy:build', function () {
  return gulp.src([`${buildFolder}/**/*`, `!${buildFolder}/**/*.js`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 7. Copy package.json from /src to /dist
 */
gulp.task('copy:manifest', function () {
  return gulp.src([`${srcFolder}/package.json`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 8. Copy README.md from /src to /dist
 */
gulp.task('copy:readme', function () {
  return gulp.src([`${srcFolder}/README.md`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 9. Delete /.tmp folder
 */
gulp.task('clean:tmp', function () {
  return deleteFolders([tmpFolder]);
});

/**
 * 10. Delete /build folder
 */
gulp.task('clean:build', function () {
  return deleteFolders([buildFolder]);
});

gulp.task('compile', function () {
  runSequence(
    'clean:dist',
    'copy:source',
    'inline-resources',
    'ngc',
    'rollup',
    'copy:build',
    'copy:manifest',
    'copy:readme',
    'clean:build',
    'clean:tmp',
    function (err) {
      if (err) {
        console.log('ERROR:', err.message);
        deleteFolders([distFolder, tmpFolder, buildFolder]);
      } else {
        console.log('Compilation finished succesfully');
      }
    });
});

/**
 * Watch for any change in the /src folder and compile files
 */
gulp.task('watch', function () {
  gulp.watch(`${srcFolder}/**/*`, ['compile']);
});

gulp.task('clean', ['clean:dist', 'clean:tmp', 'clean:build']);

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

/**
 * Deletes the specified folder
 */
function deleteFolders(folders) {
  return del(folders);
}
<commit_msg>Migrate Gulp tasks<commit_after>/* eslint-disable */
const path = require('path'),
  ngc = require('@angular/compiler-cli/src/main').main,
  rollup = require('gulp-rollup'),
  del = require('del'),
  inlineResources = require('./tools/gulp/inline-resources');

const { watch, series, parallel, src, dest } = require('gulp');

const rootFolder = path.join(__dirname);
const srcFolder = path.join(rootFolder, 'src');
const tmpFolder = path.join(rootFolder, '.tmp');
const buildFolder = path.join(rootFolder, 'build');
const distFolder = path.join(rootFolder, 'dist');

/**
 * 1. Delete /dist folder
 */
function cleanDist() {
  return deleteFolders([distFolder]);
}

/**
 * 2. Clone the /src folder into /.tmp. If an npm link inside /src has been made,
 *    then it's likely that a node_modules folder exists. Ignore this folder
 *    when copying to /.tmp.
 */
function copySource() {
  return src([`${srcFolder}/**/*`, `!${srcFolder}/node_modules`])
    .pipe(dest(tmpFolder));
}

/**
 * 3. Inline template (.html) and style (.css) files into the the component .ts files.
 *    We do this on the /.tmp folder to avoid editing the original /src files
 */
function inlineRes() {
   return inlineResources(tmpFolder);
}

/**
 * 4. Run the Angular compiler, ngc, on the /.tmp folder. This will output all
 *    compiled modules to the /build folder.
 */
function angularCompile() {
  return ngc({
    project: `${tmpFolder}/tsconfig.es5.json`
  })
    .then((exitCode) => {
      if (exitCode === 1) {
        // This error is caught in the 'compile' task by the runSequence method callback
        // so that when ngc fails to compile, the whole compile process stops running
        throw new Error('ngc compilation failed');
      }
  });
}

/**
 * 5. Run rollup inside the /build folder to generate our Flat ES module and place the
 *    generated file into the /dist folder
 */
function rollupBuild() {
  return src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({
      // any option supported by Rollup can be set here.
      input: `${buildFolder}/index.js`,
      output: {
        format: 'es',
      },
      external: [
        '@angular/core',
        '@angular/common'
      ]
    }))
    .pipe(dest(distFolder));
}

/**
 * 6. Copy all the files from /build to /dist, except .js files. We ignore all .js from /build
 *    because with don't need individual modules anymore, just the Flat ES module generated
 *    on step 5.
 */
function copyBuild() {
  return src([`${buildFolder}/**/*`, `!${buildFolder}/**/*.js`])
    .pipe(dest(distFolder));
}

/**
 * 7. Copy package.json from /src to /dist
 */
function copyManifest() {
  return src([`${srcFolder}/package.json`])
    .pipe(dest(distFolder));
}

/**
 * 8. Copy README.md from /src to /dist
 */
function copyReadme() {
  return src([`${srcFolder}/README.md`])
    .pipe(dest(distFolder));
}

/**
 * 9. Delete /.tmp folder
 */
function cleanTmp() {
  return deleteFolders([tmpFolder]);
}

/**
 * 10. Delete /build folder
 */
function cleanBuild() {
  return deleteFolders([buildFolder]);
}

/**
 * Deletes the specified folder
 */
function deleteFolders(folders) {
  return del(folders);
}

function watchSrc() {
  return watch(`${srcFolder}/**/*`, exports.build);
}

exports.clean = parallel(cleanDist, cleanTmp, cleanBuild);
exports.build = series(
  exports.clean,
  series(
    copySource,
    inlineRes,
    angularCompile,
    rollupBuild,
    copyBuild,
    copyManifest,
    copyReadme,
    cleanBuild,
    cleanTmp
  )
);
exports.watch = watchSrc;
exports.buildWatch = series(exports.build, exports.watch);
exports.default = exports.buildWatch;
<|endoftext|>


<commit_before>/**
 * Plugins
 */
var gulp         = require('gulp');
    sass         = require('gulp-sass'),
    sourcemaps   = require('gulp-sourcemaps'),
    postcss      = require('gulp-postcss'),
    autoprefixer = require('autoprefixer'),
    mqpacker     = require('css-mqpacker'),
    csso         = require('gulp-csso'),
    rename       = require("gulp-rename"),
    plumber      = require('gulp-plumber'),
    concat       = require('gulp-concat'),
    imageOptim   = require('gulp-imageoptim'),
    uglify       = require('gulp-uglify'),
    notify       = require("gulp-notify"),
    browserSync  = require('browser-sync').create(),
    reload       = browserSync.reload;

/**
 * PATHS
 */
var src  = '/',
    dist = '/'

/**
 * CSS
 */
gulp.task('css', function () {
    var processors = [
        autoprefixer({browsers: ['last 3 version']}),
        mqpacker({
            sort: true
        })
    ];
    return gulp.src('scss/style.scss')
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle : 'expanded',
            sourceComments: 'map'
        })
        .on('error', notify.onError("Error: <%= error.message %>")))
        .pipe(sourcemaps.write())
        .pipe(postcss(processors))
        .pipe(gulp.dest('css/'))
        .pipe(browserSync.stream());
});

gulp.task('minify-css', function() {
  return gulp.src('css/style.css')
    .pipe(csso())
    .pipe(gulp.dest('css/'));
});

/**
 * JAVASCRIPT
 */

// compile
gulp.task('jsLibs', function() { // Concatenate all JS libs
    return gulp.src('js/app/plugins/*.js')
    .pipe(concat('plugins.js'))
    .pipe(gulp.dest('js/'));
});

gulp.task('jsScripts', function() { // Move main js script file
    gulp.src('js/app/index.js')
    .pipe(concat('script.js'))
    .pipe(gulp.dest('js/'))
    .pipe(browserSync.stream());
});

//build for prod
gulp.task('jsScriptsBuild', function() { // Move and minify main js script file
    gulp.src('js/app/index.js')
    .pipe(concat('script.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/'));
});

gulp.task('jsLibsBuild', function() { // Concatenate and minify libs file
  return gulp.src('js/app/plugins/*.js')
    .pipe(concat('plugins.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/'));
});

gulp.task('browser-sync', function() {
   browserSync.init({
        server: {
            baseDir: "./"
        }
    });
});

 /**
 * TASKS
 */

// default task (development)
gulp.task('default', ['css', 'jsLibs', 'jsScripts', 'browser-sync'], function () {
    gulp.watch('scss/**/*.scss', ['css']).on("change", reload);
    gulp.watch('js/**/*.js', ['jsScripts', 'jsLibs']).on("change", reload);;
    // gulp.watch('img/**/*', ['images']);
    gulp.watch('**/*.html').on("change", reload);
});

// Build tasks
gulp.task( "prod", ['minify-css', 'jsLibsBuild', 'jsScriptsBuild'], function () {
    console.log("Build complete !");
});
<commit_msg>Added BS local dev config snippet<commit_after>/**
 * Plugins
 */
var gulp         = require('gulp');
    sass         = require('gulp-sass'),
    sourcemaps   = require('gulp-sourcemaps'),
    postcss      = require('gulp-postcss'),
    autoprefixer = require('autoprefixer'),
    mqpacker     = require('css-mqpacker'),
    csso         = require('gulp-csso'),
    rename       = require("gulp-rename"),
    plumber      = require('gulp-plumber'),
    concat       = require('gulp-concat'),
    imageOptim   = require('gulp-imageoptim'),
    uglify       = require('gulp-uglify'),
    notify       = require("gulp-notify"),
    browserSync  = require('browser-sync').create(),
    reload       = browserSync.reload;

/**
 * PATHS
 */
var src  = '/',
    dist = '/'

/**
 * CSS
 */
gulp.task('css', function () {
    var processors = [
        autoprefixer({browsers: ['last 3 version']}),
        mqpacker({
            sort: true
        })
    ];
    return gulp.src('scss/style.scss')
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle : 'expanded',
            sourceComments: 'map'
        })
        .on('error', notify.onError("Error: <%= error.message %>")))
        .pipe(sourcemaps.write())
        .pipe(postcss(processors))
        .pipe(gulp.dest('css/'))
        .pipe(browserSync.stream());
});

gulp.task('minify-css', function() {
  return gulp.src('css/style.css')
    .pipe(csso())
    .pipe(gulp.dest('css/'));
});

/**
 * JAVASCRIPT
 */

// compile
gulp.task('jsLibs', function() { // Concatenate all JS libs
    return gulp.src('js/app/plugins/*.js')
    .pipe(concat('plugins.js'))
    .pipe(gulp.dest('js/'));
});

gulp.task('jsScripts', function() { // Move main js script file
    gulp.src('js/app/index.js')
    .pipe(concat('script.js'))
    .pipe(gulp.dest('js/'))
    .pipe(browserSync.stream());
});

//build for prod
gulp.task('jsScriptsBuild', function() { // Move and minify main js script file
    gulp.src('js/app/index.js')
    .pipe(concat('script.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/'));
});

gulp.task('jsLibsBuild', function() { // Concatenate and minify libs file
  return gulp.src('js/app/plugins/*.js')
    .pipe(concat('plugins.js'))
    .pipe(uglify())
    .pipe(gulp.dest('js/'));
});

gulp.task('browser-sync', function() {
   browserSync.init({
        server: {
            baseDir: "./"
        }
    });

    // browserSync.init({
    //     proxy: "yourlocal.dev"
    // });

});

 /**
 * TASKS
 */

// default task (development)
gulp.task('default', ['css', 'jsLibs', 'jsScripts', 'browser-sync'], function () {
    gulp.watch('scss/**/*.scss', ['css']).on("change", reload);
    gulp.watch('js/**/*.js', ['jsScripts', 'jsLibs']).on("change", reload);;
    // gulp.watch('img/**/*', ['images']);
    gulp.watch('**/*.html').on("change", reload);
});

// Build tasks
gulp.task( "prod", ['minify-css', 'jsLibsBuild', 'jsScriptsBuild'], function () {
    console.log("Build complete !");
});
<|endoftext|>


<commit_before>const glob = require('glob');
const gulp = require('gulp');
const env = require('./utils/env');

function loadTask(dir, callback) {
  const files = glob.sync(`${dir}/**/*.js`);
  files.forEach((file) => {
    const task = require(file); // eslint-disable-line
    callback(task);
  });
}

const options = {
  homePath: process.cwd(),
  srcDir: './src',
  cssDir: '/css',
  jsDir: '/js',
  imageDir: '/image',
  staticDir: '/static',
  distDir: './assets',
  componentsDir: '/components',
  env
};

const prodTasks = [];
const defaultTasks = [];

const tasksDir = './tasks';

loadTask(tasksDir, (task) => {
  const deps = task.deps || [];
  gulp.task(task.name, deps, task.bind(gulp, options));

  if (task.production !== false) {
    prodTasks.push(task.name);
  }

  if (task.development !== false) {
    defaultTasks.push(task.name);
  }
});

gulp.task('default', defaultTasks);
gulp.task('production', prodTasks);

function runTask(envName = 'development', opts = {}) {
  opts.env = env.getEnv(envName);

  Object.extend(options, opts);

  if (opts.env.isProduction) {
    gulp.run(prodTasks);

    return;
  }

  gulp.run(defaultTasks);
}

module.exports = runTask;

<commit_msg>fix assign options<commit_after>const glob = require('glob');
const gulp = require('gulp');
const env = require('./utils/env');

function loadTask(dir, callback) {
  const files = glob.sync(`${dir}/**/*.js`);
  files.forEach((file) => {
    const task = require(file); // eslint-disable-line
    callback(task);
  });
}

const options = {
  homePath: process.cwd(),
  srcDir: './src',
  cssDir: '/css',
  jsDir: '/js',
  imageDir: '/image',
  staticDir: '/static',
  distDir: './assets',
  componentsDir: '/components',
  env
};

const prodTasks = [];
const defaultTasks = [];

const tasksDir = './tasks';

loadTask(tasksDir, (task) => {
  const deps = task.deps || [];
  gulp.task(task.name, deps, task.bind(gulp, options));

  if (task.production !== false) {
    prodTasks.push(task.name);
  }

  if (task.development !== false) {
    defaultTasks.push(task.name);
  }
});

gulp.task('default', defaultTasks);
gulp.task('production', prodTasks);

function runTask(envName = 'development', opts = {}) {
  opts.env = env.getEnv(envName);

  Object.assign(options, opts);

  if (opts.env.isProduction) {
    gulp.run(prodTasks);

    return;
  }

  gulp.run(defaultTasks);
}

module.exports = runTask;

<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require('./webpack.config.js');

//copy html and css files
gulp.task('copy', ['clean'], function () {
  return gulp.src([
    'src/index.html',
    'src/**/*.html',
    'src/**/*.css'
  ])
    .pipe(gulp.dest('dist'));
});

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

// build javascript for deployment using webpack
gulp.task('build', ['clean'], function (callback) {
  //modify webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  );
  // run webpack
  webpack(myConfig, function (err, stats) {
    if (err) throw new gutil.PluginError("webpack:build", err);
    gutil.log("[build]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task('deploy', ['clean', 'copy', 'build']);

// modify some webpack config options
var myDevConfig = Object.create(webpackConfig);
myDevConfig.devtool = "sourcemap";
myDevConfig.debug = true;

// create a single instance of the compiler to allow caching
var devCompiler = webpack(myDevConfig);

gulp.task("build-dev", ['clean'], function (callback) {
  // run webpack
  devCompiler.run(function (err, stats) {
    if (err) throw new gutil.PluginError("build-dev", err);
    gutil.log("[build-dev]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task("dev", ["copy", "build-dev"])

//run webpack dev server
gulp.task("dev-server", function (callback) {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.devtool = "sourcemap";
  myConfig.debug = true;

  // Start a webpack-dev-server
  new WebpackDevServer(webpack(myConfig), {
    contentBase: 'src',
    // publicPath: "/" + myConfig.output.publicPath,
    stats: {
      colors: true
    }
  }).listen(8080, "localhost", function (err) {
    if (err) throw new gutil.PluginError("webpack-dev-server", err);
    gutil.log("[dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
  });
});

gulp.task('default', ['dev-server']);
<commit_msg>updated the port number of the dev-server gulp task<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var webpackConfig = require('./webpack.config.js');

//copy html and css files
gulp.task('copy', ['clean'], function () {
  return gulp.src([
    'src/index.html',
    'src/**/*.html',
    'src/**/*.css'
  ])
    .pipe(gulp.dest('dist'));
});

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

// build javascript for deployment using webpack
gulp.task('build', ['clean'], function (callback) {
  //modify webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        "NODE_ENV": JSON.stringify("production")
      }
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  );
  // run webpack
  webpack(myConfig, function (err, stats) {
    if (err) throw new gutil.PluginError("webpack:build", err);
    gutil.log("[build]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task('deploy', ['clean', 'copy', 'build']);

// modify some webpack config options
var myDevConfig = Object.create(webpackConfig);
myDevConfig.devtool = "sourcemap";
myDevConfig.debug = true;

// create a single instance of the compiler to allow caching
var devCompiler = webpack(myDevConfig);

gulp.task("build-dev", ['clean'], function (callback) {
  // run webpack
  devCompiler.run(function (err, stats) {
    if (err) throw new gutil.PluginError("build-dev", err);
    gutil.log("[build-dev]", stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task("dev", ["copy", "build-dev"])

//run webpack dev server
gulp.task("dev-server", function (callback) {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.devtool = "sourcemap";
  myConfig.debug = true;

  // Start a webpack-dev-server
  new WebpackDevServer(webpack(myConfig), {
    contentBase: 'src',
    // publicPath: "/" + myConfig.output.publicPath,
    stats: {
      colors: true
    }
  }).listen(3000, "localhost", function (err) {
    if (err) throw new gutil.PluginError("webpack-dev-server", err);
    gutil.log("[dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
  });
});

gulp.task('default', ['dev-server']);
<|endoftext|>


<commit_before>'use strict';

var beep = require( 'beepbeep' ),
	browserify = require( 'browserify' ),
	concat = require( 'gulp-concat' ),
	del = require( 'del' ),
	deploy = require( 'gulp-gh-pages' ),
	es = require( 'event-stream' ),
	gulp = require( 'gulp' ),
	gutil = require( 'gulp-util' ),
	jshint = require( 'gulp-jshint' ),
	mocha = require( 'gulp-mocha' ),
	react = require( 'gulp-react' ),
	reactify = require( 'reactify' ),
	rename = require( 'gulp-rename' ),
	runSequence = require( 'run-sequence' ),
	sass = require( 'gulp-sass' ),
	source = require( 'vinyl-source-stream' ),
	streamify = require( 'gulp-streamify' ),
	template = require( 'gulp-template' ),
	uglify = require( 'gulp-uglify' );

var config = {
	buildPath: './build',
	cssPath: './stylesheets/css',
	indexPath: './index.html',
	jsPath: './js',
	sassPath: './stylesheets/scss',
	testPath: './test/*',

	// Files in the root that need to be copied over to the root of the build directory
	// This excludes index.html which is handled separately due to its templating
	assets: [ './CNAME', './favicon.ico' ]
};

var jsExtension = gutil.env.production ? 'min.js' : 'js',
	bundleFileName = 'bundle.' + jsExtension;

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

gulp.task( 'watch', function() {
	gulp.watch( config.indexPath, [ 'index' ] );
	gulp.watch( config.sassPath + '/*', [ 'css' ] );
	gulp.watch( config.jsPath + '/**/*', [ 'js' ] );
	gulp.watch( config.testPath, [ 'test' ] );
} );

gulp.task( 'build', function( callback ) {
	runSequence( 'clean', [ 'jshint', 'js', 'css', 'assets', 'index', 'test' ], callback );
} );

// Run `gulp deploy --production` to deploy to Github Pages
gulp.task( 'deploy', [ 'build' ], function () {
	if ( ! gutil.env.production ) {
		throw new Error( 'gulp deploy must be run with the --production flag to ensure the JavaScript bundle is minified' );
	}

	return gulp.src( config.buildPath + '/**/*' )
		.pipe( deploy() )
		.on( 'error', function( error ){
			gutil.log( error.message );
		} );
} );

gulp.task( 'clean', function() {
	return del( config.buildPath );
} );

gulp.task( 'jshint', function () {
	return gulp.src( [ config.jsPath + '/**/*', './gulpfile.js' ] )
		.pipe( react() )
		.pipe( jshint() )
		.pipe( jshint.reporter( 'default' ) );
} );

gulp.task( 'js', function( cb ) {
	var mainPath = config.jsPath + '/main.js';

	return browserify({
		entries: mainPath,
		extensions: [ '.jsx' ]
	} )
		.transform( reactify )
		.bundle()
		.on( 'error', function( error ) {
			beep();
			gutil.log( error.message );
			cb( error );
		} )
		.pipe( source( mainPath ) )
		.pipe( gutil.env.production ? streamify( uglify() ) : gutil.noop() )
		.pipe( rename( bundleFileName ) )
		.pipe( gulp.dest( config.buildPath + '/js' ) );
} );

gulp.task( 'css', function () {
	var cssFiles = gulp.src( config.cssPath + '/*.css' ),
		sassFiles = gulp.src( config.sassPath + '/*.scss' ).pipe( sass( { style: 'compressed' } ) );

	return es.concat( cssFiles, sassFiles )
		.pipe( concat( 'style.css' ) )
		.pipe( gulp.dest( config.buildPath + '/stylesheets' ) );
} );

gulp.task( 'assets', function() {
	return gulp.src( config.assets ).
		pipe( gulp.dest( config.buildPath ) );
} );

gulp.task( 'index', function() {
	return gulp.src( config.indexPath )
		.pipe( template( {
			bundleFileName: bundleFileName
		} ) )
		.pipe( gulp.dest( config.buildPath ) );
} );

gulp.task( 'test', function () {
	return gulp.src( config.testPath, { read: false } )
		.pipe( mocha( { reporter: 'dot' } ) )
		.once('error', function () {
			beep();
		} );
});
<commit_msg>Update spacing<commit_after>'use strict';

var beep = require( 'beepbeep' ),
	browserify = require( 'browserify' ),
	concat = require( 'gulp-concat' ),
	del = require( 'del' ),
	deploy = require( 'gulp-gh-pages' ),
	es = require( 'event-stream' ),
	gulp = require( 'gulp' ),
	gutil = require( 'gulp-util' ),
	jshint = require( 'gulp-jshint' ),
	mocha = require( 'gulp-mocha' ),
	react = require( 'gulp-react' ),
	reactify = require( 'reactify' ),
	rename = require( 'gulp-rename' ),
	runSequence = require( 'run-sequence' ),
	sass = require( 'gulp-sass' ),
	source = require( 'vinyl-source-stream' ),
	streamify = require( 'gulp-streamify' ),
	template = require( 'gulp-template' ),
	uglify = require( 'gulp-uglify' );

var config = {
	buildPath: './build',
	cssPath: './stylesheets/css',
	indexPath: './index.html',
	jsPath: './js',
	sassPath: './stylesheets/scss',
	testPath: './test/*',

	// Files in the root that need to be copied over to the root of the build directory
	// This excludes index.html which is handled separately due to its templating
	assets: [ './CNAME', './favicon.ico' ]
};

var jsExtension = gutil.env.production ? 'min.js' : 'js',
	bundleFileName = 'bundle.' + jsExtension;

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

gulp.task( 'watch', function() {
	gulp.watch( config.indexPath, [ 'index' ] );
	gulp.watch( config.sassPath + '/*', [ 'css' ] );
	gulp.watch( config.jsPath + '/**/*', [ 'js' ] );
	gulp.watch( config.testPath, [ 'test' ] );
} );

gulp.task( 'build', function( callback ) {
	runSequence( 'clean', [ 'jshint', 'js', 'css', 'assets', 'index', 'test' ], callback );
} );

// Run `gulp deploy --production` to deploy to Github Pages
gulp.task( 'deploy', [ 'build' ], function () {
	if ( ! gutil.env.production ) {
		throw new Error( 'gulp deploy must be run with the --production flag to ensure the JavaScript bundle is minified' );
	}

	return gulp.src( config.buildPath + '/**/*' )
		.pipe( deploy() )
		.on( 'error', function( error ){
			gutil.log( error.message );
		} );
} );

gulp.task( 'clean', function() {
	return del( config.buildPath );
} );

gulp.task( 'jshint', function () {
	return gulp.src( [ config.jsPath + '/**/*', './gulpfile.js' ] )
		.pipe( react() )
		.pipe( jshint() )
		.pipe( jshint.reporter( 'default' ) );
} );

gulp.task( 'js', function( cb ) {
	var mainPath = config.jsPath + '/main.js';

	return browserify( {
		entries: mainPath,
		extensions: [ '.jsx' ]
	} )
		.transform( reactify )
		.bundle()
		.on( 'error', function( error ) {
			beep();
			gutil.log( error.message );
			cb( error );
		} )
		.pipe( source( mainPath ) )
		.pipe( gutil.env.production ? streamify( uglify() ) : gutil.noop() )
		.pipe( rename( bundleFileName ) )
		.pipe( gulp.dest( config.buildPath + '/js' ) );
} );

gulp.task( 'css', function () {
	var cssFiles = gulp.src( config.cssPath + '/*.css' ),
		sassFiles = gulp.src( config.sassPath + '/*.scss' ).pipe( sass( { style: 'compressed' } ) );

	return es.concat( cssFiles, sassFiles )
		.pipe( concat( 'style.css' ) )
		.pipe( gulp.dest( config.buildPath + '/stylesheets' ) );
} );

gulp.task( 'assets', function() {
	return gulp.src( config.assets ).
		pipe( gulp.dest( config.buildPath ) );
} );

gulp.task( 'index', function() {
	return gulp.src( config.indexPath )
		.pipe( template( {
			bundleFileName: bundleFileName
		} ) )
		.pipe( gulp.dest( config.buildPath ) );
} );

gulp.task( 'test', function () {
	return gulp.src( config.testPath, { read: false } )
		.pipe( mocha( { reporter: 'dot' } ) )
		.once('error', function () {
			beep();
		} );
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('backend/**/*.js')
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('backend/**/*.spec.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<commit_msg>making sure that if the test step fails the stacktrace with the error is shown<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('backend/**/*.js')
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('backend/**/*.spec.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
      cb(mochaErr);
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('coveralls', ['test'], function () {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe(coveralls());
});

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test', 'coveralls']);
<|endoftext|>


<commit_before>import { getColorForProperties as poiColorizer } from "../utils/stadtplanHelper";
import "url-search-params-polyfill";

export const getColorForProperties = (properties) => {
  let searchParams = new URLSearchParams(window.location.href);
  let openForPublic= searchParams.get("openForPublic")||"147DA3";
  let closedForPublic=searchParams.get("closedForPublic")||"52A6C4"

  if (properties.more.zugang === "öffentlich" && properties.more.betreiber === "Verein") {
    return "#"+openForPublic;
  } else if (properties.more.zugang === "nicht öffentlich") {
    return "#"+closedForPublic;
  } else {
    return poiColorizer(properties);
  }
};

<commit_msg>:lipstick: wo #32: new default colors for the map icons<commit_after>import { getColorForProperties as poiColorizer } from "../utils/stadtplanHelper";
import "url-search-params-polyfill";

export const getColorForProperties = (properties) => {
  let searchParams = new URLSearchParams(window.location.href);
  let openForPublic= searchParams.get("openForPublic")||"107FC9";
  let closedForPublic=searchParams.get("closedForPublic")||"4AC1D1"

  if (properties.more.zugang === "öffentlich" && properties.more.betreiber === "Verein") {
    return "#"+openForPublic;
  } else if (properties.more.zugang === "nicht öffentlich") {
    return "#"+closedForPublic;
  } else {
    return poiColorizer(properties);
  }
};

<|endoftext|>


<commit_before>/**
 * page-formats module
 * @module utils/page-formats
 * @type array<Format>
 * @description When required, this module exports an array of formats supported by the application
 */

'use strict';

/**
 * Define a page format
 * @constructor
 * @param {string} label The format's label
 * @param {number} long The format's long dimension in milimeters
 * @param {number} short The format's short dimension in milimeters
 */
function Format(label,long,short){
  this.label = label;
  this.long = long;
  this.short = short;
}

/**
 * Register the only formats supported now by the application
 * @var supportedFormats
 * @global
 *
 * @todo this should be a plugin parameter defined in the setup function of the editor
 */
var supportedFormats = {
  'A4': {
    long: '297',
    short: '210'
  }
};

/**
 * @exports each supported format as instances of Format
 */
$.each(supportedFormats,function(label,format){
  exports[label] = new Format(label, format.long, format.short);
});
<commit_msg>clean code<commit_after>/**
 * page-formats module
 * @module utils/page-formats
 * @type array<Format>
 * @description When required, this module exports an array of formats supported by the application
 */

'use strict';

/**
 * Define a page format
 * @constructor
 * @param {string} label The format's label
 * @param {number} long The format's long dimension in milimeters
 * @param {number} short The format's short dimension in milimeters
 */
function Format(label,long,short){
  this.label = label;
  this.long = long;
  this.short = short;
}

/**
 * Register the only formats supported now by the application
 * @var supportedFormats
 * @global
 *
 * @todo this should be a plugin parameter defined in the setup function of the editor
 */
var supportedFormats = {
  'A4': {
    long: '297',
    short: '210'
  }
};

var exp = [];
$.each(supportedFormats,function(label,format){
  exp[label] = new Format(label, format.long, format.short);
});

module.exports = exp;
<|endoftext|>


<commit_before>'use strict';

var path      = require('path');
var gulp      = require('gulp');
var concat    = require('gulp-concat');
var minifyCSS = require('gulp-minify-css');
var compass   = require('gulp-compass');
var clean     = require('gulp-clean');
var uglify    = require('gulp-uglify');
var express   = require('express');
var swig      = require('swig');
var tempWrite = require('temp-write');
var generator = require('./generator');

// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------

var BASE_URL    = process.env.BASE_URL ? process.env.BASE_URL : '/';
var SERVER_PORT = 3000;
var MODERNIZR   = 'vendor/foundation/js/vendor/modernizr.js';
var JAVASCRIPTS = [
  'vendor/jquery/dist/jquery.min.js',
  'vendor/foundation/js/foundation.min.js',
  'vendor/underscore/underscore.js',
  'vendor/backbone/backbone.js',
  'vendor/handlebars/handlebars.min.js',
  'vendor/jspdf/dist/jspdf.min.js',
  'vendor/markdown/lib/markdown.js',
  'src/app.js'
];
var STYLESHEETS = [
  'vendor/font-awesome/css/font-awesome.min.css',
  'build/css/app.css'
];
var FONTS = [
  'vendor/font-awesome/fonts/**'
];

// -----------------------------------------------------------------------------
// Templates
// -----------------------------------------------------------------------------

swig.setDefaults({cache: false});

// Custom Swig instance (to avoid conflicts with Handlebars delimiters).
var customSwig = new swig.Swig({
  varControls: ['<%=', '%>'],
  tagControls: ['<%', '%>'],
  cmtControls: ['<#', '#>']
});

// Template context
var context = {
  env       : 'production',
  modernizr : MODERNIZR,
  scripts   : JAVASCRIPTS,
  styles    : STYLESHEETS,
  baseurl   : BASE_URL
};

// -----------------------------------------------------------------------------
// Express Server (defaults)
// -----------------------------------------------------------------------------

var server = express();
server.use(express.compress());
server.use(express.json());
server.use(express.urlencoded());
server.set('view cache', false);

// -----------------------------------------------------------------------------
// Compilation Tasks
// -----------------------------------------------------------------------------

gulp.task('compile:data', function() {
  var data = generator.buildData();
  var json = JSON.stringify(data, null, 2);
  var file = tempWrite.sync(json, 'data.json');
  gulp.src(file)
    .pipe(gulp.dest('build/data'));
});

gulp.task('compile:index', function() {
  var compiled = customSwig.compileFile(path.join(__dirname, 'views', 'index.html'));
  var tpl = compiled(context);
  var file = tempWrite.sync(tpl, 'index.html');
  return gulp.src(file)
    .pipe(gulp.dest('build/html'));
});

gulp.task('compile:stylesheets', function() {
  gulp.src('./src/*.scss')
    .pipe(compass({
      project     : __dirname,
      css         : 'build/css',
      sass        : 'src',
      image       : 'src/images',
      import_path : ['vendor/foundation/scss']
    }));
});

gulp.task('compile', [
  'compile:data',
  'compile:index',
  'compile:stylesheets'
]);

// -----------------------------------------------------------------------------
// Build "public" directory
// -----------------------------------------------------------------------------

gulp.task('public:data', ['compile:data'], function() {
  gulp.src('build/data/data.json')
    .pipe(gulp.dest('public'));
});

gulp.task('public:index', ['compile:index'], function() {
  gulp.src('build/html/index.html')
    .pipe(gulp.dest('public'));
});

gulp.task('public:fonts', function() {
  gulp.src(FONTS)
    .pipe(gulp.dest('public/fonts'));
});

gulp.task('public:javascripts', function() {
  gulp.src(MODERNIZR)
    .pipe(gulp.dest('public/js'));
  gulp.src(JAVASCRIPTS)
    .pipe(concat('scripts.js'))
    .pipe(uglify())
    .pipe(gulp.dest('public/js'));
});

gulp.task('public:stylesheets', ['compile:stylesheets'], function() {
  gulp.src(STYLESHEETS)
    .pipe(concat('styles.css'))
    .pipe(minifyCSS())
    .pipe(gulp.dest('public/css'));
});

gulp.task('public', [
  'public:data',
  'public:index',
  'public:fonts',
  'public:javascripts',
  'public:stylesheets'
]);

// -----------------------------------------------------------------------------
// Clean Tasks
// -----------------------------------------------------------------------------

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

gulp.task('clean:public', function() {
  return gulp.src('public')
    .pipe(clean({force: true}));
});

gulp.task('clean', [
  'clean:build',
  'clean:public'
]);

// -----------------------------------------------------------------------------
// Watch
// -----------------------------------------------------------------------------

gulp.task('watch', function() {
  gulp.watch(['src/**', 'data/**', 'views/**'], ['compile']);
});

// -----------------------------------------------------------------------------
// Servers
// -----------------------------------------------------------------------------

gulp.task('server:development', function() {
  context.env = 'development';
  server.engine('html', customSwig.renderFile);
  server.set('view engine', 'html');
  server.set('views', path.join(__dirname, 'views'));
  server.use(express.static(__dirname));
  server.use(express.static(path.join(__dirname, 'build', 'data')));
  server.get('*', function(req, res) { res.render('index', context); });
  server.listen(SERVER_PORT);
  console.log('Express server listen on port ' + SERVER_PORT + '...');
});

gulp.task('server:test', function() {
  context.env = 'development';
  server.use(express.static(__dirname));
  server.use(express.static(path.join(__dirname, 'build')));
  server.get('*', function(req, res) { res.sendfile('test/index.html'); });
  server.listen(SERVER_PORT);
  console.log('Express server listen on port ' + SERVER_PORT + '...');
});

gulp.task('server:production', function() {
  server.use(express.static(path.join(__dirname, 'public')));
  //server.get('*', function(req, res) { res.sendfile(path.join(__dirname, 'public', 'index.html')); });
  console.log('Express server listen on port ' + SERVER_PORT + '...');
  server.listen(SERVER_PORT);
});

// -----------------------------------------------------------------------------
// Top Level Tasks
// -----------------------------------------------------------------------------

gulp.task('build', [
  'clean:build',
  'compile'
]);

gulp.task('generate', [
  'clean:build',
  'clean:public',
  'public'
]);

gulp.task('serve', [
  'compile',
  'server:development',
  'watch'
]);

gulp.task('serve:test', [
  'compile:data',
  'server:test'
]);

gulp.task('serve:production', [
  'clean:build',
  'clean:public',
  'public',
  'server:production'
]);
<commit_msg>Improve gulpfile tasks.<commit_after>'use strict';

var path      = require('path');
var gulp      = require('gulp');
var concat    = require('gulp-concat');
var minifyCSS = require('gulp-minify-css');
var compass   = require('gulp-compass');
var clean     = require('gulp-clean');
var uglify    = require('gulp-uglify');
var express   = require('express');
var swig      = require('swig');
var tempWrite = require('temp-write');
var generator = require('./generator');

// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------

var BASE_URL    = process.env.BASE_URL ? process.env.BASE_URL : '/';
var SERVER_PORT = 3000;
var MODERNIZR   = 'vendor/foundation/js/vendor/modernizr.js';
var JAVASCRIPTS = [
  'vendor/jquery/dist/jquery.min.js',
  'vendor/foundation/js/foundation.min.js',
  'vendor/underscore/underscore.js',
  'vendor/backbone/backbone.js',
  'vendor/handlebars/handlebars.min.js',
  'vendor/jspdf/dist/jspdf.min.js',
  'vendor/markdown/lib/markdown.js',
  'src/app.js'
];
var STYLESHEETS = [
  'vendor/font-awesome/css/font-awesome.min.css',
  'build/css/app.css'
];
var FONTS = [
  'vendor/font-awesome/fonts/**'
];

// -----------------------------------------------------------------------------
// Templates
// -----------------------------------------------------------------------------

swig.setDefaults({cache: false});

// Custom Swig instance (to avoid conflicts with Handlebars delimiters).
var customSwig = new swig.Swig({
  varControls: ['<%=', '%>'],
  tagControls: ['<%', '%>'],
  cmtControls: ['<#', '#>']
});

// Template context
var context = {
  env       : 'production',
  modernizr : MODERNIZR,
  scripts   : JAVASCRIPTS,
  styles    : STYLESHEETS,
  baseurl   : BASE_URL
};

// -----------------------------------------------------------------------------
// Express Server (defaults)
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Compilation Tasks
// -----------------------------------------------------------------------------

gulp.task('compile:data', function() {
  var data = generator.buildData();
  var json = JSON.stringify(data, null, 2);
  var file = tempWrite.sync(json, 'data.json');
  return gulp.src(file)
    .pipe(gulp.dest('build/data'));
});

gulp.task('compile:index', function() {
  var compiled = customSwig.compileFile(path.join(__dirname, 'views', 'index.html'));
  var tpl = compiled(context);
  var file = tempWrite.sync(tpl, 'index.html');
  return gulp.src(file)
    .pipe(gulp.dest('build/html'));
});

gulp.task('compile:stylesheets', function() {
  return gulp.src('./src/*.scss')
    .pipe(compass({
      project     : __dirname,
      css         : 'build/css',
      sass        : 'src',
      image       : 'src/images',
      import_path : ['vendor/foundation/scss']
    }));
});

gulp.task('compile', [
  'compile:data',
  'compile:index',
  'compile:stylesheets'
]);

// -----------------------------------------------------------------------------
// Build "public" directory
// -----------------------------------------------------------------------------

gulp.task('public:data', function() {
  return gulp.src('build/data/data.json')
    .pipe(gulp.dest('public'));
});

gulp.task('public:index', function() {
  return gulp.src('build/html/index.html')
    .pipe(gulp.dest('public'));
});

gulp.task('public:fonts', function() {
  return gulp.src(FONTS)
    .pipe(gulp.dest('public/fonts'));
});

gulp.task('public:javascripts', function() {
  gulp.src(MODERNIZR)
    .pipe(gulp.dest('public/js'));
  gulp.src(JAVASCRIPTS)
    .pipe(concat('scripts.js'))
    .pipe(uglify())
    .pipe(gulp.dest('public/js'));
});

gulp.task('public:stylesheets', function() {
  return gulp.src(STYLESHEETS)
    .pipe(concat('styles.css'))
    .pipe(minifyCSS())
    .pipe(gulp.dest('public/css'));
});

gulp.task('public', [
  'public:data',
  'public:index',
  'public:fonts',
  'public:javascripts',
  'public:stylesheets'
]);

// -----------------------------------------------------------------------------
// Clean Tasks
// -----------------------------------------------------------------------------

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

gulp.task('clean:public', function() {
  return gulp.src('public')
    .pipe(clean({force: true}));
});

gulp.task('clean', ['clean:build', 'clean:public']);

// -----------------------------------------------------------------------------
// Watch
// -----------------------------------------------------------------------------

gulp.task('watch', function() {
  gulp.watch(['src/**', 'data/**', 'views/**', 'test/**'], ['compile']);
});

gulp.task('watch:production', function() {
  gulp.watch(['src/**', 'data/**', 'views/**'], ['compile', 'public']);
});

// -----------------------------------------------------------------------------
// Servers
// -----------------------------------------------------------------------------

function serve(env) {
  env = env || 'development';
  var server = express();
  server.use(express.compress());
  server.use(express.json());
  server.use(express.urlencoded());
  server.set('view cache', false);
  switch(env) {
    case 'development':
      context.env = 'development';
      server.engine('html', customSwig.renderFile);
      server.set('view engine', 'html');
      server.set('views', path.join(__dirname, 'views'));
      server.use(express.static(__dirname));
      server.use(express.static(path.join(__dirname, 'build', 'data')));
      server.get('*', function(req, res) { res.render('index', context); });
      server.listen(SERVER_PORT);
    break;
    case 'test':
      context.env = 'test';
      server.use(express.static(__dirname));
      server.use(express.static(path.join(__dirname, 'build', 'data')));
      server.use(express.static(path.join(__dirname, 'test')));
      server.listen(SERVER_PORT);
    break;
    case 'production':
      context.env = 'production';
      server.use(express.static(path.join(__dirname, 'public')));
      server.listen(SERVER_PORT);
    break;
  }
  console.log('Express server listen on port ' + SERVER_PORT + '...');
}

// -----------------------------------------------------------------------------
// Top Level Tasks
// -----------------------------------------------------------------------------

gulp.task('build', [
  'clean:build',
  'compile'
]);

gulp.task('generate', [
  'clean',
  'compile',
  'public'
]);

gulp.task('serve', [
  'clean',
  'compile',
  'watch'
], function() {
  serve('development');
});

gulp.task('serve:test', [
  'clean',
  'compile',
  'watch'
], function() {
  serve('test');
});

gulp.task('serve:production', [
  'clean',
  'compile',
  'public',
  'watch:production'
], function() {
  serve('production');
});
<|endoftext|>


<commit_before>import google from 'googleapis';
import googleAuth from 'google-auth-library'
import util from 'util';
const oAuth2 = require('googleapis').auth.OAuth2;

let helper = null;

const { GOOGLE_CLIEN_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CALLBACK_URL } = process.env;
const oauth2Client = new oAuth2(GOOGLE_CLIEN_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CALLBACK_URL);

const SheetsHelper = function(credentials) {
  oauth2Client.setCredentials(credentials);
  this.service = google.sheets({version: 'v4', auth: oauth2Client});
};

SheetsHelper.prototype.updateCredentials = function() {
  return new Promise((resolve, reject) => {
    oauth2Client.refreshAccessToken(function(err, tokens) {
      if (err) {
        reject(err);
      }
      const newCreds = {
        access_token: tokens.access_token,
        refresh_token: tokens.refresh_token,
      };
      oauth2Client.setCredentials(newCreds)
      resolve({ token: tokens.access_token, refreshToken });
    })
  })
}

const createTaskRow = (task, rowNumber) => {
  const { maximumMinutes, minimumMinutes, taskName } = task;
  return {
    startRow: rowNumber,
    startColumn: 0,
    rowData: [{
      values: [
        {
          userEnteredValue: {
            stringValue: taskName,
          },
        },
        {
          userEnteredValue: {
            numberValue: parseInt(minimumMinutes, 10),
          },
        },
        {
          userEnteredValue: {
            numberValue: parseInt(maximumMinutes, 10),
          }
        }
      ]}]
    };

}

SheetsHelper.prototype.createSpreadsheet = function(options, callback) {
  var self = this;
  const { tasks } = options;
  const tasksRows = [];
  tasks.forEach((t,i) => {
    tasksRows.push(createTaskRow(t, i));
  })
  var request = {
    resource: {
      properties: {
        title: 'title'
      },
      sheets: [
        {
          data: [
            {
              startRow: 0,
              startColumn: 0,
              rowData: [
                {
                  values: [
                    {
                      userEnteredValue: {
                        numberValue: 5,
                      }
                    },
                    {
                      userEnteredValue: {
                        numberValue: 15,
                      }
                    }
                  ],
                }
              ],
            }
          ],
          properties: {
            title: 'Data',
            gridProperties: {
              columnCount: 6,
              frozenRowCount: 1
            }
          }
        },
      ]
    }
  };
  self.service.spreadsheets.create(request, function(err, spreadsheet) {
    if (err) {
      return callback(err);
    }
    // need to save spreadsheet id into db
    return callback(null, spreadsheet);
  });
};

const getSpreadsheetHelper = (accessToken) => {
  if (!helper) {
    helper = new SheetsHelper(accessToken);
  }
  return helper;
}

export default getSpreadsheetHelper;
<commit_msg>add tasks title<commit_after>import google from 'googleapis';
import googleAuth from 'google-auth-library'
import util from 'util';
const oAuth2 = require('googleapis').auth.OAuth2;

let helper = null;

const { GOOGLE_CLIEN_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CALLBACK_URL } = process.env;
const oauth2Client = new oAuth2(GOOGLE_CLIEN_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CALLBACK_URL);

const SheetsHelper = function(credentials) {
  oauth2Client.setCredentials(credentials);
  this.service = google.sheets({version: 'v4', auth: oauth2Client});
};

SheetsHelper.prototype.updateCredentials = function() {
  return new Promise((resolve, reject) => {
    oauth2Client.refreshAccessToken(function(err, tokens) {
      if (err) {
        reject(err);
      }
      const newCreds = {
        access_token: tokens.access_token,
        refresh_token: tokens.refresh_token,
      };
      oauth2Client.setCredentials(newCreds)
      resolve({ token: tokens.access_token, refreshToken });
    })
  })
}

const createTaskCell = (value) => {
  if (/[A-Za-z]+/g.test(value)) {
   return { stringValue: value }
  }
  return { numberValue: parseInt(value, 10) };
}

const createTaskRow = (task, rowNumber) => {
  const { maximumMinutes, minimumMinutes, taskName } = task;
  return {
    startRow: rowNumber,
    startColumn: 0,
    rowData: [{
      values: [
        { userEnteredValue: createTaskCell(taskName) },
        { userEnteredValue: createTaskCell(minimumMinutes) },
        { userEnteredValue: createTaskCell(maximumMinutes) }
      ]
    }]
  };
}

SheetsHelper.prototype.createSpreadsheet = function(options, callback) {
  var self = this;
  const { tasks } = options;
  const tasksRows = [ createTaskRow({ taskName: 'task', maximumMinutes: 'maximum minutes', minimumMinutes: 'minimum minutes' }, 0)];
  tasks.forEach((t,i) => {
    tasksRows.push(createTaskRow(t, i + 1));
  })
  var request = {
    resource: {
      properties: {
        title: 'title'
      },
      sheets: [
        {
          data: tasksRows,
          properties: {
            title: 'Data',
            gridProperties: {
              columnCount: 6,
              frozenRowCount: 1
            }
          }
        },
      ]
    }
  };
  self.service.spreadsheets.create(request, function(err, spreadsheet) {
    if (err) {
      return callback(err);
    }
    // need to save spreadsheet id into db
    return callback(null, spreadsheet);
  });
};

const getSpreadsheetHelper = (accessToken) => {
  if (!helper) {
    helper = new SheetsHelper(accessToken);
  }
  return helper;
}

export default getSpreadsheetHelper;
<|endoftext|>


<commit_before>const moduleError = /Error: Cannot find module '([a-zA-Z0-9+_-]+)'/g;

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('child_process').spawn;

const isDev = process.argv[2] === '--dev';

let bot;

const paths = {
    srcFiles: 'src/**/!(_)*.js',
    configFiles: 'data/configs/config.json',
    gulpFile: 'gulpfile.js'
};

function killBot() {
    if (bot) bot.kill();
}

gulp.task('kill', () => {
    killBot();
});

gulp.task('lint', () =>
    gulp.src([
        paths.srcFiles,
        paths.gulpFile
    ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
);

const mainTasks = ['kill'];
if (isDev) {
    mainTasks.push('lint');
}

gulp.task('main', mainTasks, () => {
    bot = spawn('node', ['src/bot.js'], { 'stdio': ['inherit', 'inherit', 'pipe'] });

    bot.stderr.on('data', data => {
        process.stderr.write(data);
        if (moduleError.test(data.toString())) {
            console.error(`
#########################################################################################################################
 Node has failed to load a module! If you just updated, you may need to run \'yarn\' again to install/update dependencies.
 'yarn' will attempt to run now and install the dependencies for you.
#########################################################################################################################
`);
            spawn('yarn', ['--force'], { 'stdio': 'inherit' }).on('close', code => {
                if (code === 0) {
                    console.log(`
New modules have been installed. The bot will now restart.
                `);
                    gulp.start('main');
                }
            });
        }
    });

    bot.on('close', code => {
        if (code === null) {
            // Killed by killBot()
            return;
        }

        if (code === 42) {
            // Restart
            console.error('Restart code detected.');
            gulp.start('main');
        } else if (code === 666) {
            // Full process stop
            console.log('Process exit code detected.');
            process.exit(1);
        } else {
            // Wait for changes
            console.log('Bot has exited. Waiting for changes...');
        }
    });
});

gulp.task('watch', () => {
    gulp.watch([
        paths.srcFiles,
        paths.configFiles
    ], ['main']);
});

const defaultTasks = ['main'];
if (isDev) {
    defaultTasks.push('watch');
}
gulp.task('default', defaultTasks);

process.on('exit', () => {
    killBot();
});
<commit_msg>Re-enable watch even on non dev<commit_after>const moduleError = /Error: Cannot find module '([a-zA-Z0-9+_-]+)'/g;

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('child_process').spawn;

const isDev = process.argv[2] === '--dev';

let bot;

const paths = {
    srcFiles: 'src/**/!(_)*.js',
    configFiles: 'data/configs/config.json',
    gulpFile: 'gulpfile.js'
};

function killBot() {
    if (bot) bot.kill();
}

gulp.task('kill', () => {
    killBot();
});

gulp.task('lint', () =>
    gulp.src([
        paths.srcFiles,
        paths.gulpFile
    ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
);

const mainTasks = ['kill'];
if (isDev) {
    mainTasks.push('lint');
}

gulp.task('main', mainTasks, () => {
    bot = spawn('node', ['src/bot.js'], { 'stdio': ['inherit', 'inherit', 'pipe'] });

    bot.stderr.on('data', data => {
        process.stderr.write(data);
        if (moduleError.test(data.toString())) {
            console.error(`
#########################################################################################################################
 Node has failed to load a module! If you just updated, you may need to run \'yarn\' again to install/update dependencies.
 'yarn' will attempt to run now and install the dependencies for you.
#########################################################################################################################
`);
            spawn('yarn', ['--force'], { 'stdio': 'inherit' }).on('close', code => {
                if (code === 0) {
                    console.log(`
New modules have been installed. The bot will now restart.
                `);
                    gulp.start('main');
                }
            });
        }
    });

    bot.on('close', code => {
        if (code === null) {
            // Killed by killBot()
            return;
        }

        if (code === 42) {
            // Restart
            console.error('Restart code detected.');
            gulp.start('main');
        } else if (code === 666) {
            // Full process stop
            console.log('Process exit code detected.');
            process.exit(1);
        } else {
            // Wait for changes
            console.log('Bot has exited. Waiting for changes...');
        }
    });
});

gulp.task('watch', () => {
    gulp.watch([
        paths.srcFiles,
        paths.configFiles
    ], ['main']);
});

gulp.task('default', ['main', 'watch']);

process.on('exit', () => {
    killBot();
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    gls = require('gulp-live-server'),
    uglify = require('gulp-uglifyjs'),
    rename = require("gulp-rename");
//___________________________________________________

gulp.task('default', ['lint', 'uglify']);
gulp.task('lint', ['jslint']);

//___________________________________________________
// npm i --save-dev gulp-jshint jshint-stylish
var jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish');

gulp.task('jslint', function() {
    gulp.src('./index.js')
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});
//___________________________________________________
gulp.task('serve-test', function() {
    var server = gls.static("./test", 8287);
    server.start();
    //live reload changed resource(s)
    gulp.watch(['index.js', 'test/**/*.js'], server.notify);
});
//___________________________________________________
gulp.task('uglify', function() {
    gulp.src('index.js')
        .pipe(uglify())
        .pipe(rename('decompose.min.js'))
        .pipe(gulp.dest('dist'))
});<commit_msg>udpate docs<commit_after>var gulp = require('gulp'),
    gls = require('gulp-live-server'),
    uglify = require('gulp-uglifyjs'),
    rename = require("gulp-rename");
//___________________________________________________

gulp.task('default', ['lint', 'uglify']);
gulp.task('lint', ['jslint']);

//___________________________________________________
// npm i --save-dev gulp-jshint jshint-stylish
var jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish');

gulp.task('jslint', function() {
    gulp.src('./index.js')
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});
//___________________________________________________
gulp.task('serve-test', function() {
    var server = gls.static(".", 8287);
    server.start();
    //live reload changed resource(s)
    gulp.watch(['index.js', 'test/**/*.js'], server.notify);
});
//___________________________________________________
gulp.task('uglify', function() {
    gulp.src('index.js')
        .pipe(uglify())
        .pipe(rename('decompose.min.js'))
        .pipe(gulp.dest('dist'))
});
<|endoftext|>


<commit_before>'use strict';

// =============================
// ------ Import Plugins -------
// =============================

var gulp     = require('gulp');
var bower    = require('gulp-bower');
var watch    = require('gulp-watch');
var postcss  = require('gulp-postcss');
var sass     = require('gulp-sass');
var rigger   = require('gulp-rigger');
var cssmin   = require('gulp-clean-css');
var filter   = require('gulp-filter');
var csscomb  = require('gulp-csscomb');
var zip      = require('gulp-zip');
var plumber  = require('gulp-plumber');
var util     = require('gulp-util');
var posthtml = require('gulp-posthtml');
var mmq      = require('gulp-merge-media-queries');

var autoprefixer = require('autoprefixer');
var browserSync  = require('browser-sync').create();
var attrSorter   = require('posthtml-attrs-sorter');
var rimraf       = require('rimraf');
var reload       = browserSync.reload;

// =============================
// -------- Functions ----------
// =============================

// Error handler for gulp-plumber
function errorHandler(err) {
    util.log([ (err.name + ' in ' + err.plugin).bold.red, '', err.message, '' ].join('\n'));

    this.emit('end');
}

function correctNumber(number) {
    return number < 10 ? '0' + number : number;
}

// Return timestamp
function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = correctNumber(now.getMonth() + 1);
    var day = correctNumber(now.getDate());
    var hours = correctNumber(now.getHours());
    var minutes = correctNumber(now.getMinutes());
    return year + '-' + month + '-' + day + '-' + hours + minutes;
};

// =============================
// ------- Add var path --------
// =============================

var path = {

    build: {
        html:   'web/',
        js:     'web/js/',
        css:    'web/css/',
        img:    'web/images/',
        fonts:  'web/fonts/',
        libs:   'web/libs/'
    },

    src: {
        html:   'src/*.html',                 // Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js:     'src/js/common.js',
        style:  'src/sass/style.scss',
        media:  'src/sass/media.scss',
        img:    'src/images/**/*.*',           // Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts:  'src/fonts/**/*.*',
        libs:   './bower_components/'
    },

    watch: {
        html:   'src/**/*.html',
        js:     'src/js/**/*.js',
        style:  'src/sass/**/*.scss',
        img:    'src/images/**/*.*',
        fonts:  'src/fonts/**/*.*'
    },

    clean:      './web'
};

// =============================
// ---- Add plugins options ----
// =============================

var option = {

    browserSync: {
        server: './web',
        tunnel: false,
        open: false,
        host: 'localhost',
        port: 9000,
        logPrefix: "lucas"
    },

    plumber: {
        errorHandler: errorHandler
    },

    sass: {
        outputStyle: 'expanded'
    },

    postcss: [
        autoprefixer({
            cascade: true
        }),
    ],

    posthtml: {
        plugins: [
            attrSorter({
                order: [
                    'class',
                    'id',
                    'name',
                    'data',
                    'ng',
                    'src',
                    'for',
                    'type',
                    'href',
                    'values',
                    'title',
                    'alt',
                    'role',
                    'aria',
                    'tabindex'
                ]
            })
        ],
        options: {}
    },

    mmq: {
        log: true,
        use_external: true
    },

    csscomb: 'csscomb.json',

}

// =============================
// --------- Sub tasks ---------
// =============================

// Удаление скомпилированных файлов
gulp.task('clean', function (cb) {
    return rimraf(path.clean, cb);
});

// Запуск сервера с livereload
gulp.task('serve', function () {
    return browserSync.init(option.browserSync);
});

// Загрузка плагинов из Bower
gulp.task('bower', function() {
    return bower();
});

// =============================
// ------- Build tasks ---------
// =============================

gulp.task('build:html', function () {
    gulp.src(path.src.html)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(posthtml(option.posthtml.plugins, option.posthtml.options))
        .pipe(gulp.dest(path.build.html))
        .pipe(reload({stream: true}));
});

gulp.task('build:js', function () {
    gulp.src(path.src.js)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.js))
        .pipe(reload({stream: true}));
});

gulp.task('build:css', function () {
    // style.css
    gulp.src(path.src.style)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(mmq(option.mmq))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));
});

gulp.task('build:img', function () {
    gulp.src(path.src.img)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.img))
        .pipe(reload({stream: true}));
});

gulp.task('build:fonts', function() {
    gulp.src(path.src.fonts)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.fonts))
});

gulp.task('build:zip', function() {
    var datetime = '-' + getDateTime();
    var zipName = 'web' + datetime + '.zip';

    gulp.src('web/**/*.*')
        .pipe(zip(zipName))
        .pipe(gulp.dest('dist'));
});

// =============================
// ------- Watch task ----------
// =============================

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        gulp.start('build:html');
    });

    watch([path.watch.style], function(event, cb) {
        gulp.start('build:css');
    });

    watch([path.watch.js], function(event, cb) {
        gulp.start('build:js');
    });

    watch([path.watch.img], function(event, cb) {
        gulp.start('build:img');
    });

    watch([path.watch.fonts], function(event, cb) {
        gulp.start('build:fonts');
    });
});

// =============================
// -------- Main task ----------
// =============================

gulp.task('vendor', [
    'bower',
    'filter'
]);

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

gulp.task('build', [
    'build:html',
    'build:css',
    'build:js',
    'build:img',
    'build:fonts'
]);

gulp.task('dev', [
    'build',
    'watch',
    'serve'
]);

// Default task
gulp.task('default', ['dev']);

// TODO: Разобрать таск и переписать
// Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
    // Настраиваем фильтры для файлов
    const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
    const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

    // Для нормальных плагинов отработает этот кусок кода
    const stream = gulp.src([
        'bower_components/**/*.min.*',
        'bower_components/**/fonts/*',
        'bower_components/**/*.css',
        '!bower_components/**/*.map'
    ])

    // Фильтруем содержимое на наличие js и css
    .pipe(jsFilter)
    .pipe(cssFilter)
    // run them through a plugin
    .pipe(gulp.dest('dist'));

    // Вываливаем в билд
    jsFilter.restore.pipe(gulp.dest(path.build.libs));

    return stream;
});
<commit_msg>add return for task<commit_after>'use strict';

// =============================
// ------ Import Plugins -------
// =============================

var gulp     = require('gulp');
var bower    = require('gulp-bower');
var watch    = require('gulp-watch');
var postcss  = require('gulp-postcss');
var sass     = require('gulp-sass');
var rigger   = require('gulp-rigger');
var cssmin   = require('gulp-clean-css');
var filter   = require('gulp-filter');
var csscomb  = require('gulp-csscomb');
var zip      = require('gulp-zip');
var plumber  = require('gulp-plumber');
var util     = require('gulp-util');
var posthtml = require('gulp-posthtml');
var mmq      = require('gulp-merge-media-queries');

var autoprefixer = require('autoprefixer');
var browserSync  = require('browser-sync').create();
var attrSorter   = require('posthtml-attrs-sorter');
var rimraf       = require('rimraf');
var del          = require('del');
var reload       = browserSync.reload;

// =============================
// -------- Functions ----------
// =============================

// Error handler for gulp-plumber
function errorHandler(err) {
    util.log([ (err.name + ' in ' + err.plugin).bold.red, '', err.message, '' ].join('\n'));

    this.emit('end');
}

function correctNumber(number) {
    return number < 10 ? '0' + number : number;
}

// Return timestamp
function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = correctNumber(now.getMonth() + 1);
    var day = correctNumber(now.getDate());
    var hours = correctNumber(now.getHours());
    var minutes = correctNumber(now.getMinutes());
    return year + '-' + month + '-' + day + '-' + hours + minutes;
};

// =============================
// ------- Add var path --------
// =============================

var path = {

    build: {
        html:   'web/',
        js:     'web/js/',
        css:    'web/css/',
        img:    'web/images/',
        fonts:  'web/fonts/',
        libs:   'web/libs/'
    },

    src: {
        html:   'src/*.html',                 // Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js:     'src/js/common.js',
        style:  'src/sass/style.scss',
        media:  'src/sass/media.scss',
        img:    'src/images/**/*.*',           // Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts:  'src/fonts/**/*.*',
        libs:   './bower_components/'
    },

    watch: {
        html:   'src/**/*.html',
        js:     'src/js/**/*.js',
        style:  'src/sass/**/*.scss',
        img:    'src/images/**/*.*',
        fonts:  'src/fonts/**/*.*'
    },

    clean:      './web'
};

// =============================
// ---- Add plugins options ----
// =============================

var option = {

    browserSync: {
        server: './web',
        tunnel: false,
        open: false,
        host: 'localhost',
        port: 9000,
        logPrefix: "lucas"
    },

    plumber: {
        errorHandler: errorHandler
    },

    sass: {
        outputStyle: 'expanded'
    },

    postcss: [
        autoprefixer({
            cascade: true
        }),
    ],

    posthtml: {
        plugins: [
            attrSorter({
                order: [
                    'class',
                    'id',
                    'name',
                    'data',
                    'ng',
                    'src',
                    'for',
                    'type',
                    'href',
                    'values',
                    'title',
                    'alt',
                    'role',
                    'aria',
                    'tabindex'
                ]
            })
        ],
        options: {}
    },

    mmq: {
        log: true,
        use_external: true
    },

    csscomb: 'csscomb.json',

}

// =============================
// --------- Sub tasks ---------
// =============================

// Удаление скомпилированных файлов
gulp.task('clean', function (cb) {
    return del(path.clean, cb);
});

// Запуск сервера с livereload
gulp.task('serve', function () {
    return browserSync.init(option.browserSync);
});

// Загрузка плагинов из Bower
gulp.task('bower', function() {
    return bower();
});

// =============================
// ------- Build tasks ---------
// =============================

gulp.task('build:html', function () {
    return gulp.src(path.src.html)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(posthtml(option.posthtml.plugins, option.posthtml.options))
        .pipe(gulp.dest(path.build.html))
        .pipe(reload({stream: true}));
});

gulp.task('build:js', function () {
    return gulp.src(path.src.js)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.js))
        .pipe(reload({stream: true}));
});

gulp.task('build:css', function () {
    // style.css
    return gulp.src(path.src.style)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(mmq(option.mmq))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));
});

gulp.task('build:img', function () {
    return gulp.src(path.src.img)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.img))
        .pipe(reload({stream: true}));
});

gulp.task('build:fonts', function() {
    return gulp.src(path.src.fonts)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.fonts))
});

gulp.task('build:zip', function() {
    var datetime = '-' + getDateTime();
    var zipName = 'web' + datetime + '.zip';

    return gulp.src('web/**/*.*')
        .pipe(zip(zipName))
        .pipe(gulp.dest('dist'));
});

// =============================
// ------- Watch task ----------
// =============================

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        return gulp.start('build:html');
    });

    watch([path.watch.style], function(event, cb) {
        return gulp.start('build:css');
    });

    watch([path.watch.js], function(event, cb) {
        return gulp.start('build:js');
    });

    watch([path.watch.img], function(event, cb) {
        return gulp.start('build:img');
    });

    watch([path.watch.fonts], function(event, cb) {
        return gulp.start('build:fonts');
    });
});

// =============================
// -------- Main task ----------
// =============================

gulp.task('vendor', [
    'bower',
    'filter'
]);

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

gulp.task('build', [
    'build:html',
    'build:css',
    'build:js',
    'build:img',
    'build:fonts'
]);

gulp.task('dev', [
    'build',
    'watch',
    'serve'
]);

// Default task
gulp.task('default', ['dev']);

// TODO: Разобрать таск и переписать
// Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
    // Настраиваем фильтры для файлов
    const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
    const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

    // Для нормальных плагинов отработает этот кусок кода
    const stream = gulp.src([
        'bower_components/**/*.min.*',
        'bower_components/**/fonts/*',
        'bower_components/**/*.css',
        '!bower_components/**/*.map'
    ])

    // Фильтруем содержимое на наличие js и css
    .pipe(jsFilter)
    .pipe(cssFilter)
    // run them through a plugin
    .pipe(gulp.dest('dist'));

    // Вываливаем в билд
    jsFilter.restore.pipe(gulp.dest(path.build.libs));

    return stream;
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserSync = require('browser-sync');
var historyApiFallback = require('connect-history-api-fallback');
var reload = browserSync.reload;

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: ".",
            middleware: [ historyApiFallback() ]
        }
    });
});

gulp.task('bs-reload', function () {
    browserSync.reload();
});

gulp.task('serveit', ['browser-sync'], function () {
    // gulp.watch("index.html", ['bs-reload']);
    // gulp.watch("lib/**/*.js", ['bs-reload']);
    // gulp.watch("lib/**/*.jsx", ['bs-reload']);
    // gulp.watch("lib-template/**/*.js", ['bs-reload']);
    // gulp.watch("lib-template/**/*.css", ['bs-reload']);
    // gulp.watch("lib-template/**/*.jsx", ['bs-reload']);
});<commit_msg>no watch task<commit_after>var gulp = require('gulp');
var browserSync = require('browser-sync');
var historyApiFallback = require('connect-history-api-fallback');
var reload = browserSync.reload;

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: ".",
            middleware: [ historyApiFallback() ]
        }
    });
});

gulp.task('bs-reload', function () {
    browserSync.reload();
});

gulp.task('serveit', ['browser-sync'], function () {
    gulp.watch("index.html", ['bs-reload']);
    gulp.watch("lib/**/*.js", ['bs-reload']);
    gulp.watch("lib/**/*.jsx", ['bs-reload']);
    gulp.watch("lib-template/**/*.js", ['bs-reload']);
    gulp.watch("lib-template/**/*.css", ['bs-reload']);
    gulp.watch("lib-template/**/*.jsx", ['bs-reload']);
});

gulp.task('serveit-no-watch', ['browser-sync'], function () {
});<|endoftext|>


<commit_before>'use strict';

/**
 * Dependencies
 */
var gulp = require('gulp')
  , sass = require('gulp-sass')
  , sourcemaps = require('gulp-sourcemaps')
  , uglify = require('gulp-uglify')
  , jsconcat = require('gulp-concat')
  , jshint = require('gulp-jshint')
  , stylish = require('jshint-stylish')
  , ngAnnotate = require('gulp-ng-annotate')
  , notify = require('gulp-notify')
  , plumber = require('gulp-plumber')
  , gulpif = require('gulp-if')
  , browserSync = require('browser-sync')
  , nodemon = require('gulp-nodemon')
  , flatten = require('gulp-flatten')
  , del = require('del');

/**
 * Environment
 */
var env = process.env.NODE_ENV || 'development';

/**
 * Paths
 */
var paths = {
  stylesheets: {
      input: './public/stylesheets/**/*.scss'
    , dev: './development/stylesheets/'
    , output: './dist/stylesheets/'
  },

  scripts: {
      input: [
          './public/scripts/main.js'
        , './public/scripts/services/**/*.js'
        , './public/scripts/directives/**/*.js'
        , './public/scripts/controllers/**/*.js'
      ]
    , dev: './development/scripts/'
    , output: './dist/scripts/'
  },

  assets: {
      input: './public/assets/*'
    , dev: './development/assets/'
    , output: './dist/assets/'
  },

  bower: {
    css: {
        input: './bower_components/**/*.min.css'
      , dev: './development/stylesheets/vendors/'
      , output: './dist/stylesheets/vendors/'
    },
    js: {
        input: [
            './bower_components/**/*.min.js'
          , './bower_components/angularjs-ordinal-filter/ordinal-browser.js'
        ]
      , dev: './development/scripts/vendors/'
      , output: './dist/scripts/vendors/'
    }
  },

  clean: {
      development: './development/'
    , dist: './dist/'
  },

  cname: {
      input: './CNAME'
    , dist: './dist/'
  },

  deploy: {
    input: './dist/**/*'
  }
}

/**
 * Builds
 */
gulp.task('build:views', function() {
 return gulp.src(paths.views.input)
   .pipe(plumber({errorHandler: notify.onError('Error Jade: <%= error.message %>')}))
   .pipe(jade())
   .pipe(gulpif(env === 'development', gulp.dest(paths.views.dev)))
   .pipe(gulpif(env === 'production', gulp.dest(paths.views.output)))
   .pipe(browserSync.reload({stream: true}))
});

gulp.task('build:stylesheets', function () {
  return gulp.src(paths.stylesheets.input)
    .pipe(plumber({errorHandler: notify.onError('Error Sass: <%= error.message %>')}))
    .pipe(gulpif(env === 'development', sourcemaps.init()))
    .pipe(gulpif(env === 'development', sass()))
    .pipe(gulpif(env === 'production', sass({outputStyle: 'compressed'})))
    .pipe(gulpif(env === 'development', sourcemaps.write()))
    .pipe(gulpif(env === 'development', gulp.dest(paths.stylesheets.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.stylesheets.output)))
    .pipe(notify('Sass Compiled'))
    .pipe(browserSync.stream())
});

gulp.task('build:scripts', function () {
  return gulp.src(paths.scripts.input)
    .pipe(plumber({errorHandler: notify.onError('Error JS: <%= error.message %>')}))
    .pipe(gulpif(env === 'production', jshint('.jshintrc')))
    .pipe(gulpif(env === 'production', jshint.reporter('jshint-stylish')))
    .pipe(gulpif(env === 'development', sourcemaps.init()))
    .pipe(jsconcat('main.js'))
    .pipe(gulpif(env === 'development', sourcemaps.write()))
    .pipe(gulpif(env === 'production', ngAnnotate({single_quotes: true})))
    .pipe(gulpif(env === 'production', uglify()))
    .pipe(gulpif(env === 'development', gulp.dest(paths.scripts.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.scripts.output)))
    .pipe(notify('JS Compiled'))
    .pipe(browserSync.stream())
});

gulp.task('build:assets', function () {
  return gulp.src(paths.assets.input)
    .pipe(gulpif(env === 'development', gulp.dest(paths.assets.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.assets.output)))
});

/**
 * Server
 */
gulp.task('server:browserSync', function() {
  browserSync({
    proxy: 'localhost:4000/market',
    files: ['**/*.*'],
    notify: false,
    options: {
      reloadDelay: 2000
    }
  });
});

gulp.task('server:nodemon', function (cb) {
	var started = false;
	return nodemon({
    script: 'server.js'
  }).on('start', function () {
		if (!started) {
			cb();
			started = true;
		}
	});
});

 /**
  * Helpers
  */
gulp.task('helper:bowerComponentsCss', function () {
  gulp.src(paths.bower.css.input)
    .pipe(flatten())
    .pipe(gulpif(env === 'development', gulp.dest(paths.bower.css.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.bower.css.output)))
});

gulp.task('helper:bowerComponentsJs', function () {
  gulp.src(paths.bower.js.input)
    .pipe(flatten())
    .pipe(gulpif(env === 'development', gulp.dest(paths.bower.js.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.bower.js.output)))
});

gulp.task('helper:cname', function () {
  return gulp.src(paths.cname.input)
    .pipe(plumber())
    .pipe(gulp.dest(paths.cname.dist))
});

gulp.task('helper:clean', function () {
  del.sync([
    paths.clean.development
  ])

  del.sync([
    paths.clean.dist
  ])
});

gulp.task('helper:watcher', function() {
  gulp.watch(paths.stylesheets.input, ['build:stylesheets']);
  gulp.watch(paths.scripts.input, ['build:scripts']);
});

gulp.task('deploy', [
    'helper:clean'
  , 'build:stylesheets'
  , 'build:scripts'
  , 'build:assets'
  , 'helper:bowerComponentsCss'
  , 'helper:bowerComponentsJs'
  , 'helper:cname'
]);

gulp.task('default', [
    'helper:clean'
  , 'build:stylesheets'
  , 'build:scripts'
  , 'build:assets'
  , 'helper:bowerComponentsCss'
  , 'helper:bowerComponentsJs'
  , 'helper:cname'
  , 'server:nodemon'
  , 'helper:watcher'
  , 'server:browserSync'
]);
<commit_msg>Fixing Server<commit_after>'use strict';

/**
 * Dependencies
 */
var gulp = require('gulp')
  , sass = require('gulp-sass')
  , sourcemaps = require('gulp-sourcemaps')
  , uglify = require('gulp-uglify')
  , jsconcat = require('gulp-concat')
  , jshint = require('gulp-jshint')
  , stylish = require('jshint-stylish')
  , ngAnnotate = require('gulp-ng-annotate')
  , notify = require('gulp-notify')
  , plumber = require('gulp-plumber')
  , gulpif = require('gulp-if')
  , browserSync = require('browser-sync')
  , nodemon = require('gulp-nodemon')
  , flatten = require('gulp-flatten')
  , del = require('del');

/**
 * Environment
 */
var env = process.env.NODE_ENV || 'development';

/**
 * Paths
 */
var paths = {
  stylesheets: {
      input: './public/stylesheets/**/*.scss'
    , dev: './development/stylesheets/'
    , output: './dist/stylesheets/'
  },

  scripts: {
      input: [
          './public/scripts/main.js'
        , './public/scripts/services/**/*.js'
        , './public/scripts/directives/**/*.js'
        , './public/scripts/controllers/**/*.js'
      ]
    , dev: './development/scripts/'
    , output: './dist/scripts/'
  },

  assets: {
      input: './public/assets/*'
    , dev: './development/assets/'
    , output: './dist/assets/'
  },

  bower: {
    css: {
        input: './bower_components/**/*.min.css'
      , dev: './development/stylesheets/vendors/'
      , output: './dist/stylesheets/vendors/'
    },
    js: {
        input: [
            './bower_components/**/*.min.js'
          , './bower_components/angularjs-ordinal-filter/ordinal-browser.js'
        ]
      , dev: './development/scripts/vendors/'
      , output: './dist/scripts/vendors/'
    }
  },

  clean: {
      development: './development/'
    , dist: './dist/'
  },

  cname: {
      input: './CNAME'
    , dist: './dist/'
  },

  deploy: {
    input: './dist/**/*'
  }
}

/**
 * Builds
 */
gulp.task('build:views', function() {
 return gulp.src(paths.views.input)
   .pipe(plumber({errorHandler: notify.onError('Error Jade: <%= error.message %>')}))
   .pipe(jade())
   .pipe(gulpif(env === 'development', gulp.dest(paths.views.dev)))
   .pipe(gulpif(env === 'production', gulp.dest(paths.views.output)))
   .pipe(browserSync.reload({stream: true}))
});

gulp.task('build:stylesheets', function () {
  return gulp.src(paths.stylesheets.input)
    .pipe(plumber({errorHandler: notify.onError('Error Sass: <%= error.message %>')}))
    .pipe(gulpif(env === 'development', sourcemaps.init()))
    .pipe(gulpif(env === 'development', sass()))
    .pipe(gulpif(env === 'production', sass({outputStyle: 'compressed'})))
    .pipe(gulpif(env === 'development', sourcemaps.write()))
    .pipe(gulpif(env === 'development', gulp.dest(paths.stylesheets.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.stylesheets.output)))
    .pipe(notify('Sass Compiled'))
    .pipe(browserSync.stream())
});

gulp.task('build:scripts', function () {
  return gulp.src(paths.scripts.input)
    .pipe(plumber({errorHandler: notify.onError('Error JS: <%= error.message %>')}))
    .pipe(gulpif(env === 'production', jshint('.jshintrc')))
    .pipe(gulpif(env === 'production', jshint.reporter('jshint-stylish')))
    .pipe(gulpif(env === 'development', sourcemaps.init()))
    .pipe(jsconcat('main.js'))
    .pipe(gulpif(env === 'development', sourcemaps.write()))
    .pipe(gulpif(env === 'production', ngAnnotate({single_quotes: true})))
    .pipe(gulpif(env === 'production', uglify()))
    .pipe(gulpif(env === 'development', gulp.dest(paths.scripts.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.scripts.output)))
    .pipe(notify('JS Compiled'))
    .pipe(browserSync.stream())
});

gulp.task('build:assets', function () {
  return gulp.src(paths.assets.input)
    .pipe(gulpif(env === 'development', gulp.dest(paths.assets.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.assets.output)))
});

/**
 * Server
 */
gulp.task('server:browserSync', function() {
  browserSync({
    proxy: 'localhost:4000',
    files: ['**/*.*'],
    notify: false,
    options: {
      reloadDelay: 2000
    }
  });
});

gulp.task('server:nodemon', function (cb) {
	var started = false;
	return nodemon({
    script: 'server.js'
  }).on('start', function () {
		if (!started) {
			cb();
			started = true;
		}
	});
});

 /**
  * Helpers
  */
gulp.task('helper:bowerComponentsCss', function () {
  gulp.src(paths.bower.css.input)
    .pipe(flatten())
    .pipe(gulpif(env === 'development', gulp.dest(paths.bower.css.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.bower.css.output)))
});

gulp.task('helper:bowerComponentsJs', function () {
  gulp.src(paths.bower.js.input)
    .pipe(flatten())
    .pipe(gulpif(env === 'development', gulp.dest(paths.bower.js.dev)))
    .pipe(gulpif(env === 'production', gulp.dest(paths.bower.js.output)))
});

gulp.task('helper:cname', function () {
  return gulp.src(paths.cname.input)
    .pipe(plumber())
    .pipe(gulp.dest(paths.cname.dist))
});

gulp.task('helper:clean', function () {
  del.sync([
    paths.clean.development
  ])

  del.sync([
    paths.clean.dist
  ])
});

gulp.task('helper:watcher', function() {
  gulp.watch(paths.stylesheets.input, ['build:stylesheets']);
  gulp.watch(paths.scripts.input, ['build:scripts']);
});

gulp.task('deploy', [
    'helper:clean'
  , 'build:stylesheets'
  , 'build:scripts'
  , 'build:assets'
  , 'helper:bowerComponentsCss'
  , 'helper:bowerComponentsJs'
  , 'helper:cname'
]);

gulp.task('default', [
    'helper:clean'
  , 'build:stylesheets'
  , 'build:scripts'
  , 'build:assets'
  , 'helper:bowerComponentsCss'
  , 'helper:bowerComponentsJs'
  , 'helper:cname'
  , 'server:nodemon'
  , 'helper:watcher'
  , 'server:browserSync'
]);
<|endoftext|>