<commit_before>let gulp = require('gulp')

gulp.task('clean', () => {
  let del = require('del')
  return del(['lib/*.js', 'postcss.js', 'build/', 'api/'])
})

// Build

gulp.task('compile', () => {
  let sourcemaps = require('gulp-sourcemaps')
  let changed = require('gulp-changed')
  let babel = require('gulp-babel')
  return gulp.src('lib/*.es6')
    .pipe(changed('lib', { extension: '.js' }))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('lib'))
})

gulp.task('build:lib', ['compile'], () => {
  return gulp.src(['lib/*.js', 'lib/*.d.ts']).pipe(gulp.dest('build/lib'))
})

gulp.task('build:package', () => {
  let editor = require('gulp-json-editor')
  return gulp.src('./package.json')
    .pipe(editor(json => {
      delete json.babel
      delete json.scripts
      delete json.jest
      delete json.babel
      delete json.eslintConfig
      delete json['size-limit']
      delete json['pre-commit']
      delete json['lint-staged']
      delete json.yaspeller
      delete json.devDependencies
      return json
    }))
    .pipe(gulp.dest('build'))
})

gulp.task('build:docs', () => {
  let ignore = require('fs').readFileSync('.npmignore').toString()
    .trim().split(/\n+/)
    .concat([
      'package.json', '.npmignore', 'lib/*', 'test/*', 'CONTRIBUTING.md',
      'node_modules/**/*', 'docs/api.md', 'docs/plugins.md', '*-cn.md',
      'docs/writing-a-plugin.md', 'coverage', 'coverage/*', 'coverage/**/*'
    ]).map(i => '!' + i)
  return gulp.src(['**/*'].concat(ignore))
    .pipe(gulp.dest('build'))
})

gulp.task('build', done => {
  let runSequence = require('run-sequence')
  runSequence('clean', ['build:lib', 'build:docs', 'build:package'], done)
})

// Tests

gulp.task('integration', ['build'], done => {
  let postcss = require('./build')
  let real = require('postcss-parser-tests/real')
  real(done, css => {
    return postcss.parse(css).toResult({ map: { annotation: false } })
  })
})

gulp.task('version', ['build:lib'], () => {
  let Processor = require('./lib/processor')
  let instance = new Processor()
  let pkg = require('./package')
  if (pkg.version !== instance.version) {
    throw new Error('Version in Processor is not equal to package.json')
  }
})

// Common

gulp.task('default', ['version', 'integration'])
<commit_msg>Ignore gulpfile in npm package build<commit_after>let gulp = require('gulp')

gulp.task('clean', () => {
  let del = require('del')
  return del(['lib/*.js', 'postcss.js', 'build/', 'api/'])
})

// Build

gulp.task('compile', () => {
  let sourcemaps = require('gulp-sourcemaps')
  let changed = require('gulp-changed')
  let babel = require('gulp-babel')
  return gulp.src('lib/*.es6')
    .pipe(changed('lib', { extension: '.js' }))
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('lib'))
})

gulp.task('build:lib', ['compile'], () => {
  return gulp.src(['lib/*.js', 'lib/*.d.ts']).pipe(gulp.dest('build/lib'))
})

gulp.task('build:package', () => {
  let editor = require('gulp-json-editor')
  return gulp.src('./package.json')
    .pipe(editor(json => {
      delete json.babel
      delete json.scripts
      delete json.jest
      delete json.babel
      delete json.eslintConfig
      delete json['size-limit']
      delete json['pre-commit']
      delete json['lint-staged']
      delete json.yaspeller
      delete json.devDependencies
      return json
    }))
    .pipe(gulp.dest('build'))
})

gulp.task('build:docs', () => {
  let ignore = require('fs').readFileSync('.npmignore').toString()
    .trim().split(/\n+/)
    .concat([
      'package.json', '.npmignore', 'lib/*', 'test/*', 'CONTRIBUTING.md',
      'node_modules/**/*', 'docs/api.md', 'docs/plugins.md', '*-cn.md',
      'docs/writing-a-plugin.md', 'coverage', 'coverage/*', 'coverage/**/*',
      'gulpfile.js'
    ]).map(i => '!' + i)
  return gulp.src(['**/*'].concat(ignore))
    .pipe(gulp.dest('build'))
})

gulp.task('build', done => {
  let runSequence = require('run-sequence')
  runSequence('clean', ['build:lib', 'build:docs', 'build:package'], done)
})

// Tests

gulp.task('integration', ['build'], done => {
  let postcss = require('./build')
  let real = require('postcss-parser-tests/real')
  real(done, css => {
    return postcss.parse(css).toResult({ map: { annotation: false } })
  })
})

gulp.task('version', ['build:lib'], () => {
  let Processor = require('./lib/processor')
  let instance = new Processor()
  let pkg = require('./package')
  if (pkg.version !== instance.version) {
    throw new Error('Version in Processor is not equal to package.json')
  }
})

// Common

gulp.task('default', ['version', 'integration'])
<|endoftext|>


<commit_before><commit_msg>Fixed incorrect package.json path<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
    path = require('path'),
    defaultAssets = require('./config/assets/default'),
    testAssets = require('./config/assets/test'),
    gulp = require('gulp'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    runSequence = require('run-sequence'),
    MergeStream = require('merge-stream'),
    glob = require('glob'),
    del = require('del'),
    fs = require('fs'),
    mkdirRecursive = require('mkdir-recursive'),
    argv = require('yargs').argv,
    plugins = gulpLoadPlugins({
      rename: {
        'gulp-angular-templatecache': 'templateCache'
      }
    });

// Local settings
var changedTestFiles = [];

// These will be loaded in `loadConfig` task
var environmentAssets,
    assets,
    config;

gulp.task('bower', function(done) {
  if (argv.skipBower) {
    plugins.util.log('Bower task skipped.');
    return done();
  }
  return plugins.bower();
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function() {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function() {
  process.env.NODE_ENV = 'production';
});

// Make sure local config file exists
gulp.task('copyConfig', function(done) {
  if (!fs.existsSync('config/env/local.js') ) {
    gulp
      .src('config/env/local.sample.js')
      .pipe(plugins.rename('local.js'))
      .pipe(gulp.dest('config/env/'));
      done();
  }
  else {
    done();
  }
});

// Load config + assets
// Loading config before `env:*` and `copyConfig` tasks would load configs with wrong environment
gulp.task('loadConfig', function(done) {
  if (!config) {
    config = require('./config/config');
  }
  if (!environmentAssets) {
    environmentAssets = require('./config/assets/' + process.env.NODE_ENV || 'development') || {};
  }
  if (!assets) {
    assets = _.extend(defaultAssets, environmentAssets);
  }
  done();
});

// Nodemon task
gulp.task('nodemon', function(done) {
  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: ['--debug'],
    ext: 'js html',
    ignore: _.union(
      testAssets.tests.server,
      testAssets.tests.client,
      testAssets.tests.e2e,
      ['modules/*/client/**', 'public/**', 'migrations/**', 'scripts/**', 'tmp/**', 'node_modules/**'],
      [defaultAssets.server.fontelloConfig, defaultAssets.server.gulpConfig]
    ),
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  })
  .on('crash', function () {
    console.error('[Server] Script crashed.');
  })
  .on('exit', function () {
    console.log('[Server] Script exited.');
  });
});

// Nodemon task
gulp.task('nodemon:worker', function(done) {
  return plugins.nodemon({
    script: 'worker.js',
    // nodeArgs: ['--debug'],
    ext: 'js',
    ignore: _.union(
      testAssets.tests.server,
      testAssets.tests.client,
      testAssets.tests.e2e,
      ['modules/*/client/**', 'public/**', 'migrations/**', 'scripts/**', 'tmp/**', 'node_modules/**'],
      [defaultAssets.server.fontelloConfig, defaultAssets.server.gulpConfig]
    ),
    watch: _.union(defaultAssets.server.workerJS, defaultAssets.server.config)
  })
  .on('crash', function () {
    console.error('[Worker] Script crashed.');
  })
  .on('exit', function () {
    console.log('[Worker] Script exited.');
  });
});

// Watch files for changes
gulp.task('watch', function() {
  // Start livereload
  plugins.livereload.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
  gulp.watch(defaultAssets.server.allJS, ['lint']).on('change', plugins.livereload.changed);
  gulp.watch(defaultAssets.server.fontelloConfig, ['fontello']);
  gulp.watch(defaultAssets.client.less, ['clean:css', 'styles']);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.client.js, ['lint', 'clean:js', 'scripts']);
    gulp.watch(defaultAssets.server.gulpConfig, ['lint']);
    gulp.watch(defaultAssets.client.views, ['clean:js', 'scripts']).on('change', plugins.livereload.changed);
  } else {
    gulp.watch(defaultAssets.client.js, ['lint']).on('change', plugins.livereload.changed);
    gulp.watch(defaultAssets.server.gulpConfig, ['lint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.livereload.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server:no-lint']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
        }
      });
    });

    plugins.livereload.changed();
  });
});

// ESLint JS linting task
gulp.task('eslint', function() {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failAfterError last.
    .pipe(plugins.eslint.failAfterError());
});

// ESLint JS linting task for Angular files
gulp.task('eslint-angular', function() {
  return gulp.src(defaultAssets.client.js)
    .pipe(plugins.eslint({
      configFile: '.eslintrc-angular.js'
    }))
    .pipe(plugins.eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failAfterError last.
    .pipe(plugins.eslint.failAfterError());
});

// JavaScript task
gulp.task('scripts', ['loadConfig', 'templatecache', 'uibTemplatecache'], function() {
  var scriptFiles = _.union(assets.client.lib.js, assets.client.js);
  return gulp.src( scriptFiles )
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(gulp.dest('public/dist'));
});

// Clean JS files -task
gulp.task('clean:js', function() {
  return del(['public/dist/*.js']);
});

// Clean CSS files -task
gulp.task('clean:css', function() {
  return del(['public/dist/*.css']);
});

// CSS styles task
gulp.task('styles', function() {

  // In production mode:
  if (process.env.NODE_ENV === 'production') {

    var cssStream = gulp.src(defaultAssets.client.lib.css)
        .pipe(plugins.concat('css-files.css'));

    var lessStream = gulp.src( _.union(defaultAssets.client.lib.less, defaultAssets.client.less) )
        .pipe(plugins.concat('less-files.less'))
        .pipe(plugins.less());

    // Combine CSS and LESS streams into one minified css file
    return MergeStream(lessStream, cssStream)
      .pipe(plugins.concat('application.css'))
      .pipe(plugins.autoprefixer())
    	.pipe(plugins.csso())
    	.pipe(plugins.rename({suffix: '.min'}))
      .pipe(gulp.dest('public/dist'));
  }
  // In development mode:
  else {
    // Process only LESS files, since CSS libs will be linked directly at the template
    return gulp.src( _.union(defaultAssets.client.lib.less, defaultAssets.client.less) )
      .pipe(plugins.concat('less-files.less'))
      .pipe(plugins.less())
      .pipe(plugins.autoprefixer())
    	.pipe(plugins.rename({basename: 'application', extname: '.css'}))
      .pipe(gulp.dest('public/dist'))
      .pipe(plugins.livereload());
  }
});

// Angular UI-Boostrap template cache task
// We're not using prebuild UI-Boostraps so that
// we can pick modules we need. Therefore we need
// to manually compile our UIB templates.
gulp.task('uibTemplatecache', function() {

  var uibModulesStreams = new MergeStream();

  // Loop trough module names
  defaultAssets.client.lib.uibModuleTemplates.forEach(function(uibModule) {

    var moduleStream = gulp.src(['public/lib/angular-ui-bootstrap/template/' + uibModule + '/*.html'])
      .pipe(plugins.htmlmin({ collapseWhitespace: true }))
      .pipe(plugins.templateCache('uib-templates-' + uibModule + '.js', {
        root: 'uib/template/' + uibModule + '/',
        module: 'core',
        templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {',
        templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
        templateFooter: '} })();'
      }));

      // Combine with previouly processed templates
      uibModulesStreams.add(moduleStream);
  });

  // Output all tempaltes to one file
  return uibModulesStreams
    .pipe(plugins.concat('uib-templates.js'))
    .pipe(gulp.dest('public/dist'));

});

// Angular template cache task
gulp.task('templatecache', function() {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.htmlmin({ collapseWhitespace: true }))
    .pipe(plugins.templateCache('templates.js', {
      root: '/modules/',
      transformUrl: function(url) {
	      return url.replace('/client', '');
      },
      module: 'core',
      templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {',
      templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '} })();'
    }))
    .pipe(gulp.dest('public/dist'));
});

// Generate font icon files from Fontello.com
gulp.task('fontello', function(done) {
  return gulp.src(defaultAssets.server.fontelloConfig)
    .pipe(plugins.fontello( {
      font:       'font', // Destination dir for Fonts and Glyphs
      css:        'css',  // Destination dir for CSS Styles,
      assetsOnly: true    // extract from ZipFile only CSS Styles and Fonts exclude config.json, LICENSE.txt, README.txt and demo.html
    }))
    .pipe(plugins.print())
    .pipe(gulp.dest('modules/core/client/fonts/fontello'))
    .pipe(plugins.livereload());
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', ['loadConfig'], function(done) {
  mkdirRecursive.mkdir(config.uploadDir, function(err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
    done();
  });
});

// Run Selenium tasks
gulp.task('selenium', plugins.shell.task('python ./scripts/selenium/test.py'));

// Mocha tests task
gulp.task('mocha', function(done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose');
  var agenda = require('./config/lib/agenda');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongoose.connect(function() {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function(err) {
        // If an error occurs, save it
        error = err;
        console.error(err);
      })
      .on('end', function() {
        // When the tests are done, disconnect agenda/mongoose
        // and pass the error state back to gulp
        agenda._mdb.close(function() {
          mongoose.disconnect(function() {
            done(error);
          });
        });
      });
  });

});

// Karma test runner task - singleRun mode
gulp.task('karma', function(done) {
  var KarmaServer = require('karma').Server;
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

// Karma test runner task - watch mode
gulp.task('karma:watch', function(done) {
  var KarmaServer = require('karma').Server;
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
});

// Analyse code for potential errors
gulp.task('lint', function(done) {
  runSequence(['eslint', 'eslint-angular'], done);
});

// Build assets for development mode
gulp.task('build:dev', function(done) {
  runSequence('env:dev', 'bower', 'lint', 'clean', ['uibTemplatecache', 'styles'], done);
});

// Build assets for production mode
gulp.task('build:prod', function(done) {
  runSequence('env:prod', 'bower', 'lint', 'clean', ['styles', 'scripts'], done);
});

// Clean dist css and js files
gulp.task('clean', function(done) {
  runSequence(['clean:css', 'clean:js'], done);
});

// Run the project tests
gulp.task('test', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', ['karma', 'mocha'], done);
});

gulp.task('test:server', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'mocha', done);
});

gulp.task('test:server:no-lint', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function(done) {
  runSequence('test:server:no-lint', 'watch:server:run-tests', done);
});

gulp.task('test:client', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'karma', done);
});

gulp.task('test:client:watch', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'karma:watch', done);
});

// Run the project in development mode
gulp.task('develop', function(done) {
  runSequence('env:dev', 'copyConfig', 'makeUploadsDir', 'build:dev', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
  runSequence('env:prod', 'copyConfig', 'makeUploadsDir', 'build:prod', ['nodemon', 'watch'], done);
});

// Run worker script in development mode
gulp.task('worker:dev', function(done) {
  runSequence('env:dev', 'copyConfig', ['nodemon:worker'], done);
});

// Run worker script in production mode
gulp.task('worker:prod', function(done) {
  runSequence('env:prod', 'copyConfig', ['nodemon:worker'], done);
});

// Default to develop mode
gulp.task('default', function(done) {
  runSequence('develop', done);
});
<commit_msg>More verbose less processor errors<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
    path = require('path'),
    defaultAssets = require('./config/assets/default'),
    testAssets = require('./config/assets/test'),
    gulp = require('gulp'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    runSequence = require('run-sequence'),
    MergeStream = require('merge-stream'),
    glob = require('glob'),
    del = require('del'),
    fs = require('fs'),
    mkdirRecursive = require('mkdir-recursive'),
    argv = require('yargs').argv,
    plugins = gulpLoadPlugins({
      rename: {
        'gulp-angular-templatecache': 'templateCache'
      }
    });

// Local settings
var changedTestFiles = [];

// These will be loaded in `loadConfig` task
var environmentAssets,
    assets,
    config;

gulp.task('bower', function(done) {
  if (argv.skipBower) {
    plugins.util.log('Bower task skipped.');
    return done();
  }
  return plugins.bower();
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
  process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function() {
  process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function() {
  process.env.NODE_ENV = 'production';
});

// Make sure local config file exists
gulp.task('copyConfig', function(done) {
  if (!fs.existsSync('config/env/local.js') ) {
    gulp
      .src('config/env/local.sample.js')
      .pipe(plugins.rename('local.js'))
      .pipe(gulp.dest('config/env/'));
      done();
  }
  else {
    done();
  }
});

// Load config + assets
// Loading config before `env:*` and `copyConfig` tasks would load configs with wrong environment
gulp.task('loadConfig', function(done) {
  if (!config) {
    config = require('./config/config');
  }
  if (!environmentAssets) {
    environmentAssets = require('./config/assets/' + process.env.NODE_ENV || 'development') || {};
  }
  if (!assets) {
    assets = _.extend(defaultAssets, environmentAssets);
  }
  done();
});

// Nodemon task
gulp.task('nodemon', function(done) {
  return plugins.nodemon({
    script: 'server.js',
    nodeArgs: ['--debug'],
    ext: 'js html',
    ignore: _.union(
      testAssets.tests.server,
      testAssets.tests.client,
      testAssets.tests.e2e,
      ['modules/*/client/**', 'public/**', 'migrations/**', 'scripts/**', 'tmp/**', 'node_modules/**'],
      [defaultAssets.server.fontelloConfig, defaultAssets.server.gulpConfig]
    ),
    watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
  })
  .on('crash', function () {
    console.error('[Server] Script crashed.');
  })
  .on('exit', function () {
    console.log('[Server] Script exited.');
  });
});

// Nodemon task
gulp.task('nodemon:worker', function(done) {
  return plugins.nodemon({
    script: 'worker.js',
    // nodeArgs: ['--debug'],
    ext: 'js',
    ignore: _.union(
      testAssets.tests.server,
      testAssets.tests.client,
      testAssets.tests.e2e,
      ['modules/*/client/**', 'public/**', 'migrations/**', 'scripts/**', 'tmp/**', 'node_modules/**'],
      [defaultAssets.server.fontelloConfig, defaultAssets.server.gulpConfig]
    ),
    watch: _.union(defaultAssets.server.workerJS, defaultAssets.server.config)
  })
  .on('crash', function () {
    console.error('[Worker] Script crashed.');
  })
  .on('exit', function () {
    console.log('[Worker] Script exited.');
  });
});

// Watch files for changes
gulp.task('watch', function() {
  // Start livereload
  plugins.livereload.listen();

  // Add watch rules
  gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
  gulp.watch(defaultAssets.server.allJS, ['lint']).on('change', plugins.livereload.changed);
  gulp.watch(defaultAssets.server.fontelloConfig, ['fontello']);
  gulp.watch(defaultAssets.client.less, ['clean:css', 'styles']);

  if (process.env.NODE_ENV === 'production') {
    gulp.watch(defaultAssets.client.js, ['lint', 'clean:js', 'scripts']);
    gulp.watch(defaultAssets.server.gulpConfig, ['lint']);
    gulp.watch(defaultAssets.client.views, ['clean:js', 'scripts']).on('change', plugins.livereload.changed);
  } else {
    gulp.watch(defaultAssets.client.js, ['lint']).on('change', plugins.livereload.changed);
    gulp.watch(defaultAssets.server.gulpConfig, ['lint']);
    gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
  }
});

// Watch server test files
gulp.task('watch:server:run-tests', function () {
  // Start livereload
  plugins.livereload.listen();

  // Add Server Test file rules
  gulp.watch([testAssets.tests.server, defaultAssets.server.allJS], ['test:server:no-lint']).on('change', function (file) {
    changedTestFiles = [];

    // iterate through server test glob patterns
    _.forEach(testAssets.tests.server, function (pattern) {
      // determine if the changed (watched) file is a server test
      _.forEach(glob.sync(pattern), function (f) {
        var filePath = path.resolve(f);

        if (filePath === path.resolve(file.path)) {
          changedTestFiles.push(f);
        }
      });
    });

    plugins.livereload.changed();
  });
});

// ESLint JS linting task
gulp.task('eslint', function() {
  var assets = _.union(
    defaultAssets.server.gulpConfig,
    defaultAssets.server.allJS,
    defaultAssets.client.js,
    testAssets.tests.server,
    testAssets.tests.client,
    testAssets.tests.e2e
  );

  return gulp.src(assets)
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failAfterError last.
    .pipe(plugins.eslint.failAfterError());
});

// ESLint JS linting task for Angular files
gulp.task('eslint-angular', function() {
  return gulp.src(defaultAssets.client.js)
    .pipe(plugins.eslint({
      configFile: '.eslintrc-angular.js'
    }))
    .pipe(plugins.eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failAfterError last.
    .pipe(plugins.eslint.failAfterError());
});

// JavaScript task
gulp.task('scripts', ['loadConfig', 'templatecache', 'uibTemplatecache'], function() {
  var scriptFiles = _.union(assets.client.lib.js, assets.client.js);
  return gulp.src( scriptFiles )
    .pipe(plugins.ngAnnotate())
    .pipe(plugins.uglify({
      mangle: false
    }))
    .pipe(plugins.concat('application.min.js'))
    .pipe(gulp.dest('public/dist'));
});

// Clean JS files -task
gulp.task('clean:js', function() {
  return del(['public/dist/*.js']);
});

// Clean CSS files -task
gulp.task('clean:css', function() {
  return del(['public/dist/*.css']);
});

// CSS styles task
gulp.task('styles', function() {

  // In production mode:
  if (process.env.NODE_ENV === 'production') {

    var cssStream = gulp.src(defaultAssets.client.lib.css)
        .pipe(plugins.concat('css-files.css'));

    var lessStream = gulp.src(_.union(defaultAssets.client.lib.less, defaultAssets.client.less))
        .pipe(plugins.concat('less-files.less'))
        .pipe(plugins.less());

    // Combine CSS and LESS streams into one minified css file
    return MergeStream(lessStream, cssStream)
      .pipe(plugins.concat('application.css'))
      .pipe(plugins.autoprefixer())
    	.pipe(plugins.csso())
    	.pipe(plugins.rename({ suffix: '.min' }))
      .pipe(gulp.dest('public/dist'));
  }
  // In development mode:
  else {
    // More verbose `less` errors
    var lessProcessor = plugins.less();
    lessProcessor.on('error', function(err) {
      console.log(err);
    });
    // Process only LESS files, since CSS libs will be linked directly at the template
    return gulp.src(_.union(defaultAssets.client.lib.less, defaultAssets.client.less))
      .pipe(plugins.concat('less-files.less'))
      .pipe(lessProcessor)
      .pipe(plugins.autoprefixer())
    	.pipe(plugins.rename({ basename: 'application', extname: '.css' }))
      .pipe(gulp.dest('public/dist'))
      .pipe(plugins.livereload());
  }
});

// Angular UI-Boostrap template cache task
// We're not using prebuild UI-Boostraps so that
// we can pick modules we need. Therefore we need
// to manually compile our UIB templates.
gulp.task('uibTemplatecache', function() {

  var uibModulesStreams = new MergeStream();

  // Loop trough module names
  defaultAssets.client.lib.uibModuleTemplates.forEach(function(uibModule) {

    var moduleStream = gulp.src(['public/lib/angular-ui-bootstrap/template/' + uibModule + '/*.html'])
      .pipe(plugins.htmlmin({ collapseWhitespace: true }))
      .pipe(plugins.templateCache('uib-templates-' + uibModule + '.js', {
        root: 'uib/template/' + uibModule + '/',
        module: 'core',
        templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {',
        templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
        templateFooter: '} })();'
      }));

      // Combine with previouly processed templates
      uibModulesStreams.add(moduleStream);
  });

  // Output all tempaltes to one file
  return uibModulesStreams
    .pipe(plugins.concat('uib-templates.js'))
    .pipe(gulp.dest('public/dist'));

});

// Angular template cache task
gulp.task('templatecache', function() {
  return gulp.src(defaultAssets.client.views)
    .pipe(plugins.htmlmin({ collapseWhitespace: true }))
    .pipe(plugins.templateCache('templates.js', {
      root: '/modules/',
      transformUrl: function(url) {
	      return url.replace('/client', '');
      },
      module: 'core',
      templateHeader: '(function() { \'use strict\'; angular.module(\'<%= module %>\'<%= standalone %>).run(templates); templates.$inject = [\'$templateCache\']; function templates($templateCache) {',
      templateBody: '$templateCache.put(\'<%= url %>\', \'<%= contents %>\');',
      templateFooter: '} })();'
    }))
    .pipe(gulp.dest('public/dist'));
});

// Generate font icon files from Fontello.com
gulp.task('fontello', function(done) {
  return gulp.src(defaultAssets.server.fontelloConfig)
    .pipe(plugins.fontello( {
      font:       'font', // Destination dir for Fonts and Glyphs
      css:        'css',  // Destination dir for CSS Styles,
      assetsOnly: true    // extract from ZipFile only CSS Styles and Fonts exclude config.json, LICENSE.txt, README.txt and demo.html
    }))
    .pipe(plugins.print())
    .pipe(gulp.dest('modules/core/client/fonts/fontello'))
    .pipe(plugins.livereload());
});

// Make sure upload directory exists
gulp.task('makeUploadsDir', ['loadConfig'], function(done) {
  mkdirRecursive.mkdir(config.uploadDir, function(err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err);
    }
    done();
  });
});

// Run Selenium tasks
gulp.task('selenium', plugins.shell.task('python ./scripts/selenium/test.py'));

// Mocha tests task
gulp.task('mocha', function(done) {
  // Open mongoose connections
  var mongoose = require('./config/lib/mongoose');
  var agenda = require('./config/lib/agenda');
  var testSuites = changedTestFiles.length ? changedTestFiles : testAssets.tests.server;
  var error;

  // Connect mongoose
  mongoose.connect(function() {
    mongoose.loadModels();
    // Run the tests
    gulp.src(testSuites)
      .pipe(plugins.mocha({
        reporter: 'spec',
        timeout: 10000
      }))
      .on('error', function(err) {
        // If an error occurs, save it
        error = err;
        console.error(err);
      })
      .on('end', function() {
        // When the tests are done, disconnect agenda/mongoose
        // and pass the error state back to gulp
        agenda._mdb.close(function() {
          mongoose.disconnect(function() {
            done(error);
          });
        });
      });
  });

});

// Karma test runner task - singleRun mode
gulp.task('karma', function(done) {
  var KarmaServer = require('karma').Server;
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

// Karma test runner task - watch mode
gulp.task('karma:watch', function(done) {
  var KarmaServer = require('karma').Server;
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
});

// Analyse code for potential errors
gulp.task('lint', function(done) {
  runSequence(['eslint', 'eslint-angular'], done);
});

// Build assets for development mode
gulp.task('build:dev', function(done) {
  runSequence('env:dev', 'bower', 'lint', 'clean', ['uibTemplatecache', 'styles'], done);
});

// Build assets for production mode
gulp.task('build:prod', function(done) {
  runSequence('env:prod', 'bower', 'lint', 'clean', ['styles', 'scripts'], done);
});

// Clean dist css and js files
gulp.task('clean', function(done) {
  runSequence(['clean:css', 'clean:js'], done);
});

// Run the project tests
gulp.task('test', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', ['karma', 'mocha'], done);
});

gulp.task('test:server', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'mocha', done);
});

gulp.task('test:server:no-lint', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'mocha', done);
});

// Watch all server files for changes & run server tests (test:server) task on changes
gulp.task('test:server:watch', function(done) {
  runSequence('test:server:no-lint', 'watch:server:run-tests', done);
});

gulp.task('test:client', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'karma', done);
});

gulp.task('test:client:watch', function(done) {
  runSequence('env:test', 'copyConfig', 'makeUploadsDir', 'lint', 'karma:watch', done);
});

// Run the project in development mode
gulp.task('develop', function(done) {
  runSequence('env:dev', 'copyConfig', 'makeUploadsDir', 'build:dev', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
  runSequence('env:prod', 'copyConfig', 'makeUploadsDir', 'build:prod', ['nodemon', 'watch'], done);
});

// Run worker script in development mode
gulp.task('worker:dev', function(done) {
  runSequence('env:dev', 'copyConfig', ['nodemon:worker'], done);
});

// Run worker script in production mode
gulp.task('worker:prod', function(done) {
  runSequence('env:prod', 'copyConfig', ['nodemon:worker'], done);
});

// Default to develop mode
gulp.task('default', function(done) {
  runSequence('develop', done);
});
<|endoftext|>


<commit_before><commit_msg>no cache.<commit_after><|endoftext|>


<commit_before>var buffer = require('vinyl-buffer');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var path = require('path');
var del = require('del');

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

var SRC = './src';
var DEST = './dist';
var PACKAGES = './modules'

function copy()
{
    var src = gulp.src(
    [
        'src/**/*',
        '!src/*.twig',
        '!src/*.html',
        '!src/*.scss',
        '!src/**/assets/sass/**/*',
        '!src/**/assets/img/layout/**/*',
        '!src/**/assets/js/modules/**/*',
        '!src/**/layouts/**/*',
        '!src/**/templates/**/*',
    ], { nodir: true })
    .pipe(plugins.changed(DEST))
    .pipe(gulp.dest(DEST));

    var packages = gulp.src(
    [
        './src/**/*',
        '!**/*.html',
        '!**/*.twig',
        '!**/*.sass',
        '!**/sprite/**/*',
        '!**/svg-sprite/**/*',
        '!**/sass/**/*',
        '!**/js/**/*',
        '!**/layouts/**/*',
        '!**/templates/**/*',
    ], { nodir: true })
    .pipe(gulp.dest(DEST));

    var bower_components = gulp.src(
    [
        './bower_components/**',
        '!./bower_components/*tipi*/**',
        '!./bower_components/*bourbon*/**',
    ], { nodir: true })
    .pipe(gulp.dest(DEST + '/assets/js/lib/'));

    return merge(src, packages, bower_components);
}

function clean()
{
    return del([DEST]);
}

function sass()
{
    var sass = gulp.src(ASSETS + '/sass/tipi.scss')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.sassGlob({
        ignorePaths: [
            '**/__*.scss'
        ]
    }))
    .pipe(plugins.sass().on('error', plugins.sass.logError))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/css'));

    return sass.pipe(plugins.connect.reload());
}

function spritesmith()
{
    var spritesmith = gulp.src(SRC + '/assets/img/layout/sprite/**.png')
    .pipe(plugins.plumber())
    .pipe(plugins.spritesmith({
        padding: 4,
        imgName: 'sprite.png',
        imgPath: '/assets/img/layout/',
        cssName: 'tipi.sprite.css',
        cssTemplate: SRC + '/assets/img/layout/sprite/config.handlebars',
        cssHandlebarsHelpers : {
            divideRetina : function(value) {
                return parseInt(value) / 2;
            }
        }
    }));

    var img = spritesmith.img
    .pipe(buffer())
    .pipe(gulp.dest(DEST + '/assets/img/layout/'));

    var css = spritesmith.css
    .pipe(plugins.cssnano())
    .pipe(gulp.dest(DEST + '/assets/css/'));

    return merge(img, css).pipe(plugins.connect.reload())
}

function svgstore()
{
    var svgstore = gulp.src(
    [
        SRC + '/assets/img/layout/svg-sprite/**.svg'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.filter(function(file) {
        return file.stat && file.contents.length;
    }))
    .pipe(plugins.rename({prefix: 'glyph-'}))
    .pipe(plugins.svgmin(function (file) {
        var prefix = path.basename(file.relative, path.extname(file.relative));

        return {
            plugins: [
                {
                   cleanupIDs: {
                       prefix: prefix + '-',
                       minify: true
                   },
               },
               {
                   removeAttrs: {
                       attrs: [
                           '(fill|stroke|class|style)',
                           'svg:(width|height)'
                       ]
                   }
               }
           ]
        }
    }))
    .pipe(plugins.svgstore({
        inlineSvg: true
    }))
    .pipe(gulp.dest(DEST + '/assets/img/layout/'))

    return svgstore.pipe(plugins.connect.reload());;
}

function concat()
{

    var src = gulp.src('src/assets/js/modules/**.js')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('modules.js'))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/js/'));

    var packages = gulp.src(PACKAGES + '/**/tipi.*.js')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('tipi.js'))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/js/lib/tipi'));

    return merge(src, packages).pipe(plugins.connect.reload());
}

function twig()
{
    var options = {
        base : SRC,
        errorLogToConsole : true
    }

    var src = gulp.src(
    [
        SRC + '/**/*.twig',
        '!' + SRC + '/**/layouts/**/*.twig',
        '!' + SRC + '/**/partials/*.twig',
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.twig(options))
    .pipe(plugins.faker())
    .pipe(gulp.dest(DEST));

    var packages = gulp.src(
    [
        PACKAGES + '/*tipi*/*.twig'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.twig(options))
    .pipe(plugins.faker())
    .pipe(gulp.dest(DEST + '/packages'));

    return merge(src, packages).pipe(plugins.connect.reload());
}

function connect()
{
    plugins.connect.server({
        root: DEST,
        livereload: true
    });
}

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

gulp.task('copy', function() {
   return copy();
});

gulp.task('styles', function() {
   return sass();
});

gulp.task('spritesmith', function () {
   return spritesmith();
});

gulp.task('svgstore', function () {
   return svgstore();
});

gulp.task('javascripts', function() {
   return concat();
});

gulp.task('pages', function() {
   return twig();
});

gulp.task('connect', function() {
   return connect();
});

gulp.task('watch', function() {
    plugins.watch([
            SRC + '/assets/**/*',
        ], function() {
            gulp.start('copy');
        }
    );

    plugins.watch([
            SRC + '/assets/**/*.scss',
            PACKAGES + '/**/*.scss',
        ], function() {
            gulp.start('styles');
        }
    );

    plugins.watch([
            SRC + '/assets/img/layout/svg-sprite/**/*.svg',
        ], function() {
            gulp.start('svgstore');
        }
    );

    plugins.watch([
            SRC + '/assets/img/layout/sprite/**/*.png',
        ], function() {
            gulp.start('spritesmith');
        }
    );

    plugins.watch([
            SRC + '/assets/**/*.js',
            PACKAGES + '/**/tipi.*.js'
        ], function() {
            gulp.start('javascripts');
        }
    );

    plugins.watch([
            SRC + '/**/*.twig',
            PACKAGES + '/*tipi*/*.twig',
        ], function() {
            gulp.start('pages');
        }
    );
});

gulp.task('default', function(callback) {
    runSequence(
        'clean',
        'copy',
        [
            'styles',
            'spritesmith',
            'svgstore',
            'javascripts',
            'pages'
        ],
        callback
    );
});

gulp.task('serve', function(callback) {
    runSequence(
        'clean',
        'copy',
        [
            'styles',
            'spritesmith',
            'svgstore',
            'javascripts',
            'pages'
        ],
        'connect',
        'watch',
        callback
    );
});<commit_msg>Remove ASSETS<commit_after>var buffer = require('vinyl-buffer');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var path = require('path');
var del = require('del');

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

var SRC = './src';
var DEST = './dist';
var PACKAGES = './modules'

function copy()
{
    var src = gulp.src(
    [
        'src/**/*',
        '!src/*.twig',
        '!src/*.html',
        '!src/*.scss',
        '!src/**/assets/sass/**/*',
        '!src/**/assets/img/layout/**/*',
        '!src/**/assets/js/modules/**/*',
        '!src/**/layouts/**/*',
        '!src/**/templates/**/*',
    ], { nodir: true })
    .pipe(plugins.changed(DEST))
    .pipe(gulp.dest(DEST));

    var packages = gulp.src(
    [
        './src/**/*',
        '!**/*.html',
        '!**/*.twig',
        '!**/*.sass',
        '!**/sprite/**/*',
        '!**/svg-sprite/**/*',
        '!**/sass/**/*',
        '!**/js/**/*',
        '!**/layouts/**/*',
        '!**/templates/**/*',
    ], { nodir: true })
    .pipe(gulp.dest(DEST));

    var bower_components = gulp.src(
    [
        './bower_components/**',
        '!./bower_components/*tipi*/**',
        '!./bower_components/*bourbon*/**',
    ], { nodir: true })
    .pipe(gulp.dest(DEST + '/assets/js/lib/'));

    return merge(src, packages, bower_components);
}

function clean()
{
    return del([DEST]);
}

function sass()
{
    var sass = gulp.src(SRC + '/assets/sass/tipi.scss')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.sassGlob({
        ignorePaths: [
            '**/__*.scss'
        ]
    }))
    .pipe(plugins.sass().on('error', plugins.sass.logError))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/css'));

    return sass.pipe(plugins.connect.reload());
}

function spritesmith()
{
    var spritesmith = gulp.src(SRC + '/assets/img/layout/sprite/**.png')
    .pipe(plugins.plumber())
    .pipe(plugins.spritesmith({
        padding: 4,
        imgName: 'sprite.png',
        imgPath: '/assets/img/layout/',
        cssName: 'tipi.sprite.css',
        cssTemplate: SRC + '/assets/img/layout/sprite/config.handlebars',
        cssHandlebarsHelpers : {
            divideRetina : function(value) {
                return parseInt(value) / 2;
            }
        }
    }));

    var img = spritesmith.img
    .pipe(buffer())
    .pipe(gulp.dest(DEST + '/assets/img/layout/'));

    var css = spritesmith.css
    .pipe(plugins.cssnano())
    .pipe(gulp.dest(DEST + '/assets/css/'));

    return merge(img, css).pipe(plugins.connect.reload())
}

function svgstore()
{
    var svgstore = gulp.src(
    [
        SRC + '/assets/img/layout/svg-sprite/**.svg'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.filter(function(file) {
        return file.stat && file.contents.length;
    }))
    .pipe(plugins.rename({prefix: 'glyph-'}))
    .pipe(plugins.svgmin(function (file) {
        var prefix = path.basename(file.relative, path.extname(file.relative));

        return {
            plugins: [
                {
                   cleanupIDs: {
                       prefix: prefix + '-',
                       minify: true
                   },
               },
               {
                   removeAttrs: {
                       attrs: [
                           '(fill|stroke|class|style)',
                           'svg:(width|height)'
                       ]
                   }
               }
           ]
        }
    }))
    .pipe(plugins.svgstore({
        inlineSvg: true
    }))
    .pipe(gulp.dest(DEST + '/assets/img/layout/'))

    return svgstore.pipe(plugins.connect.reload());;
}

function concat()
{

    var src = gulp.src('src/assets/js/modules/**.js')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('modules.js'))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/js/'));

    var packages = gulp.src(PACKAGES + '/**/tipi.*.js')
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.concat('tipi.js'))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest(DEST + '/assets/js/lib/tipi'));

    return merge(src, packages).pipe(plugins.connect.reload());
}

function twig()
{
    var options = {
        base : SRC,
        errorLogToConsole : true
    }

    var src = gulp.src(
    [
        SRC + '/**/*.twig',
        '!' + SRC + '/**/layouts/**/*.twig',
        '!' + SRC + '/**/partials/*.twig',
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.twig(options))
    .pipe(plugins.faker())
    .pipe(gulp.dest(DEST));

    var packages = gulp.src(
    [
        PACKAGES + '/*tipi*/*.twig'
    ])
    .pipe(plugins.plumber())
    .pipe(plugins.twig(options))
    .pipe(plugins.faker())
    .pipe(gulp.dest(DEST + '/packages'));

    return merge(src, packages).pipe(plugins.connect.reload());
}

function connect()
{
    plugins.connect.server({
        root: DEST,
        livereload: true
    });
}

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

gulp.task('copy', function() {
   return copy();
});

gulp.task('styles', function() {
   return sass();
});

gulp.task('spritesmith', function () {
   return spritesmith();
});

gulp.task('svgstore', function () {
   return svgstore();
});

gulp.task('javascripts', function() {
   return concat();
});

gulp.task('pages', function() {
   return twig();
});

gulp.task('connect', function() {
   return connect();
});

gulp.task('watch', function() {
    plugins.watch([
            SRC + '/assets/**/*',
        ], function() {
            gulp.start('copy');
        }
    );

    plugins.watch([
            SRC + '/assets/**/*.scss',
            PACKAGES + '/**/*.scss',
        ], function() {
            gulp.start('styles');
        }
    );

    plugins.watch([
            SRC + '/assets/img/layout/svg-sprite/**/*.svg',
        ], function() {
            gulp.start('svgstore');
        }
    );

    plugins.watch([
            SRC + '/assets/img/layout/sprite/**/*.png',
        ], function() {
            gulp.start('spritesmith');
        }
    );

    plugins.watch([
            SRC + '/assets/**/*.js',
            PACKAGES + '/**/tipi.*.js'
        ], function() {
            gulp.start('javascripts');
        }
    );

    plugins.watch([
            SRC + '/**/*.twig',
            PACKAGES + '/*tipi*/*.twig',
        ], function() {
            gulp.start('pages');
        }
    );
});

gulp.task('default', function(callback) {
    runSequence(
        'clean',
        'copy',
        [
            'styles',
            'spritesmith',
            'svgstore',
            'javascripts',
            'pages'
        ],
        callback
    );
});

gulp.task('serve', function(callback) {
    runSequence(
        'clean',
        'copy',
        [
            'styles',
            'spritesmith',
            'svgstore',
            'javascripts',
            'pages'
        ],
        'connect',
        'watch',
        callback
    );
});<|endoftext|>


<commit_before>import { GET } from '../../commons/utils/request';
import { ZIXUN_JUNSHI } from '../constants/urls';
import * as types from '../constants/actionTypes';

const receiveJunShi = data => {
  return {
    type: types.RECEIVE_JUNSHI,
    ...data,
  };
};

const fetchJunShi = params => {
  return dispatch => {
    return GET(ZIXUN_JUNSHI, params).then(resp => {
      dispatch(
        receiveJunShi({
          junshi: resp.data,
        }),
      );
    });
  };
};

module.exports = {
  fetchJunShi,
};
<commit_msg>prettier<commit_after>import { GET } from '../../commons/utils/request';
import { ZIXUN_JUNSHI } from '../constants/urls';
import * as types from '../constants/actionTypes'

const receiveJunShi = data => {
  return {
    type: types.RECEIVE_JUNSHI,
    ...data,
  };
};

const fetchJunShi = params => {
  return dispatch => {
    return GET(ZIXUN_JUNSHI, params).then(resp => {
      dispatch(
        receiveJunShi({
          junshi: resp.data,
        }),
      );
    });
  };
};

module.exports = {
  fetchJunShi,
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    initGulpTasks = require('react-component-gulp-tasks');

var taskConfig = {

	component: {
		name: 'Elemental',
		dependencies: [
			'react',
			'react/addons',
			'blacklist',
			'classnames',
			'underscore'
		]
	},

	example: {
		src: 'site/src',
		dist: 'site/dist',
		files: [
			'index.html',
			'.gitignore'
		],
		scripts: [
			'site.js'
		],
		less: [
			'site.less'
		]
	}

};

initGulpTasks(gulp, taskConfig);
<commit_msg>Including moment in component dependencies<commit_after>var gulp = require('gulp'),
    initGulpTasks = require('react-component-gulp-tasks');

var taskConfig = {

	component: {
		name: 'Elemental',
		dependencies: [
			'blacklist',
			'classnames',
			'moment',
			'react',
			'react/addons',
			'underscore'
		]
	},

	example: {
		src: 'site/src',
		dist: 'site/dist',
		files: [
			'index.html',
			'.gitignore'
		],
		scripts: [
			'site.js'
		],
		less: [
			'site.less'
		]
	}

};

initGulpTasks(gulp, taskConfig);
<|endoftext|>


<commit_before>var autoprefixer    = require('gulp-autoprefixer'),
    // base64          = require('gulp-base64'),
    // bundle          = require('gulp-bundle-assets'),
    cached          = require('gulp-cached'),
    // changed         = require('gulp-changed'),
    csslint         = require('gulp-csslint'),
    del             = require('del'),
    // docco           = require('gulp-docco'),
    fixmyjs         = require('gulp-fixmyjs'),
    git             = require('gulp-git'),
    gulp            = require('gulp'),
    // include         = require('gulp-file-include'),
    jshint          = require('gulp-jshint'),
    lintspaces      = require('gulp-lintspaces'),
    nib             = require('nib'),
    notify          = require('gulp-notify'),
    // Pageres         = require('pageres'),
    phpcs           = require('gulp-phpcs'),
    prettify        = require('gulp-jsbeautifier'),
    // sourcemaps      = require('gulp-sourcemaps'),
    // stripDebug      = require('gulp-strip-debug'),
    stylish         = require('jshint-stylish'),
    stylus          = require('gulp-stylus'),
    svgmin          = require('gulp-svgmin'),
    tinypng         = require('gulp-tinypng'),
    uglify          = require('gulp-uglify'),
    p               = {
                        allfiles    : [
                                            './**/*.php',
                                            './**/*.phtml',
                                            './asset_sources/stylus/**/*.styl',
                                            './asset_sources/js/*.js'
                                      ],
                        phpfiles    : ['./**/*.php', '!./laterpay/library/**/*.php'],
                        srcStylus   : './asset_sources/stylus/*.styl',
                        srcJS       : './asset_sources/js/',
                        srcSVG      : './asset_sources/img/**/*.svg',
                        srcPNG      : './asset_sources/img/**/*.png',
                        distJS      : './res/js/',
                        distCSS     : './res/css/',
                        distIMG     : './res/img/',
                    };

// TASKS -----------------------------------------------------------------------
// clean up all files in the target directories
gulp.task('clean', function(cb) {
    del([p.distJS + '*.js', p.distCSS + '*.css'], cb);
});

// CSS related tasks
gulp.task('css-watch', function() {
    gulp.src(p.srcStylus)
        .pipe(stylus({                                                          // process Stylus sources to CSS
            use     : nib(),
            linenos : true,                                                      // make line numbers available in browser dev tools
            // TODO: generate sourcemap
        }))
        .pipe(autoprefixer('last 3 versions', '> 2%', 'ff > 23', 'ie > 8'))     // vendorize properties for supported browsers
        .on('error', notify.onError())
        .pipe(gulp.dest(p.distCSS));                                            // move to target folder
});

gulp.task('css-build', function() {
    gulp.src(p.srcStylus)
        .pipe(stylus({                                                          // process Stylus sources to CSS
            use     : nib(),
            compress: true
        }))
        // .pipe(base64({                                                          // base64-encode images and inline them using datauris
        //     baseDir         : 'laterpay/assets/img',
        //     extensions      : ['png', svg],
        //     exclude         : ['laterpay-wordpress-icons'],
        //     maxImageSize    : 12*1024,
        //     debug           : true
        // }))
        .on('error', notify.onError())
        .pipe(autoprefixer('last 3 versions', '> 2%', 'ff > 23', 'ie > 8'))     // vendorize properties for supported browsers
        .pipe(gulp.dest(p.distCSS));                                            // move to target folder
});

// Javascript related tasks
gulp.task('js-watch', function() {
    gulp.src(p.srcJS + '*.js')
        .pipe(cached('hinting'))                                                // only process modified files
            .pipe(jshint('.jshintrc'))
            .pipe(jshint.reporter(stylish))
            .pipe(gulp.dest(p.distJS));                                          // move to target folder;
});

gulp.task('js-build', function() {
    gulp.src(p.srcJS + '*.js')
        // can't use stripDebug, as it kills the one alert we are using on purpose in laterpay-post-view.js
        // .pipe(stripDebug())                                                     // remove console, alert, and debugger statements
        // .pipe(fixmyjs({                                                         // fix JSHint errors if possible
        //     lookup: false
        // }))
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter(stylish))
        .pipe(uglify())                                                         // compress with uglify
        .pipe(gulp.dest(p.distJS));                                             // move to target folder
});

gulp.task('js-format', function() {
    return gulp.src(p.srcJS + '*.js')
            .pipe(prettify({
                config  : '.jsbeautifyrc',
                mode    : 'VERIFY_AND_WRITE',
            }))
            .pipe(gulp.dest(p.srcJS));
});

// Image related tasks
gulp.task('img-build', function() {
    gulp.src(p.srcSVG)
        .pipe(svgmin())                                                         // compress with svgmin
        .pipe(gulp.dest(p.distIMG));                                            // move to target folder

    gulp.src(p.srcPNG)
        .pipe(tinypng('-XMDmj3TW4Rymyizj1jcUXIvtc-uYJcM'))                      // compress with TinyPNG
        .pipe(gulp.dest(p.distIMG));                                            // move to target folder
});

// ensure consistent whitespace etc. in files
gulp.task('fileformat', function() {
    return gulp.src(p.allfiles)
            .pipe(lintspaces({
                indentation     : 'spaces',
                spaces          : 4,
                trailingspaces  : true,
                newline         : true,
                newlineMaximum  : 2,
            }))
            .pipe(lintspaces.reporter());
});

// check PHP coding standards
gulp.task('sniffphp', function() {
    return gulp.src(p.phpfiles)
            .pipe(phpcs({
                bin             : '/usr/local/bin/phpcs',
                standard        : 'WordPress',
                warningSeverity : 0
            }))
            .pipe(phpcs.reporter('log'));
});

// update git submodules
gulp.task('updateSubmodules', function() {
    git.updateSubmodule({args: '--init'});
});

// COMMANDS --------------------------------------------------------------------
gulp.task('default', ['clean', 'img-build', 'css-watch', 'js-watch'], function() {
    // watch for changes
    gulp.watch(p.allfiles,          ['fileformat']);
    gulp.watch(p.stylus,            ['css-watch']);
    gulp.watch(p.srcJS + '*.js',    ['js-watch']);
});

// check code quality before git commit
gulp.task('precommit', ['sniffphp', 'js-format'], function() {
    gulp.src(p.srcJS + '*.js')
        .pipe(fixmyjs({                                                         // fix JSHint errors if possible
            lookup: false
        }))
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter(stylish));

    gulp.src(p.distCSS + '*.css')
        .pipe(csslint())
        .pipe(csslint.reporter());
});

// build project for release
gulp.task('build', ['clean', 'updateSubmodules'], function() {
    // TODO: git archive is the right option to export the entire repo
    gulp.start('img-build');
    gulp.start('css-build');
    gulp.start('js-build');
});
<commit_msg>#41 Now even with cleaned-up gulpfile<commit_after>var gulp    = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    del     = require('del'),
    p               = {
                        allfiles    : [
                                            './**/*.php',
                                            './**/*.phtml',
                                            './asset_sources/stylus/**/*.styl',
                                            './asset_sources/js/*.js'
                                      ],
                        phpfiles    : ['./**/*.php', '!./laterpay/library/**/*.php'],
                        srcStylus   : './asset_sources/stylus/*.styl',
                        srcJS       : './asset_sources/js/',
                        srcSVG      : './asset_sources/img/**/*.svg',
                        srcPNG      : './asset_sources/img/**/*.png',
                        distJS      : './res/js/',
                        distCSS     : './res/css/',
                        distIMG     : './res/img/',
                    };

// TASKS -----------------------------------------------------------------------
// clean up all files in the target directories
gulp.task('clean', function(cb) {
    del([p.distJS + '*.js', p.distCSS + '*.css'], cb);
});

// CSS related tasks
gulp.task('css-watch', function() {
    gulp.src(p.srcStylus)
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.stylus({                                                  // process Stylus sources to CSS
            use     : plugins.nib(),
            linenos : true,                                                     // make line numbers available in browser dev tools
        }))
        .pipe(plugins.sourcemaps.write('./maps'))                               // write sourcemaps
        .pipe(plugins.autoprefixer('last 3 versions', '> 2%', 'ff > 23', 'ie > 8')) // vendorize properties for supported browsers
        .on('error', plugins.notify.onError())
        .pipe(gulp.dest(p.distCSS));                                            // move to target folder
});

gulp.task('css-build', function() {
    gulp.src(p.srcStylus)
        .pipe(plugins.stylus({                                                  // process Stylus sources to CSS
            use     : plugins.nib(),
            compress: true
        }))
        .on('error', plugins.notify.onError())
        .pipe(plugins.autoprefixer('last 3 versions', '> 2%', 'ff > 23', 'ie > 8')) // vendorize properties for supported browsers
        .pipe(gulp.dest(p.distCSS));                                            // move to target folder
});

// Javascript related tasks
gulp.task('js-watch', function() {
    gulp.src(p.srcJS + '*.js')
        .pipe(plugins.cached('hinting'))                                        // only process modified files
            .pipe(plugins.jshint('.jshintrc'))
            .pipe(plugins.jshint.reporter(plugins.stylish))
            .pipe(plugins.sourcemaps.init())
            .pipe(plugins.sourcemaps.write('./maps'))                           // write sourcemaps
            .pipe(gulp.dest(p.distJS));                                         // move to target folder
});

gulp.task('js-build', function() {
    gulp.src(p.srcJS + '*.js')
        .pipe(plugins.jshint('.jshintrc'))
        .pipe(plugins.jshint.reporter(plugins.stylish))
        .pipe(plugins.uglify())                                                 // compress with uglify
        .pipe(gulp.dest(p.distJS));                                             // move to target folder
});

// Image related tasks
gulp.task('img-build', function() {
    gulp.src(p.srcSVG)
        .pipe(plugins.svgmin())                                                 // compress with svgmin
        .pipe(gulp.dest(p.distIMG));                                            // move to target folder

    gulp.src(p.srcPNG)
        .pipe(plugins.tinypng('-XMDmj3TW4Rymyizj1jcUXIvtc-uYJcM'))              // compress with TinyPNG
        .pipe(gulp.dest(p.distIMG));                                            // move to target folder
});

// update git submodules
gulp.task('updateSubmodules', function() {
    plugins.git.updateSubmodule({args: '--init'});
});

// COMMANDS --------------------------------------------------------------------
gulp.task('default', ['clean', 'img-build', 'css-watch', 'js-watch'], function() {
    // watch for changes
    gulp.watch(p.stylus,            ['css-watch']);
    gulp.watch(p.srcJS + '*.js',    ['js-watch']);
});

// build project for release
gulp.task('build', ['clean', 'updateSubmodules'], function() {
    // TODO: git archive is the right option to export the entire repo
    gulp.start('img-build');
    gulp.start('css-build');
    gulp.start('js-build');
});
<|endoftext|>


<commit_before>/* load command line arguments */
var args = require('yargs').argv;

/* load gulp */
var gulp = require('gulp');

/* load the plugins */
var gulpLoadPlugins    = require('gulp-load-plugins');
var plugins            = gulpLoadPlugins({ scope: ['devDependencies'] });
plugins.del            = require("del");
plugins.mainBowerFiles = require("main-bower-files");
plugins.pngcrush       = require('imagemin-pngcrush');

/* clean tasks */
gulp.task('clean:bower', function (cb) {
	return plugins.del(['dist/bower_components/*'],cb);
});

gulp.task('clean:css-patternlab', function (cb) {
	return plugins.del(['dist/css/patternlab/*'],cb);
});

gulp.task('clean:css-custom', function (cb) {
	return plugins.del(['dist/css/custom/*'],cb);
});

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

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

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

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

/* core tasks */
gulp.task('build:bower', ['clean:bower'], function(){
	return gulp.src(plugins.mainBowerFiles())
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest("dist/bower_components"))
		.pipe(gulp.dest("../../../public/styleguide/bower_components"));
});

gulp.task('build:css-general', function() {
	return gulp.src(['src/css/prism-okaidia.css'])
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-patternlab', ['clean:css-patternlab', 'build:css-general'], function() {
	return plugins.rubySass('src/sass/styleguide.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-custom', ['clean:css-custom'], function() {
	return plugins.rubySass('src/sass/styleguide-specific.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(gulp.dest('../../../source/styleguide/css'));
});

gulp.task('build:fonts', ['clean:fonts'], function() {
	return gulp.src('src/fonts/*')
		.pipe(gulp.dest('dist/fonts'))
		.pipe(gulp.dest('../../../public/styleguide/fonts'));
});

gulp.task('build:html', ['clean:html'], function() {
	return gulp.src('src/html/*')
		.pipe(gulp.dest('dist/html'))
		.pipe(gulp.dest('../../../public'));
});

gulp.task('build:images', ['clean:images'], function() {
	return gulp.src('src/images/*')
		.pipe(plugins.imagemin({
		          progressive: true,
		          svgoPlugins: [{removeViewBox: false}],
		          use: [plugins.pngcrush()]
		 }))
		.pipe(gulp.dest('dist/images'))
		.pipe(gulp.dest('../../../public/styleguide/images'));
});

gulp.task('build:js-viewer', ['clean:js'], function() {
	return gulp.src(['src/js/*.js','!src/js/annotations-pattern.js','!src/js/code-pattern.js','!src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-viewer.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('build:js-pattern', ['build:js-viewer'], function() {
	return gulp.src(['src/js/postmessage.js','src/js/annotations-pattern.js','src/js/code-pattern.js','src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-pattern.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('default', ['build:bower', 'build:css-custom', 'build:css-patternlab', 'build:fonts', 'build:html', 'build:images', 'build:js-pattern'], function () {

	if (args.watch !== undefined) {
		gulp.watch(['src/bower_components/**/*'], ['build:bower']);
		gulp.watch(['src/css/prism-okaidia.css'],['build:css-general']);
		gulp.watch(['src/sass/styleguide.scss'], ['build:css-patternlab']);
		gulp.watch(['src/sass/styleguide-specific.scss'], ['build:css-custom']);
		gulp.watch(['src/fonts/*'], ['build:fonts'])
		gulp.watch(['src/html/*'], ['build:html']);
		gulp.watch(['src/images/*'], ['build:images']);
		gulp.watch(['src/js/*'], ['build:js-pattern']);
	}

});
<commit_msg>Remove unused tasks<commit_after>/* load command line arguments */
var args = require('yargs').argv;

/* load gulp */
var gulp = require('gulp');

/* load the plugins */
var gulpLoadPlugins    = require('gulp-load-plugins');
var plugins            = gulpLoadPlugins({ scope: ['devDependencies'] });
plugins.del            = require("del");
plugins.mainBowerFiles = require("main-bower-files");
plugins.pngcrush       = require('imagemin-pngcrush');

/* clean tasks */
gulp.task('clean:bower', function (cb) {
	return plugins.del(['dist/bower_components/*'],cb);
});

gulp.task('clean:css-patternlab', function (cb) {
	return plugins.del(['dist/css/patternlab/*'],cb);
});

gulp.task('clean:css-custom', function (cb) {
	return plugins.del(['dist/css/custom/*'],cb);
});

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

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

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

/* core tasks */
gulp.task('build:bower', ['clean:bower'], function(){
	return gulp.src(plugins.mainBowerFiles())
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest("dist/bower_components"))
		.pipe(gulp.dest("../../../public/styleguide/bower_components"));
});

gulp.task('build:css-general', function() {
	return gulp.src(['src/css/prism-okaidia.css'])
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-patternlab', ['clean:css-patternlab', 'build:css-general'], function() {
	return plugins.rubySass('src/sass/styleguide.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/patternlab'))
		.pipe(gulp.dest('../../../public/styleguide/css'));
});

gulp.task('build:css-custom', ['clean:css-custom'], function() {
	return plugins.rubySass('src/sass/styleguide-specific.scss', { style: 'expanded', "sourcemap=none": true })
		.pipe(plugins.autoprefixer({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'android 4']}, {map: false }))
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.minifyCss())
		.pipe(gulp.dest('dist/css/custom'))
		.pipe(gulp.dest('../../../source/styleguide/css'));
});

gulp.task('build:fonts', ['clean:fonts'], function() {
	return gulp.src('src/fonts/*')
		.pipe(gulp.dest('dist/fonts'))
		.pipe(gulp.dest('../../../public/styleguide/fonts'));
});

gulp.task('build:html', ['clean:html'], function() {
	return gulp.src('src/html/*')
		.pipe(gulp.dest('dist/html'))
		.pipe(gulp.dest('../../../public'));
});

gulp.task('build:js-viewer', ['clean:js'], function() {
	return gulp.src(['src/js/*.js','!src/js/annotations-pattern.js','!src/js/code-pattern.js','!src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-viewer.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('build:js-pattern', ['build:js-viewer'], function() {
	return gulp.src(['src/js/postmessage.js','src/js/annotations-pattern.js','src/js/code-pattern.js','src/js/info-panel.js'])
		.pipe(plugins.jshint('.jshintrc'))
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.resolveDependencies( { pattern: /\* @requires [\s-]*(.*?\.js)/g } ))
		.on('error', function(err) { console.log(err.message); })
		.pipe(plugins.concat('patternlab-pattern.js'))
		.pipe(gulp.dest('dist/js'))
		.pipe(plugins.rename({suffix: '.min'}))
		.pipe(plugins.uglify())
		.pipe(gulp.dest('dist/js'))
		.pipe(gulp.dest('../../../public/styleguide/js'));
});

gulp.task('default', ['build:bower', 'build:css-custom', 'build:css-patternlab', 'build:fonts', 'build:html', 'build:js-pattern'], function () {

	if (args.watch !== undefined) {
		gulp.watch(['src/bower_components/**/*'], ['build:bower']);
		gulp.watch(['src/css/prism-okaidia.css'],['build:css-general']);
		gulp.watch(['src/sass/styleguide.scss'], ['build:css-patternlab']);
		gulp.watch(['src/sass/styleguide-specific.scss'], ['build:css-custom']);
		gulp.watch(['src/fonts/*'], ['build:fonts'])
		gulp.watch(['src/html/*'], ['build:html']);
		gulp.watch(['src/js/*'], ['build:js-pattern']);
	}

});
<|endoftext|>


<commit_before>'use strict';

require('mocha');

var chai = require('chai'),
    sinon = require('sinon'),
    expect = chai.expect,
    AuthTokenRefresh = require('../lib/refresh.js');

chai.use(require('sinon-chai'));

// Dummy OAuth2 object
function OAuth2(clientId, clientSecret, baseSite, authorizeUrl, accessTokenUrl) {
  this._accessTokenUrl = accessTokenUrl;
}

// Makes it easy to invocate in the specs
var newOAuth2 = function(accessTokenUrl) {
  return new OAuth2(null, null, null, null, accessTokenUrl);
};

describe('Auth token refresh', function() {

  beforeEach(function() {
    AuthTokenRefresh._strategies = {};
  });

  describe('use', function() {
    it('should add a strategy with an explicitly defined name', function() {
      var strategy = {
        name: 'internal_name',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use('explicit_name', strategy);

      expect(AuthTokenRefresh._strategies.explicit_name.strategy).to.equal(strategy);expect(AuthTokenRefresh._strategies.strategy).to.be.undefined;
    });

    it('should add a strategy without an explicitly defined name', function() {
      var strategy = {
        name: 'internal_name',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use(strategy);

      expect(AuthTokenRefresh._strategies.internal_name.strategy).to.equal(strategy);
    });

    it('should add a strategy with a refreshURL', function() {
      var strategy = {
        name: 'test_strategy',
        _refreshURL: 'refreshURL',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.strategy).to.equal(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2._accessTokenUrl).to.equal('refreshURL');
    });

    it('should add a strategy without a refreshURL', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.strategy).to.equal(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2._accessTokenUrl).to.equal('accessTokenUrl');
    });

    it('should create a new oauth2 object with the same prototype as the strategy\'s _oauth2 object', function() {
      var strategyOAuth2 = newOAuth2();
      var strategy = {
        name: 'test_strategy',
        _oauth2: strategyOAuth2
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2).to.not.equal(strategyOAuth2);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2).to.be.instanceof(OAuth2);

    });

    it('should not add a null strategy', function() {
      var strategy = null;
      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: strategy is null');
    });

    it('should not add a strategy with no name', function() {
      var strategy = {
        name: '',
        _oauth2: newOAuth2()
      };

      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: name must be specified, or strategy must include name');
    });

    it('should not add a non-OAuth 2.0 strategy', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: null
      };

      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: not an OAuth2 strategy');
    });
  });

  describe('has', function() {
    it('should return true if a strategy has been added', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh.has('test_strategy')).to.be.true;
    });

    it('should return false if a strategy has not been added', function() {
      expect(AuthTokenRefresh.has('test_strategy')).to.be.false;
    });
  });

  describe('request new access token', function() {
    it('should refresh an access token', function() {
      var getOAuthAccessTokenSpy = sinon.spy();
      var done = sinon.spy();

      AuthTokenRefresh._strategies = {
        test_strategy: {
          refreshOAuth2: {
            getOAuthAccessToken: getOAuthAccessTokenSpy
          }
        }
      };

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', done);

      expect(getOAuthAccessTokenSpy).to.have.been.calledWith('refresh_token', { grant_type: 'refresh_token' }, done);
    });

    it('should refresh a new access token with extra params', function() {
      var getOAuthAccessTokenSpy = sinon.spy();
      var done = sinon.spy();

      AuthTokenRefresh._strategies = {
        test_strategy: {
          refreshOAuth2: {
            getOAuthAccessToken: getOAuthAccessTokenSpy
          }
        }
      };

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', { some: 'extra_param' }, done);

      expect(getOAuthAccessTokenSpy).to.have.been.calledWith('refresh_token', { grant_type: 'refresh_token', some: 'extra_param' }, done);
    });

    it('should not refresh if the strategy was not previously registered', function() {
      var done = sinon.spy();
      var expectedErr = new Error('Strategy was not registered to refresh a token');

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', done);

      expect(done).to.have.been.calledWith(expectedErr);
    });
  });
});
<commit_msg>wrote tests for getOAuthAccessToken strategy overwrites<commit_after>'use strict';

require('mocha');

var chai = require('chai'),
    sinon = require('sinon'),
    expect = chai.expect,
    AuthTokenRefresh = require('../lib/refresh.js');

chai.use(require('sinon-chai'));

// Dummy OAuth2 object
function OAuth2(clientId, clientSecret, baseSite, authorizeUrl, accessTokenUrl) {
  this._accessTokenUrl = accessTokenUrl;
}

// Add dummy method
OAuth2.prototype.getOAuthAccessToken = new Function();

// Makes it easy to invocate in the specs
var newOAuth2 = function(accessTokenUrl) {
  return new OAuth2(null, null, null, null, accessTokenUrl);
};

describe('Auth token refresh', function() {

  beforeEach(function() {
    AuthTokenRefresh._strategies = {};
  });

  describe('use', function() {
    it('should add a strategy with an explicitly defined name', function() {
      var strategy = {
        name: 'internal_name',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use('explicit_name', strategy);

      expect(AuthTokenRefresh._strategies.explicit_name.strategy).to.equal(strategy);expect(AuthTokenRefresh._strategies.strategy).to.be.undefined;
    });

    it('should add a strategy without an explicitly defined name', function() {
      var strategy = {
        name: 'internal_name',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use(strategy);

      expect(AuthTokenRefresh._strategies.internal_name.strategy).to.equal(strategy);
    });

    it('should add a strategy with a refreshURL', function() {
      var strategy = {
        name: 'test_strategy',
        _refreshURL: 'refreshURL',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.strategy).to.equal(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2._accessTokenUrl).to.equal('refreshURL');
    });

    it('should add a strategy without a refreshURL', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.strategy).to.equal(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2._accessTokenUrl).to.equal('accessTokenUrl');
    });

    it('should create a new oauth2 object with the same prototype as the strategy\'s _oauth2 object', function() {
      var strategyOAuth2 = newOAuth2();
      var strategy = {
        name: 'test_strategy',
        _oauth2: strategyOAuth2
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2).to.not.equal(strategyOAuth2);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2).to.be.instanceof(OAuth2);

    });

    it('should not add a null strategy', function() {
      var strategy = null;
      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: strategy is null');
    });

    it('should not add a strategy with no name', function() {
      var strategy = {
        name: '',
        _oauth2: newOAuth2()
      };

      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: name must be specified, or strategy must include name');
    });

    it('should not add a non-OAuth 2.0 strategy', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: null
      };

      var fn = function() {
        AuthTokenRefresh.use(strategy);
      };

      expect(fn).to.throw(Error, 'Cannot register: not an OAuth2 strategy');
    });

    it('should use the default getOAuthAccessToken function if not overwritten by strategy', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2.getOAuthAccessToken).to.equal(OAuth2.prototype.getOAuthAccessToken);
    });

    it('should use the overwritten getOAuthAccessToken function if overwritten by strategy', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2('accessTokenUrl')
      };

      strategy._oauth2.getOAuthAccessToken = new Function();

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2.getOAuthAccessToken).to.equal(strategy._oauth2.getOAuthAccessToken);
      expect(AuthTokenRefresh._strategies.test_strategy.refreshOAuth2.getOAuthAccessToken).not.equal(OAuth2.prototype.getOAuthAccessToken);
    });
  });

  describe('has', function() {
    it('should return true if a strategy has been added', function() {
      var strategy = {
        name: 'test_strategy',
        _oauth2: newOAuth2()
      };

      AuthTokenRefresh.use(strategy);
      expect(AuthTokenRefresh.has('test_strategy')).to.be.true;
    });

    it('should return false if a strategy has not been added', function() {
      expect(AuthTokenRefresh.has('test_strategy')).to.be.false;
    });
  });

  describe('request new access token', function() {
    it('should refresh an access token', function() {
      var getOAuthAccessTokenSpy = sinon.spy();
      var done = sinon.spy();

      AuthTokenRefresh._strategies = {
        test_strategy: {
          refreshOAuth2: {
            getOAuthAccessToken: getOAuthAccessTokenSpy
          }
        }
      };

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', done);

      expect(getOAuthAccessTokenSpy).to.have.been.calledWith('refresh_token', { grant_type: 'refresh_token' }, done);
    });

    it('should refresh a new access token with extra params', function() {
      var getOAuthAccessTokenSpy = sinon.spy();
      var done = sinon.spy();

      AuthTokenRefresh._strategies = {
        test_strategy: {
          refreshOAuth2: {
            getOAuthAccessToken: getOAuthAccessTokenSpy
          }
        }
      };

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', { some: 'extra_param' }, done);

      expect(getOAuthAccessTokenSpy).to.have.been.calledWith('refresh_token', { grant_type: 'refresh_token', some: 'extra_param' }, done);
    });

    it('should not refresh if the strategy was not previously registered', function() {
      var done = sinon.spy();
      var expectedErr = new Error('Strategy was not registered to refresh a token');

      AuthTokenRefresh.requestNewAccessToken('test_strategy', 'refresh_token', done);

      expect(done).to.have.been.calledWith(expectedErr);
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>Disable gulp demo download<commit_after><|endoftext|>


<commit_before>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const babelMinify = require('babel-minify');

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, "utf8");
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(`[${fileName}]: before -> ${content.length}kb`)
	console.log(`[${fileName}]: after -> ${minifiedContent.length}kb`)
}
gulp.task('copyFiles', [], function() {
	gulp
		.src('src/lib/codemirror/theme/*')
		.pipe(gulp.dest('app/lib/codemirror/theme'));
	gulp
		.src('src/lib/codemirror/mode/**/*')
		.pipe(gulp.dest('app/lib/codemirror/mode'));
	gulp
		.src('src/lib/transpilers/*')
		.pipe(gulp.dest('app/lib/transpilers'));
	gulp.src('src/partials/*').pipe(gulp.dest('app/partials'));
	gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib'));
	gulp.src('src/icon-48.png').pipe(gulp.dest('app'));
	gulp
		.src([
			'src/FiraCode.ttf',
			'src/Fixedsys.ttf',
			'src/Inconsolata.ttf',
			'src/Monoid.ttf'
		])
		.pipe(gulp.dest('app'));
});

gulp.task('useRef', ['copyFiles'], function() {
	return gulp
		.src('src/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('minify', ['useRef'], function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');

	gulp.src('app/*.css')
		.pipe(cleanCSS({ debug: true }, (details) => {
			console.log(`${details.name}: ${details.stats.originalSize}`);
			console.log(`${details.name}: ${details.stats.minifiedSize}`);
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('generate-service-worker', ['minify'], function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`
		},
		callback
	);
});

gulp.task('default', ['generate-service-worker']);
<commit_msg>incrasemax file size for swcache<commit_after>/*eslint-env node*/

const fs = require('fs');
const gulp = require('gulp');
const useref = require('gulp-useref');
const cleanCSS = require('gulp-clean-css');
const babelMinify = require('babel-minify');

function minifyJs(fileName) {
	const content = fs.readFileSync(fileName, "utf8");
	const minifiedContent = babelMinify(content).code;
	fs.writeFileSync(fileName, minifiedContent);
	console.log(`[${fileName}]: before -> ${content.length}kb`)
	console.log(`[${fileName}]: after -> ${minifiedContent.length}kb`)
}
gulp.task('copyFiles', [], function() {
	gulp
		.src('src/lib/codemirror/theme/*')
		.pipe(gulp.dest('app/lib/codemirror/theme'));
	gulp
		.src('src/lib/codemirror/mode/**/*')
		.pipe(gulp.dest('app/lib/codemirror/mode'));
	gulp
		.src('src/lib/transpilers/*')
		.pipe(gulp.dest('app/lib/transpilers'));
	gulp.src('src/partials/*').pipe(gulp.dest('app/partials'));
	gulp.src('src/lib/screenlog.js').pipe(gulp.dest('app/lib'));
	gulp.src('src/icon-48.png').pipe(gulp.dest('app'));
	gulp
		.src([
			'src/FiraCode.ttf',
			'src/Fixedsys.ttf',
			'src/Inconsolata.ttf',
			'src/Monoid.ttf'
		])
		.pipe(gulp.dest('app'));
});

gulp.task('useRef', ['copyFiles'], function() {
	return gulp
		.src('src/index.html')
		.pipe(useref())
		.pipe(gulp.dest('app'));
});

gulp.task('minify', ['useRef'], function() {
	minifyJs('app/script.js');
	minifyJs('app/vendor.js');

	gulp.src('app/*.css')
		.pipe(cleanCSS({ debug: true }, (details) => {
			console.log(`${details.name}: ${details.stats.originalSize}`);
			console.log(`${details.name}: ${details.stats.minifiedSize}`);
		}))
		.pipe(gulp.dest('app'));
});

gulp.task('generate-service-worker', ['minify'], function(callback) {
	var swPrecache = require('sw-precache');
	var rootDir = 'app';

	swPrecache.write(
		`${rootDir}/service-worker.js`,
		{
			staticFileGlobs: [
				rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'
			],
			stripPrefix: `${rootDir}/`,

			// has to be increased to around 2.8mb for sass.worker.js
			maximumFileSizeToCacheInBytes: 2900000
		},
		callback
	);
});

gulp.task('default', ['generate-service-worker']);
<|endoftext|>


<commit_before>// Build file.
// Usage:
//
//    $ gulp
//
// See: https://github.com/prose/prose/issues/702

// Require dependencies.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var shell = require('gulp-shell');
var browserify = require('browserify');
var rename = require('gulp-rename');
var del = require('del');
var watch = require('gulp-watch');
var source = require('vinyl-source-stream');
var mkdirp = require('mkdirp');
var nodeJS = process.execPath;

// Scripts paths.
var paths = {
  vendorScripts: [
    'vendor/codemirror/codemirror.js',
    'vendor/codemirror/overlay.js',
    'vendor/codemirror/htmlmixed.js',
    'vendor/codemirror/clike.js',
    'vendor/codemirror/yaml.js',
    'vendor/codemirror/ruby.js',
    'vendor/codemirror/markdown.js',
    'vendor/codemirror/xml.js',
    'vendor/codemirror/javascript.js',
    'vendor/codemirror/css.js',
    'vendor/codemirror/gfm.js',
    'vendor/liquid.js'
  ],
  app: [
    'app/**/**/*.js'
  ],
  test: [
  'test/**/*.{js, json}',
  '!test/lib/index.js', // built test file
  '!test/lib/polyfill.js' // built test file.
  ],
  templates: [
    'templates/**/*.html'
  ]
};

// Removes `dist` folder.
gulp.task('clean', function (cb) {
  del(['dist'], cb);
});

// Translations.
// To run this task we have to have a `transifex.auth`
// file inside `translations` folder.
// Example file contents:
//
//  {
//    "user": "",
//    "pass": ""
//  }
//
// An account can be created at https://www.transifex.com/
//
gulp.task('translations', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        nodeJS + ' translations/update_locales',
        nodeJS + ' build'
      ])
    );
});

// Default tasks.
// ---------------------------

// Build templates.
gulp.task('templates', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        "\"" + nodeJS + "\"" + ' build'
      ])
    );
});

// Creates `dist` directory if not created and
// creates `oauth.json`.
gulp.task('oauth', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        '[ -f oauth.json ] && echo "Using existing oauth.json." || curl "https://raw.githubusercontent.com/prose/prose/gh-pages/oauth.json" > oauth.json'
      ])
    );
});

// Concatenate vendor scripts into dist/vendor.js
gulp.task('vendor', function() {
  gulp.src(paths.vendorScripts)
  .pipe(concat('vendor.js'))
  .pipe(gulp.dest('dist/'));
})

// Build tests.
gulp.task('build-tests', ['templates', 'oauth', 'vendor'], function() {

  // Browserify polyfill-require.js
  // Pass `debug` option to enable source maps.
  browserify({debug:true})
    .add('./test/lib/polyfill-require.js')
    .require('./test/lib/sourcemap-hack', {expose: 'sourcemap-hack'})
    .bundle()
    .pipe(source('polyfill.js'))
    .pipe(gulp.dest('./test/lib/'));

  // Browserify index.js
  // Pass `debug` option to enable source maps.
  return browserify({debug: true})
    .add('./test/index.js')
    .external(['chai', 'mocha'])
    .bundle()
    .pipe(source('index.js')) // Output file.
    .pipe(gulp.dest('./test/lib/')); // Output folder.

});

// Browserify app scripts, then concatenate with vendor scripts into `prose.js`.
gulp.task('build-app', ['templates', 'oauth', 'vendor'], function() {

  // Browserify app scripts.
  return browserify({debug: true})
    .add('./app/boot.js')
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./dist/'))

    // Concatenate scripts once browserify finishes.
    .on('end', function() {

      // Concatenate `vendor` and `app` scripts into `prose.js`.
      return gulp.src(['dist/vendor.js', 'dist/app.js'])
        .pipe(concat('prose.js'))
        .pipe(gulp.dest('dist/'));
    });

});

// Compress `prose.js`.
gulp.task('uglify', ['build-app'], function() {

  return gulp.src('dist/prose.js')
    .pipe(rename('prose.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

// Watch for changes in `app` scripts.
// Usage:
//
//    $ gulp watch
//
gulp.task('watch', ['build-app', 'build-tests'], function() {
  // Watch any `.js` file under `app` folder.
  gulp.watch(paths.app, ['build-app', 'build-tests']);
  gulp.watch(paths.test, ['build-tests']);
  gulp.watch(paths.templates, ['build-app']);
});

gulp.task('run-tests', ['build-tests'], shell.task([
  './node_modules/.bin/mocha-phantomjs test/index.html'
], {ignoreErrors: true}));

// Like watch, but actually run the tests whenever anything changes.
gulp.task('test', ['run-tests'], function() {
  gulp.watch([paths.app, paths.test, paths.templates], ['run-tests'])
});

// Default task which builds the project when we
// run `gulp` from the command line.
gulp.task('default', ['build-tests', 'build-app', 'uglify']);
<commit_msg>Removing debug as it throws off sourcemapping<commit_after>// Build file.
// Usage:
//
//    $ gulp
//
// See: https://github.com/prose/prose/issues/702

// Require dependencies.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var shell = require('gulp-shell');
var browserify = require('browserify');
var rename = require('gulp-rename');
var del = require('del');
var watch = require('gulp-watch');
var source = require('vinyl-source-stream');
var mkdirp = require('mkdirp');
var nodeJS = process.execPath;

// Scripts paths.
var paths = {
  vendorScripts: [
    'vendor/codemirror/codemirror.js',
    'vendor/codemirror/overlay.js',
    'vendor/codemirror/htmlmixed.js',
    'vendor/codemirror/clike.js',
    'vendor/codemirror/yaml.js',
    'vendor/codemirror/ruby.js',
    'vendor/codemirror/markdown.js',
    'vendor/codemirror/xml.js',
    'vendor/codemirror/javascript.js',
    'vendor/codemirror/css.js',
    'vendor/codemirror/gfm.js',
    'vendor/liquid.js'
  ],
  app: [
    'app/**/**/*.js'
  ],
  test: [
  'test/**/*.{js, json}',
  '!test/lib/index.js', // built test file
  '!test/lib/polyfill.js' // built test file.
  ],
  templates: [
    'templates/**/*.html'
  ]
};

// Removes `dist` folder.
gulp.task('clean', function (cb) {
  del(['dist'], cb);
});

// Translations.
// To run this task we have to have a `transifex.auth`
// file inside `translations` folder.
// Example file contents:
//
//  {
//    "user": "",
//    "pass": ""
//  }
//
// An account can be created at https://www.transifex.com/
//
gulp.task('translations', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        nodeJS + ' translations/update_locales',
        nodeJS + ' build'
      ])
    );
});

// Default tasks.
// ---------------------------

// Build templates.
gulp.task('templates', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        "\"" + nodeJS + "\"" + ' build'
      ])
    );
});

// Creates `dist` directory if not created and
// creates `oauth.json`.
gulp.task('oauth', function () {
  mkdirp('dist');
  return gulp.src('')
    .pipe(
      shell([
        '[ -f oauth.json ] && echo "Using existing oauth.json." || curl "https://raw.githubusercontent.com/prose/prose/gh-pages/oauth.json" > oauth.json'
      ])
    );
});

// Concatenate vendor scripts into dist/vendor.js
gulp.task('vendor', function() {
  gulp.src(paths.vendorScripts)
  .pipe(concat('vendor.js'))
  .pipe(gulp.dest('dist/'));
})

// Build tests.
gulp.task('build-tests', ['templates', 'oauth', 'vendor'], function() {

  // Browserify polyfill-require.js
  // Pass `debug` option to enable source maps.
  browserify({debug:true})
    .add('./test/lib/polyfill-require.js')
    .require('./test/lib/sourcemap-hack', {expose: 'sourcemap-hack'})
    .bundle()
    .pipe(source('polyfill.js'))
    .pipe(gulp.dest('./test/lib/'));

  // Browserify index.js
  // Pass `debug` option to enable source maps.
  return browserify({debug: true})
    .add('./test/index.js')
    .external(['chai', 'mocha'])
    .bundle()
    .pipe(source('index.js')) // Output file.
    .pipe(gulp.dest('./test/lib/')); // Output folder.

});

// Browserify app scripts, then concatenate with vendor scripts into `prose.js`.
gulp.task('build-app', ['templates', 'oauth', 'vendor'], function() {

  // Browserify app scripts.
  return browserify()
    .add('./app/boot.js')
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./dist/'))

    // Concatenate scripts once browserify finishes.
    .on('end', function() {

      // Concatenate `vendor` and `app` scripts into `prose.js`.
      return gulp.src(['dist/vendor.js', 'dist/app.js'])
        .pipe(concat('prose.js'))
        .pipe(gulp.dest('dist/'));
    });

});

// Compress `prose.js`.
gulp.task('uglify', ['build-app'], function() {

  return gulp.src('dist/prose.js')
    .pipe(rename('prose.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

// Watch for changes in `app` scripts.
// Usage:
//
//    $ gulp watch
//
gulp.task('watch', ['build-app', 'build-tests'], function() {
  // Watch any `.js` file under `app` folder.
  gulp.watch(paths.app, ['build-app', 'build-tests']);
  gulp.watch(paths.test, ['build-tests']);
  gulp.watch(paths.templates, ['build-app']);
});

gulp.task('run-tests', ['build-tests'], shell.task([
  './node_modules/.bin/mocha-phantomjs test/index.html'
], {ignoreErrors: true}));

// Like watch, but actually run the tests whenever anything changes.
gulp.task('test', ['run-tests'], function() {
  gulp.watch([paths.app, paths.test, paths.templates], ['run-tests'])
});

// Default task which builds the project when we
// run `gulp` from the command line.
gulp.task('default', ['build-tests', 'build-app', 'uglify']);
<|endoftext|>


<commit_before><commit_msg>Updated included scss paths<commit_after><|endoftext|>