<commit_before>/*eslint-env node */

// npm install --save-dev gulp gulp-sourcemaps gulp-sass gulp-webdriver gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css chai gulp-spawn-mocha sinon sinon-chai jsdom

var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var argv = require('yargs').argv;
var webdriver = require('gulp-webdriver');
var connect = require('gulp-connect');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');

// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */

// Load the manifest as JSON
var manifest = require('./src/manifest');

// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";

//
// Replacements config for gulp-replace
//
// 1.  Sets debug: false (in utils.js)
// 2.  Removes Logger statements
// 3.  Remove everything in .js files between "// REMOVE START" and "REMOVE END"
//     These blocks contain development code that gets optimized away
// 4.  Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
//     These blocks contain development code that gets optimized away
// 5.  Activate blocks between "<!-- BUILD START" and "BUILD END -->"
//     These contain the optimized files for the final build
// 6.  Remove the "js:" array from the manifest
//     These blocks contain development code that gets optimized away
// 7.  Remove the "scripts:" array from the manifest
//     These blocks contain development code that gets optimized away
// 8.  Rename the "jsBuild" part in the manifest to be the "js" part
//     These contain the optimized files for the final build
// 9.  Rename the "scriptsBuild" part in the manifest to be the "scripts" part
//     These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
// 11. Replaces the local reference URL to the tutorial site with the live one
var replaceOpts = {
  preserveOrder: true,
  patterns: [
    {
      match: /debug\s*:\s*true,/g,
      replacement: "debug: false,"
    },
    {
      match: /.*Logger.*/g,
      replacement: ""
    },
    {
      match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
      replacement: ""
    },
    {
      match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
      replacement: ""
    },
    {
      match: /<!-- BUILD START/g,
      replacement: ""
    },
    {
      match: /BUILD END -->/g,
      replacement: ""
    },
    {
      match: /^.*"js":[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /^.*"scripts"[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /"jsBuild"/g,
      replacement: "\"js\""
    },
    {
      match: /"scriptsBuild"/g,
      replacement: "\"scripts\""
    },
    {
      match: /##VERSION##/g,
      replacement: manifest.version
    },
    {
      match: /href="http:\/\/localhost:4000\//g,
      replacement: "href=\"http://form-o-fill.github.io/"
    }

  ]
};

// Helper to run all tests thru mocha
var runTests = function() {
  return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
    R: 'dot',
    c: true,
    debug: true
  })).on('error', console.warn.bind(console));
};

//
// Output which version to build where to
//
gulp.task('announce', function() {
  gulpUtil.log(
    'Building version', chalk.cyan(manifest.version),
    'of', chalk.cyan(manifest.name),
    'as', chalk.cyan("dist/" + distFilename)
  );
});

//
// Cleans build and dist dirs
//
gulp.task('clean', ["announce"], function() {
  return gulp.src(['build/**'], {read: false})
  .pipe(rm({async: false}));
});

//
// ESLINT the javascript (BEFORE uglifier ran over them)
//
gulp.task('lint', function () {
  return gulp.src(['src/js/**/*.js'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failOnError());
});

//
// Optimize CSS
//
gulp.task('optimizeCss', ['clean'], function () {

  // Optimize main options.css
  gulp.src(["src/vendor/intro.js/introjs.min.css", "src/css/*.css", "!src/css/content.css", "!src/css/popup.css"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('options.css'))
  .pipe(minifyCSS())
  .pipe(gulp.dest('build/css/'));

  // optimize content and popup css
  return gulp.src(['src/css/content.css', 'src/css/popup.css'])
  .pipe(minifyCSS())
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build/css'));
});

//
// Build global.js
// Sadly until I use require.js here the order is important :(
//
gulp.task('globalJs', ['clean'], function () {
  return gulp.src([
    "src/js/global/utils.js",
    "src/js/global/jsonf.js",
    "src/js/global/storage.js",
    "src/js/global/rule.js",
    "src/js/global/rules.js",
    "src/js/global/i18n.js",
    "src/js/global/libs.js",
    "src/js/global/workflow.js"
  ])
  .pipe(replace(replaceOpts))
  .pipe(concat('global.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build background.js
//
gulp.task('backgroundJs', ['clean'], function () {
  return gulp.src("src/js/background/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('background.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build content.js
//
gulp.task('contentJs', ['clean'], function () {
  return gulp.src("src/js/content/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('content.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build options.js
//
gulp.task('optionsJs', ['clean'], function () {
  return gulp.src(["src/js/options/*.js", "!src/js/options/logs.js"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('options.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build popup.js
//
gulp.task('popupJs', ['clean'], function () {
  return gulp.src("src/js/popup.js")
  .pipe(replace(replaceOpts))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js'));
});

//
// Copies files that can be copied without changes
//
gulp.task('copyUnchanged', ['clean'], function() {
  ["fonts", "images", "vendor", "_locales"].forEach(function (dir) {
    gulp.src('src/' + dir + '/**/*', { nonegate: false })
    .pipe(gulp.dest('build/' + dir));
  });
});

//
// Copies HTML files and removes comment and blocks (see above)
//
gulp.task('copyHtml', ['copyUnchanged'], function() {
  return gulp.src(['src/html/**/*.html', '!src/html/options/_logs_*.html'], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(cleanhtml())
  .pipe(gulp.dest('build/html'));
});

//
// Copies and replaces the manifest.json file (see above)
//
gulp.task('mangleManifest', [ 'clean' ], function() {
  return gulp.src('src/manifest.json')
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build'));
});

//
// SASS -> CSS
// Output is expanded since it will be compressed if
// running 'build'
gulp.task('sass', function () {
  gulp.src('src/sass/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: "expanded"}).on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('src/css'));
});

//
// Watch and live compile SASS -> CSS
//
gulp.task('sass:watch', function () {
  gulp.watch('src/sass/*.scss', ['sass']);
});

//
// Build a distribution
//
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'sass', 'optimizeCss', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
  gulp.src(['build/**'])
  .pipe(zip(distFilename))
  .pipe(gulp.dest('dist'));
});

//
// Run tests
//
gulp.task('test', function () {
  gulpUtil.log('Running tests');
  return runTests().on('error', function (e) {
    throw e;
  });
});

//
// Run tests through watching
//
gulp.task('test:watch', function () {
  gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});

//
// Starts a simple webserver hosting the integration test files
//
gulp.task('webserver:start', function() {
  connect.server({
    root: "testcases/docroot-for-testing",
    livereload: false,
    port: 9292
  });
});

//
// Kills the server (for integration tests)
//
gulp.task('webserver:stop', connect.serverClose);

gulp.task("integration", [ "webserver:start", "integration:run" ], function() {
  connect.serverClose();
});

// Integration testing (end-to-end)
// Uses webdriverio as an abstraction layer over chromedriver
//
// You can specify a single spec to run via:
// gulp integration --spec test/integration/some_spec_scene.js
//
// Specify a single spec with
// gulp integration --grep "a\sregex"
gulp.task('integration:run', [ "webserver:start" ], function () {

  var specs = [
    "./test/integration/test_setup_scene.js",
    "./test/integration/all_types_scene.js",
    "./test/integration/form_filling_scene.js",
    "./test/integration/shared_rules_scene.js",
    "./test/integration/popup_scene.js",
    "./test/integration/form_extraction_scene.js",
    "./test/integration/options_scene.js"
  ];

  // Allow --spec parameter
  if (argv.spec) {
    specs = [argv.spec];
  }

  var mochaOpts = {
    R: 'spec',
    c: true,
    debug: false,
    inlineDiffs: true
  };

  // Allow --grep as mocha opt
  if (argv.grep) {
    mochaOpts.grep = argv.grep;
  }

  return gulp.src(specs, {read: false})
  .pipe(webdriver({desiredCapabilities: {
    browserName: "chrome"
  }}));
});

//
// DEFAULT
// running "gulp" will execute this
//
gulp.task('default', function () {
  runTests();
});
<commit_msg>fixed order for option.js build step<commit_after>/*eslint-env node */

// npm install --save-dev gulp gulp-sourcemaps gulp-sass gulp-webdriver gulp-util chalk gulp-replace-task gulp-cleanhtml gulp-strip-debug gulp-concat gulp-uglify gulp-rm gulp-zip gulp-eslint through2 gulp-minify-css chai gulp-spawn-mocha sinon sinon-chai jsdom

var chalk = require('chalk');
var cleanhtml = require('gulp-cleanhtml');
var concat = require('gulp-concat');
var eslint = require('gulp-eslint');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var minifyCSS = require('gulp-minify-css');
var mocha = require('gulp-spawn-mocha');
var replace = require('gulp-replace-task');
var rm = require('gulp-rm');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var argv = require('yargs').argv;
var webdriver = require('gulp-webdriver');
var connect = require('gulp-connect');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');

// this can be used to debug gulp runs
// .pipe(debug({verbose: true}))
/*eslint-disable no-unused-vars */
var debug = require('gulp-debug');
/*eslint-enable no-unused-vars */

// Load the manifest as JSON
var manifest = require('./src/manifest');

// The final .zip filename that gets uploaded to https://chrome.google.com/webstore/developer/dashboard
var distFilename = manifest.name.replace(/[ ]/g, "_").toLowerCase() + "-v-" + manifest.version + ".zip";

//
// Replacements config for gulp-replace
//
// 1.  Sets debug: false (in utils.js)
// 2.  Removes Logger statements
// 3.  Remove everything in .js files between "// REMOVE START" and "REMOVE END"
//     These blocks contain development code that gets optimized away
// 4.  Remove everything in .html files between "<!-- REMOVE START" and "REMOVE END -->"
//     These blocks contain development code that gets optimized away
// 5.  Activate blocks between "<!-- BUILD START" and "BUILD END -->"
//     These contain the optimized files for the final build
// 6.  Remove the "js:" array from the manifest
//     These blocks contain development code that gets optimized away
// 7.  Remove the "scripts:" array from the manifest
//     These blocks contain development code that gets optimized away
// 8.  Rename the "jsBuild" part in the manifest to be the "js" part
//     These contain the optimized files for the final build
// 9.  Rename the "scriptsBuild" part in the manifest to be the "scripts" part
//     These contain the optimized files for the final build
// 10. Replace ##VERSION## with the correct version string from the manifest
// 11. Replaces the local reference URL to the tutorial site with the live one
var replaceOpts = {
  preserveOrder: true,
  patterns: [
    {
      match: /debug\s*:\s*true,/g,
      replacement: "debug: false,"
    },
    {
      match: /.*Logger.*/g,
      replacement: ""
    },
    {
      match: /^.*\/\/ REMOVE START[\s\S]*?\/\/ REMOVE END.*$/gm,
      replacement: ""
    },
    {
      match: /<!-- REMOVE START[\s\S]*?REMOVE END -->/gm,
      replacement: ""
    },
    {
      match: /<!-- BUILD START/g,
      replacement: ""
    },
    {
      match: /BUILD END -->/g,
      replacement: ""
    },
    {
      match: /^.*"js":[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /^.*"scripts"[\s\S]*?\],.*$/gm,
      replacement: ""
    },
    {
      match: /"jsBuild"/g,
      replacement: "\"js\""
    },
    {
      match: /"scriptsBuild"/g,
      replacement: "\"scripts\""
    },
    {
      match: /##VERSION##/g,
      replacement: manifest.version
    },
    {
      match: /href="http:\/\/localhost:4000\//g,
      replacement: "href=\"http://form-o-fill.github.io/"
    }

  ]
};

// Helper to run all tests thru mocha
var runTests = function() {
  return gulp.src(['test/**/*_spec.js'], {read: false}).pipe(mocha({
    R: 'dot',
    c: true,
    debug: true
  })).on('error', console.warn.bind(console));
};

//
// Output which version to build where to
//
gulp.task('announce', function() {
  gulpUtil.log(
    'Building version', chalk.cyan(manifest.version),
    'of', chalk.cyan(manifest.name),
    'as', chalk.cyan("dist/" + distFilename)
  );
});

//
// Cleans build and dist dirs
//
gulp.task('clean', ["announce"], function() {
  return gulp.src(['build/**'], {read: false})
  .pipe(rm({async: false}));
});

//
// ESLINT the javascript (BEFORE uglifier ran over them)
//
gulp.task('lint', function () {
  return gulp.src(['src/js/**/*.js'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failOnError());
});

//
// Optimize CSS
//
gulp.task('optimizeCss', ['clean'], function () {

  // Optimize main options.css
  gulp.src(["src/vendor/intro.js/introjs.min.css", "src/css/*.css", "!src/css/content.css", "!src/css/popup.css"], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(concat('options.css'))
  .pipe(minifyCSS())
  .pipe(gulp.dest('build/css/'));

  // optimize content and popup css
  return gulp.src(['src/css/content.css', 'src/css/popup.css'])
  .pipe(minifyCSS())
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build/css'));
});

//
// Build global.js
// Sadly until I use require.js here the order is important :(
//
gulp.task('globalJs', ['clean'], function () {
  return gulp.src([
    "src/js/global/utils.js",
    "src/js/global/jsonf.js",
    "src/js/global/storage.js",
    "src/js/global/rule.js",
    "src/js/global/rules.js",
    "src/js/global/i18n.js",
    "src/js/global/libs.js",
    "src/js/global/workflow.js"
  ])
  .pipe(replace(replaceOpts))
  .pipe(concat('global.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build background.js
//
gulp.task('backgroundJs', ['clean'], function () {
  return gulp.src("src/js/background/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('background.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build content.js
//
gulp.task('contentJs', ['clean'], function () {
  return gulp.src("src/js/content/*.js")
  .pipe(replace(replaceOpts))
  .pipe(concat('content.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build options.js
//
gulp.task('optionsJs', ['clean'], function () {
  return gulp.src([
    "src/js/options/editor.js",
    "src/js/options/chrome_bootstrap.js",
    "src/js/options/tabs.js",
    "src/js/options/import_export.js",
    "src/js/options/tutorial.js",
    "src/js/options/options.js",
    "src/js/options/help.js",
    "src/js/options/workflow.js"
  ])
  .pipe(replace(replaceOpts))
  .pipe(concat('options.js'))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js/'));
});

//
// Build popup.js
//
gulp.task('popupJs', ['clean'], function () {
  return gulp.src("src/js/popup.js")
  .pipe(replace(replaceOpts))
  .pipe(stripdebug())
  .pipe(uglify())
  .pipe(gulp.dest('build/js'));
});

//
// Copies files that can be copied without changes
//
gulp.task('copyUnchanged', ['clean'], function() {
  ["fonts", "images", "vendor", "_locales"].forEach(function (dir) {
    gulp.src('src/' + dir + '/**/*', { nonegate: false })
    .pipe(gulp.dest('build/' + dir));
  });
});

//
// Copies HTML files and removes comment and blocks (see above)
//
gulp.task('copyHtml', ['copyUnchanged'], function() {
  return gulp.src(['src/html/**/*.html', '!src/html/options/_logs_*.html'], { nonegate: false })
  .pipe(replace(replaceOpts))
  .pipe(cleanhtml())
  .pipe(gulp.dest('build/html'));
});

//
// Copies and replaces the manifest.json file (see above)
//
gulp.task('mangleManifest', [ 'clean' ], function() {
  return gulp.src('src/manifest.json')
  .pipe(replace(replaceOpts))
  .pipe(gulp.dest('build'));
});

//
// SASS -> CSS
// Output is expanded since it will be compressed if
// running 'build'
gulp.task('sass', function () {
  gulp.src('src/sass/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: "expanded"}).on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('src/css'));
});

//
// Watch and live compile SASS -> CSS
//
gulp.task('sass:watch', function () {
  gulp.watch('src/sass/*.scss', ['sass']);
});

//
// Build a distribution
//
gulp.task('build', ['announce', 'clean', 'test', 'lint', 'copyHtml', 'sass', 'optimizeCss', 'globalJs', 'backgroundJs', 'contentJs', 'optionsJs', 'popupJs', 'mangleManifest'], function() {
  gulp.src(['build/**'])
  .pipe(zip(distFilename))
  .pipe(gulp.dest('dist'));
});

//
// Run tests
//
gulp.task('test', function () {
  gulpUtil.log('Running tests');
  return runTests().on('error', function (e) {
    throw e;
  });
});

//
// Run tests through watching
//
gulp.task('test:watch', function () {
  gulp.watch(['src/js/**/*.js', 'test/**/*.js'], runTests);
});

//
// Starts a simple webserver hosting the integration test files
//
gulp.task('webserver:start', function() {
  connect.server({
    root: "testcases/docroot-for-testing",
    livereload: false,
    port: 9292
  });
});

//
// Kills the server (for integration tests)
//
gulp.task('webserver:stop', connect.serverClose);

gulp.task("integration", [ "webserver:start", "integration:run" ], function() {
  connect.serverClose();
});

// Integration testing (end-to-end)
// Uses webdriverio as an abstraction layer over chromedriver
//
// You can specify a single spec to run via:
// gulp integration --spec test/integration/some_spec_scene.js
//
// Specify a single spec with
// gulp integration --grep "a\sregex"
gulp.task('integration:run', [ "webserver:start" ], function () {

  var specs = [
    "./test/integration/test_setup_scene.js",
    "./test/integration/all_types_scene.js",
    "./test/integration/form_filling_scene.js",
    "./test/integration/shared_rules_scene.js",
    "./test/integration/popup_scene.js",
    "./test/integration/form_extraction_scene.js",
    "./test/integration/options_scene.js"
  ];

  // Allow --spec parameter
  if (argv.spec) {
    specs = [argv.spec];
  }

  var mochaOpts = {
    R: 'spec',
    c: true,
    debug: false,
    inlineDiffs: true
  };

  // Allow --grep as mocha opt
  if (argv.grep) {
    mochaOpts.grep = argv.grep;
  }

  return gulp.src(specs, {read: false})
  .pipe(webdriver({desiredCapabilities: {
    browserName: "chrome"
  }}));
});

//
// DEFAULT
// running "gulp" will execute this
//
gulp.task('default', function () {
  runTests();
});
<|endoftext|>


<commit_before><commit_msg>fix gulpfile<commit_after><|endoftext|>


<commit_before>var gulp = require('gulp'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    del = require('del'),
    fs = require('fs'),
    path = require('path'),
    s = require('underscore.string'),
    argv = require('yargs').argv,
    urljoin = require('url-join'),
    logger = require('js-logger'),
    hawtio = require('hawtio-node-backend');

var plugins = gulpLoadPlugins({});
var pkg = require('./package.json');

var config = {
  proxyPort: argv.port || 8181,
  targetPath: argv.path || '/jolokia',
  logLevel: argv.debug ? logger.DEBUG : logger.INFO,
  main: '.',
  ts: ['plugins/**/*.ts'],
  templates: ['plugins/**/*.html'],
  less: ['plugins/**/*.less', 'vendor/**/*.less', 'vendor/**/*.css'],
  templateModule: pkg.name + '-templates',
  dist: argv.out || './dist/',
  js: pkg.name + '.js',
  css: pkg.name + '.css',
  tsProject: plugins.typescript.createProject({
    target: 'ES5',
    module: 'commonjs',
    declarationFiles: true,
    noResolve: false
  }),
  sourceMap: argv.sourcemap
};

gulp.task('bower', function() {
  return gulp.src('index.html')
    .pipe(wiredep({}))
    .pipe(gulp.dest('.'));
});

/** Adjust the reference path of any typescript-built plugin this project depends on */
gulp.task('path-adjust', function() {
  return gulp.src('libs/**/includes.d.ts')
    .pipe(plugins.replace(/"\.\.\/libs/gm, '"../../../libs'))
    .pipe(gulp.dest('libs'));
});

gulp.task('clean-defs', function() {
  return del('defs.d.ts');
});

gulp.task('tsc', ['clean-defs'], function() {
  var cwd = process.cwd();
  var tsResult = gulp.src(config.ts)
    .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.init()))
    .pipe(plugins.typescript(config.tsProject));

  return eventStream.merge(
    tsResult.js
      .pipe(plugins.concat('compiled.js'))
      .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.write()))
      .pipe(gulp.dest('.')),
    tsResult.dts
      .pipe(gulp.dest('d.ts')))
    .pipe(plugins.filter('**/*.d.ts'))
    .pipe(plugins.concatFilenames('defs.d.ts', {
      root: cwd,
      prepend: '/// <reference path="',
      append: '"/>'
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('template', ['tsc'], function() {
  return gulp.src(config.templates)
    .pipe(plugins.angularTemplatecache({
      filename: 'templates.js',
      root: 'plugins/',
      standalone: true,
      module: config.templateModule,
      templateFooter: '}]); hawtioPluginLoader.addModule("' + config.templateModule + '");'
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('concat', ['template'], function() {
  return gulp.src(['compiled.js', 'templates.js', 'vendor/**/*.js'])
    .pipe(plugins.concat(config.js))
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', ['concat'], function() {
  return del(['templates.js', 'compiled.js']);
});

gulp.task('less', function () {
  return gulp.src(config.less)
    .pipe(plugins.less({
      paths: [path.join(__dirname, 'plugins'), path.join(__dirname, 'libs')]
    }))
    .pipe(plugins.concat(config.css))
    .pipe(gulp.dest(config.dist));
});

gulp.task('watch-less', function() {
  plugins.watch(config.less, function() {
    gulp.start('less');
  });
});

gulp.task('watch', ['build', 'watch-less'], function() {
  plugins.watch(['libs/**/*.js', 'libs/**/*.css', 'index.html', urljoin(config.dist, '*')], function() {
    gulp.start('reload');
  });
  plugins.watch(['libs/**/*.d.ts', config.ts, config.templates], function() {
    gulp.start(['tsc', 'template', 'concat', 'clean']);
  });
});

gulp.task('connect', ['watch'], function() {
  hawtio.setConfig({
    logLevel: config.logLevel,
    port: 2772,
    staticProxies: [{
      port: config.proxyPort,
      path: '/jolokia',
      targetPath: config.targetPath
    }],
    staticAssets: [{
      path: '/',
      dir: '.'

    }],
    fallback: 'index.html',
    liveReload: {
      enabled: true
    }
  });
  hawtio.use('/', function(req, res, next) {
          var path = req.originalUrl;
          // avoid returning these files, they should get pulled from js
          if (s.startsWith(path, '/plugins/') && s.endsWith(path, 'html')) {
            if (argv.debug) {
              console.log("returning 404 for: ", path);
            }
            res.statusCode = 404;
            res.end();
          } else {
            if (argv.debug) {
              console.log("allowing: ", path);
            }
            next();
          }
        });
  hawtio.listen(function(server) {
    var host = server.address().address;
    var port = server.address().port;
    console.log("started from gulp file at ", host, ":", port);
  });
});

gulp.task('reload', function() {
  gulp.src('.')
    .pipe(hawtio.reload());
});

gulp.task('build', ['bower', 'path-adjust', 'tsc', 'less', 'template', 'concat', 'clean']);

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

<commit_msg>Multiple compiled JS files concatenation does not work with gulp-typescript 3.x<commit_after>var gulp = require('gulp'),
    wiredep = require('wiredep').stream,
    eventStream = require('event-stream'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    del = require('del'),
    fs = require('fs'),
    path = require('path'),
    s = require('underscore.string'),
    argv = require('yargs').argv,
    urljoin = require('url-join'),
    logger = require('js-logger'),
    hawtio = require('hawtio-node-backend');

var plugins = gulpLoadPlugins({});
var pkg = require('./package.json');

var config = {
  proxyPort: argv.port || 8181,
  targetPath: argv.path || '/jolokia',
  logLevel: argv.debug ? logger.DEBUG : logger.INFO,
  main: '.',
  ts: ['plugins/**/*.ts'],
  templates: ['plugins/**/*.html'],
  less: ['plugins/**/*.less', 'vendor/**/*.less', 'vendor/**/*.css'],
  templateModule: pkg.name + '-templates',
  dist: argv.out || './dist/',
  js: pkg.name + '.js',
  css: pkg.name + '.css',
  tsProject: plugins.typescript.createProject({
    target: 'ES5',
    outFile: 'compiled.js',
    declaration: true,
    noResolve: false
  }),
  sourceMap: argv.sourcemap
};

gulp.task('bower', function() {
  return gulp.src('index.html')
    .pipe(wiredep({}))
    .pipe(gulp.dest('.'));
});

/** Adjust the reference path of any typescript-built plugin this project depends on */
gulp.task('path-adjust', function() {
  return gulp.src('libs/**/includes.d.ts')
    .pipe(plugins.replace(/"\.\.\/libs/gm, '"../../../libs'))
    .pipe(gulp.dest('libs'));
});

gulp.task('clean-defs', function() {
  return del('defs.d.ts');
});

gulp.task('tsc', ['clean-defs'], function() {
  var cwd = process.cwd();
  var tsResult = gulp.src(config.ts)
    .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.init()))
    .pipe(plugins.typescript(config.tsProject()));

  return eventStream.merge(
    tsResult.js
      .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.write()))
      .pipe(gulp.dest('.')),
    tsResult.dts
      .pipe(plugins.rename('defs.d.ts'))
      .pipe(gulp.dest('.')));
});

gulp.task('template', ['tsc'], function() {
  return gulp.src(config.templates)
    .pipe(plugins.angularTemplatecache({
      filename: 'templates.js',
      root: 'plugins/',
      standalone: true,
      module: config.templateModule,
      templateFooter: '}]); hawtioPluginLoader.addModule("' + config.templateModule + '");'
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('concat', ['template'], function() {
  return gulp.src(['compiled.js', 'templates.js', 'vendor/**/*.js'])
    .pipe(plugins.concat(config.js))
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', ['concat'], function() {
  return del(['templates.js', 'compiled.js']);
});

gulp.task('less', function () {
  return gulp.src(config.less)
    .pipe(plugins.less({
      paths: [path.join(__dirname, 'plugins'), path.join(__dirname, 'libs')]
    }))
    .pipe(plugins.concat(config.css))
    .pipe(gulp.dest(config.dist));
});

gulp.task('watch-less', function() {
  plugins.watch(config.less, function() {
    gulp.start('less');
  });
});

gulp.task('watch', ['build', 'watch-less'], function() {
  plugins.watch(['libs/**/*.js', 'libs/**/*.css', 'index.html', urljoin(config.dist, '*')], function() {
    gulp.start('reload');
  });
  plugins.watch(['libs/**/*.d.ts', config.ts, config.templates], function() {
    gulp.start(['tsc', 'template', 'concat', 'clean']);
  });
});

gulp.task('connect', ['watch'], function() {
  hawtio.setConfig({
    logLevel: config.logLevel,
    port: 2772,
    staticProxies: [{
      port: config.proxyPort,
      path: '/jolokia',
      targetPath: config.targetPath
    }],
    staticAssets: [{
      path: '/',
      dir: '.'

    }],
    fallback: 'index.html',
    liveReload: {
      enabled: true
    }
  });
  hawtio.use('/', function(req, res, next) {
          var path = req.originalUrl;
          // avoid returning these files, they should get pulled from js
          if (s.startsWith(path, '/plugins/') && s.endsWith(path, 'html')) {
            if (argv.debug) {
              console.log("returning 404 for: ", path);
            }
            res.statusCode = 404;
            res.end();
          } else {
            if (argv.debug) {
              console.log("allowing: ", path);
            }
            next();
          }
        });
  hawtio.listen(function(server) {
    var host = server.address().address;
    var port = server.address().port;
    console.log("started from gulp file at ", host, ":", port);
  });
});

gulp.task('reload', function() {
  gulp.src('.')
    .pipe(hawtio.reload());
});

gulp.task('build', ['bower', 'path-adjust', 'tsc', 'less', 'template', 'concat', 'clean']);

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

<|endoftext|>


<commit_before>/*
 * Viking Base registers gulp tasks for you.
 * For more information and examples see the
 * project on GitHub (https://github.com/jneurock/viking-base).
 */

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    vb = require('./bower_components/viking-base/node_modules/viking-base');

// Set module refeneces on vb object
vb.gulp = gulp;
vb.plugins = plugins;

// Modify tasks as you need before calling vb.registerGulpTasks
vb.registerGulpTasks();<commit_msg>Skipped JSDoc build target<commit_after>/*
 * Viking Base registers gulp tasks for you.
 * For more information and examples see the
 * project on GitHub (https://github.com/jneurock/viking-base).
 */

var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    vb = require('./bower_components/viking-base/node_modules/viking-base');

// Set module refeneces on vb object
vb.gulp = gulp;
vb.plugins = plugins;

vb.tasks.build.depends = [
  'handlebars',
  'root'
];

// Modify tasks as you need before calling vb.registerGulpTasks
vb.registerGulpTasks();<|endoftext|>


<commit_before>// Pull in fractal
const fractal       = require('./fractal.js');
const logger        = fractal.cli.console;

// Gulpy gulp
const gulp          = require('gulp');
const autoprefixer  = require('gulp-autoprefixer');
const babel         = require('gulp-babel');
const buffer        = require('vinyl-buffer');
const browserify    = require('browserify');
const concat        = require('gulp-concat');
const del           = require('del');
const eslint        = require('gulp-eslint');
const glob          = require('glob');
const rename        = require('gulp-rename');
const sass          = require('gulp-sass');
const sassLint      = require('gulp-sass-lint');
const source        = require('vinyl-source-stream');
const sourcemaps    = require('gulp-sourcemaps');
const surge         = require('gulp-surge');
const svgmin        = require('gulp-svgmin');
const svgsymbols    = require('gulp-svg-symbols');
const uglify        = require('gulp-uglify');

// Paths
const paths = {
  src: `${__dirname}/src/`,
  dest: `${__dirname}/tmp/`,
  build: `${__dirname}/www/`,
  dist: `${__dirname}/dist/`
};

// Deploy location:
const surgeURL = 'https://vam-design-guide.surge.sh';

//---
// Empty temp folders
function clean() {
  return del([`${paths.dest}`, `${paths.build}`]);
}

//---
// Setup a local server
function serve() {
  const server = fractal.web.server({
    sync: true
  });
  server.on('error', err => logger.error(err.message));
  return server.start().then(() => {
    logger.success(`Fractal online at: ${server.url}`);
  });
}

//---
// Create a static build of fractal
// Build location defined in `fractal.js`
function staticBuild() {
  const builder = fractal.web.builder();
  builder.on('progress', (completed, total) => logger.update(`Exported ${completed} of ${total} items`, 'info'));
  builder.on('error', err => logger.error(err.message));
  return builder.build().then(() => {
    logger.success('Fractal build complete');
  });
}

//---
// Deploy to surge
function deploy() {
  return surge({
    project: paths.build,
    domain: surgeURL
  });
}

//---
// Style
function styles() {
  // Look at replacing a lot of this with postCSS
  return gulp.src(`${paths.src}/assets/styles/*.scss`)
    .pipe(sourcemaps.init())
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(`${paths.dest}/assets/styles`));
}

//---
// Fonts
function fonts() {
  return gulp.src(`${paths.src}/assets/fonts/**/*`)
    .pipe(gulp.dest(`${paths.dest}/assets/fonts`));
}

//---
// Scripts
const opts = {
  transform: [
        ["babelify", { presets: ["es2015"],
                        plugins: ["transform-class-properties"]
                      }
        ],
      ],
  debug: true
};

const newBundle = entry => {
  opts.entries = entry;
  let b = browserify(opts);

  const rebundle = () => {
    b.bundle()
    .on('error', swallowError)
    .pipe(source(entry))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(uglify())
    .pipe(rename('vamscript.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(`${paths.dest}/assets/scripts`));
  }

  return rebundle();
}

function scripts() {
  return gulp.src(`${paths.src}/assets/scripts/precompiled/*.js`)
    .pipe(gulp.dest(`${paths.dest}/assets/scripts`));

  return glob(`${paths.src}/assets/scripts/*.js`, function(err, files) {
    var tasks = files.map(function(entry) {
      newBundle(entry);
    });
  });
}

function swallowError (error) {
  console.log(error.toString())
  this.emit('end')
}

//---
// SVG Icons
function svg() {
  return gulp.src(`${paths.src}/assets/svg/*.svg`)
    .pipe(svgmin())
    .pipe(svgsymbols({
      svgClassname: 's-svg-icon',
      templates: [`${paths.src}/assets/templates/svg-template.svg`],
      title: false,
    }))
    .pipe(gulp.dest(`${paths.dest}/assets/svg`));
}

//---
// Prepare for release
function releaseSVG() {
  return gulp.src(`${paths.dest}/assets/svg/*.svg`)
    .pipe(rename('vamicons.svg'))
    .pipe(gulp.dest(`${paths.dist}/svg`));
}

function releaseCSS() {
  return gulp.src(`${paths.dest}/assets/styles/vam-style.css*`)
    .pipe(gulp.dest(`${paths.dist}/css`));
}

function releaseJS() {
  return gulp.src(`${paths.dest}/assets/scripts/*.js*`)
    .pipe(gulp.dest(`${paths.dist}/scripts`));
}

//---
// Linters
function sassLinter() {
  return gulp.src(`${paths.src}/**/*.scss`)
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
}

function jsLinter() {
  return gulp.src(`${paths.src}/**/*.js`)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
}

//---
// Watch
function watch() {
  serve();
  gulp.watch([`${paths.src}/assets/**/*.scss`, `${paths.src}/components/**/*.scss`], styles);
  gulp.watch([`${paths.src}/assets/**/*.js`, `${paths.src}/components/**/_*.js`], scripts);
  gulp.watch(`${paths.src}/assets/svg/*.svg`, svg);
  gulp.watch(`${paths.src}/assets/fonts`, fonts);
}

const compile = gulp.series(clean, gulp.parallel(fonts, svg, styles, scripts));
const buildDistAssets = gulp.parallel(releaseSVG, releaseCSS, releaseJS);
const linter = gulp.series(sassLinter, jsLinter);

gulp.task('dev', gulp.series(compile, watch));
gulp.task('deploy', gulp.series(linter, compile, staticBuild, deploy));
gulp.task('dist', gulp.series(linter, compile, buildDistAssets, staticBuild, deploy, clean));
gulp.task('lint', gulp.series(linter));
<commit_msg>undo gulp fix, since it breaks the vamscript asset pipeline - will need to find a proper fix for newer versions of gulp!<commit_after>// Pull in fractal
const fractal       = require('./fractal.js');
const logger        = fractal.cli.console;

// Gulpy gulp
const gulp          = require('gulp');
const autoprefixer  = require('gulp-autoprefixer');
const babel         = require('gulp-babel');
const buffer        = require('vinyl-buffer');
const browserify    = require('browserify');
const concat        = require('gulp-concat');
const del           = require('del');
const eslint        = require('gulp-eslint');
const glob          = require('glob');
const rename        = require('gulp-rename');
const sass          = require('gulp-sass');
const sassLint      = require('gulp-sass-lint');
const source        = require('vinyl-source-stream');
const sourcemaps    = require('gulp-sourcemaps');
const surge         = require('gulp-surge');
const svgmin        = require('gulp-svgmin');
const svgsymbols    = require('gulp-svg-symbols');
const uglify        = require('gulp-uglify');

// Paths
const paths = {
  src: `${__dirname}/src/`,
  dest: `${__dirname}/tmp/`,
  build: `${__dirname}/www/`,
  dist: `${__dirname}/dist/`
};

// Deploy location:
const surgeURL = 'https://vam-design-guide.surge.sh';

//---
// Empty temp folders
function clean() {
  return del([`${paths.dest}`, `${paths.build}`]);
}

//---
// Setup a local server
function serve() {
  const server = fractal.web.server({
    sync: true
  });
  server.on('error', err => logger.error(err.message));
  return server.start().then(() => {
    logger.success(`Fractal online at: ${server.url}`);
  });
}

//---
// Create a static build of fractal
// Build location defined in `fractal.js`
function staticBuild() {
  const builder = fractal.web.builder();
  builder.on('progress', (completed, total) => logger.update(`Exported ${completed} of ${total} items`, 'info'));
  builder.on('error', err => logger.error(err.message));
  return builder.build().then(() => {
    logger.success('Fractal build complete');
  });
}

//---
// Deploy to surge
function deploy() {
  return surge({
    project: paths.build,
    domain: surgeURL
  });
}

//---
// Style
function styles() {
  // Look at replacing a lot of this with postCSS
  return gulp.src(`${paths.src}/assets/styles/*.scss`)
    .pipe(sourcemaps.init())
    .pipe(sass({
      outputStyle: 'compressed'
    }).on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(`${paths.dest}/assets/styles`));
}

//---
// Fonts
function fonts() {
  return gulp.src(`${paths.src}/assets/fonts/**/*`)
    .pipe(gulp.dest(`${paths.dest}/assets/fonts`));
}

//---
// Scripts
const opts = {
  transform: [
        ["babelify", { presets: ["es2015"],
                        plugins: ["transform-class-properties"]
                      }
        ],
      ],
  debug: true
};

const newBundle = entry => {
  opts.entries = entry;
  let b = browserify(opts);

  const rebundle = () => {
    b.bundle()
    .on('error', swallowError)
    .pipe(source(entry))
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(uglify())
    .pipe(rename('vamscript.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(`${paths.dest}/assets/scripts`));
  }

  return rebundle();
}

function scripts() {
  gulp.src(`${paths.src}/assets/scripts/precompiled/*.js`)
    .pipe(gulp.dest(`${paths.dest}/assets/scripts`));

  return glob(`${paths.src}/assets/scripts/*.js`, function(err, files) {
    var tasks = files.map(function(entry) {
      newBundle(entry);
    });
  });
}

function swallowError (error) {
  console.log(error.toString())
  this.emit('end')
}

//---
// SVG Icons
function svg() {
  return gulp.src(`${paths.src}/assets/svg/*.svg`)
    .pipe(svgmin())
    .pipe(svgsymbols({
      svgClassname: 's-svg-icon',
      templates: [`${paths.src}/assets/templates/svg-template.svg`],
      title: false,
    }))
    .pipe(gulp.dest(`${paths.dest}/assets/svg`));
}

//---
// Prepare for release
function releaseSVG() {
  return gulp.src(`${paths.dest}/assets/svg/*.svg`)
    .pipe(rename('vamicons.svg'))
    .pipe(gulp.dest(`${paths.dist}/svg`));
}

function releaseCSS() {
  return gulp.src(`${paths.dest}/assets/styles/vam-style.css*`)
    .pipe(gulp.dest(`${paths.dist}/css`));
}

function releaseJS() {
  return gulp.src(`${paths.dest}/assets/scripts/*.js*`)
    .pipe(gulp.dest(`${paths.dist}/scripts`));
}

//---
// Linters
function sassLinter() {
  return gulp.src(`${paths.src}/**/*.scss`)
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
}

function jsLinter() {
  return gulp.src(`${paths.src}/**/*.js`)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failOnError());
}

//---
// Watch
function watch() {
  serve();
  gulp.watch([`${paths.src}/assets/**/*.scss`, `${paths.src}/components/**/*.scss`], styles);
  gulp.watch([`${paths.src}/assets/**/*.js`, `${paths.src}/components/**/_*.js`], scripts);
  gulp.watch(`${paths.src}/assets/svg/*.svg`, svg);
  gulp.watch(`${paths.src}/assets/fonts`, fonts);
}

const compile = gulp.series(clean, gulp.parallel(fonts, svg, styles, scripts));
const buildDistAssets = gulp.parallel(releaseSVG, releaseCSS, releaseJS);
const linter = gulp.series(sassLinter, jsLinter);

gulp.task('dev', gulp.series(compile, watch));
gulp.task('deploy', gulp.series(linter, compile, staticBuild, deploy));
gulp.task('dist', gulp.series(linter, compile, buildDistAssets, staticBuild, deploy, clean));
gulp.task('lint', gulp.series(linter));
<|endoftext|>


<commit_before>//npm install gulp gulp-concat gulp-imagemin imagemin-pngquant gulp-cache gulp-autoprefixer gulp-minify-css gulp-uncss font-spider gulp-uglify gulp-jshint gulp-replace gulp-processhtml gulp-htmlmin browser-sync --save-dev

var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var imagemin = require('gulp-imagemin');				//- 图片压缩
var pngquant = require('imagemin-pngquant');				//- 深度压缩png插件
var cache = require('gulp-cache');					//- 只压缩修改的图片，没有修改的图片直接从缓存文件读取
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var minifyCss = require('gulp-minify-css');				//- 压缩CSS为一行
var uncss = require('gulp-uncss');					//- 删除没用到的css
var FontSpider = require('font-spider');				//- 删除没用到的字体
var uglify = require('gulp-uglify');					//- js合并压缩
var jshint = require('gulp-jshint');					//- js检测
var replace = require('gulp-replace');					//- 文本替换
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具

var y_Sz="src";								//- 生产环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('imagemin',function(){
	gulp.src('./'+y_Sz+'/img/*.{png,jpg,gif,ico}')
	.pipe(cache(imagemin({
	progressive: true,
	svgoPlugins: [{removeViewBox: false}],				//- 不要移除svg的viewbox属性
	use: [pngquant()]						//- 使用pngquant深度压缩png图片的imagemin插件
	})))
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

gulp.task('concat',function(){						//- 创建一个名为 concat 的 task
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(uncss({
	html: ['./'+y_Sz+'/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(minifyCss({compatibility: 'ie8', keepBreaks:false}))	//- 压缩处理成一行,兼容ie
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('jsmin',function(){						//- 合并多个文件
	gulp.src(['./'+y_Sz+'/js/*.js'])				//- 多个文件以数组形式传入
	.pipe(uglify())
	.pipe(concat('index.js'))
	.pipe(gulp.dest('./'+y_Dz+'/js'));
});

gulp.task('jshint',function(){						//- 检查文件
	gulp.src('./'+y_Dz+'/js/*.js')
	.pipe(jshint())
	.pipe(jshint.reporter('default'));				//- 检查错误
});

gulp.task('processhtml',function(){					//- 修改该html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('fs',function(){
	return FontSpider(['./'+y_Sz+'/*.html']);		//- 删除多余的字体和图标，添加return返回最终的数据流
});

gulp.task('cp',['fs'],function(){					//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'						//- 被复制的目标路径
	})
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径

	gulp.src(['./'+y_Sz+'/icon/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/icon'						//- 被复制的目标路径
	})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

/*-------------bs,html这两个命令是需要时手动执行-----------------*/

gulp.task('html',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
};
gulp.src('./'+y_Dz+'/*.html')						//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Sz+'/'}				//- 目标文件夹路径
	});
});

//执行插件函数
gulp.task('default',['concat','imagemin','jsmin','jshint','processhtml','cp']);<commit_msg>pxtorem<commit_after>//npm install gulp gulp-concat gulp-imagemin imagemin-pngquant gulp-cache gulp-autoprefixer gulp-minify-css gulp-uncss font-spider gulp-uglify gulp-jshint gulp-replace gulp-processhtml gulp-htmlmin browser-sync --save-dev

var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var imagemin = require('gulp-imagemin');				//- 图片压缩
var pngquant = require('imagemin-pngquant');				//- 深度压缩png插件
var cache = require('gulp-cache');					//- 只压缩修改的图片，没有修改的图片直接从缓存文件读取
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var minifyCss = require('gulp-minify-css');				//- 压缩CSS为一行
var px2rem = require('gulp-px3rem');					//- px转rem
var uncss = require('gulp-uncss');					//- 删除没用到的css
var FontSpider = require('font-spider');				//- 删除没用到的字体
var uglify = require('gulp-uglify');					//- js合并压缩
var jshint = require('gulp-jshint');					//- js检测
var replace = require('gulp-replace');					//- 文本替换
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具

var y_Sz="src";								//- 生产环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('imagemin',function(){
	gulp.src('./'+y_Sz+'/img/*.{png,jpg,gif,ico}')
	.pipe(cache(imagemin({
	progressive: true,
	svgoPlugins: [{removeViewBox: false}],				//- 不要移除svg的viewbox属性
	use: [pngquant()]						//- 使用pngquant深度压缩png图片的imagemin插件
	})))
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

gulp.task('concat',function(){						//- 创建一个名为 concat 的 task
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(uncss({
	html: ['./'+y_Sz+'/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(px2rem({remUnit: 100}))					//- px/100转rem值，如果有不想转换的类在值后面加/*no*/
	.pipe(minifyCss({compatibility: 'ie8', keepBreaks:false}))	//- 压缩处理成一行,兼容ie
	.pipe(concat('index.css'))						//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('jsmin',function(){						//- 合并多个文件
	gulp.src(['./'+y_Sz+'/js/*.js'])				//- 多个文件以数组形式传入
	.pipe(uglify())
	.pipe(concat('index.js'))
	.pipe(gulp.dest('./'+y_Dz+'/js'));
});

gulp.task('jshint',function(){						//- 检查文件
	gulp.src('./'+y_Dz+'/js/*.js')
	.pipe(jshint())
	.pipe(jshint.reporter('default'));				//- 检查错误
});

gulp.task('processhtml',function(){					//- 修改该html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('fs',function(){
	return FontSpider(['./'+y_Sz+'/*.html']);		//- 删除多余的字体和图标，添加return返回最终的数据流
});

gulp.task('cp',['fs'],function(){					//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'						//- 被复制的目标路径
	})
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径

	gulp.src(['./'+y_Sz+'/icon/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/icon'						//- 被复制的目标路径
	})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

/*-------------bs,html这两个命令是需要时手动执行-----------------*/

gulp.task('html',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
};
gulp.src('./'+y_Dz+'/*.html')						//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Sz+'/'}				//- 目标文件夹路径
	});
});

//执行插件函数
gulp.task('default',['concat','imagemin','jsmin','jshint','processhtml','cp']);<|endoftext|>


<commit_before>'use strict';

const {spawn} = require('child_process');
const del = require('del');
const gulp = require('gulp');
const {delimiter, normalize, resolve} = require('path');

/**
 * The file patterns providing the list of source files.
 * @type {string[]}
 */
const sources = ['*.js', 'example/*.ts', 'src/**/*.ts', 'test/**/*.ts'];

/**
 * Builds the project.
 */
gulp.task('build', () => _exec('tsc'));

/**
 * Deletes all generated files and reset any saved state.
 */
gulp.task('clean', () => del(['.nyc_output', 'doc/api', 'lib', 'var/**/*', 'web']));

/**
 * Sends the results of the code coverage.
 */
gulp.task('coverage', () => _exec('coveralls', ['var/lcov.info']));

/**
 * Builds the documentation.
 */
gulp.task('doc:api', () => _exec('typedoc'));
gulp.task('doc:web', () => _exec('mkdocs', ['build']));
gulp.task('doc', gulp.series('doc:api', 'doc:web'));

/**
 * Fixes the coding standards issues.
 */
gulp.task('fix', () => _exec('tslint', ['--fix', ...sources]));

/**
 * Performs static analysis of source code.
 */
gulp.task('lint', () => _exec('tslint', sources));

/**
 * Runs the unit tests.
 */
gulp.task('test:browser', () => _exec('karma', ['start']));
gulp.task('test:node', () => _exec('nyc', [normalize('node_modules/.bin/mocha')]));
gulp.task('test', gulp.series('test:browser', 'test:node'));

/**
 * Upgrades the project to the latest revision.
 */
gulp.task('upgrade', async () => {
  await _exec('git', ['reset', '--hard']);
  await _exec('git', ['fetch', '--all', '--prune']);
  await _exec('git', ['pull', '--rebase']);
  await _exec('npm', ['install', '--ignore-scripts']);
  return _exec('npm', ['update', '--dev']);
});

/**
 * Watches for file changes.
 */
gulp.task('watch', () => {
  gulp.watch('src/**/*.ts', {ignoreInitial: false}, gulp.task('build'));
  gulp.watch('test/**/*.ts', gulp.task('test:node'));
});

/**
 * Runs the default tasks.
 */
gulp.task('default', gulp.task('build'));

/**
 * Spawns a new process using the specified command.
 * @param {string} command The command to run.
 * @param {string[]} [args] The command arguments.
 * @param {Object} [options] The settings to customize how the process is spawned.
 * @return {Promise} Completes when the command is finally terminated.
 */
function _exec(command, args = [], options = {shell: true, stdio: 'inherit'}) {
  if (!process.env.PATH.includes(normalize('node_modules/.bin'))) process.env.PATH = `${resolve('node_modules/.bin')}${delimiter}${process.env.PATH}`;
  return new Promise((fulfill, reject) => spawn(normalize(command), args, options)
    .on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill())
  );
}
<commit_msg>Fixed the build system<commit_after>'use strict';

const {spawn} = require('child_process');
const del = require('del');
const gulp = require('gulp');
const {delimiter, normalize, resolve} = require('path');

/**
 * The file patterns providing the list of source files.
 * @type {string[]}
 */
const sources = ['*.js', 'example/*.ts', 'src/**/*.ts', 'test/**/*.ts'];

/**
 * Builds the project.
 */
gulp.task('build', () => _exec('tsc'));

/**
 * Deletes all generated files and reset any saved state.
 */
gulp.task('clean', () => del(['.nyc_output', 'doc/api', 'lib', 'var/**/*', 'web']));

/**
 * Sends the results of the code coverage.
 */
gulp.task('coverage', () => _exec('coveralls', ['var/lcov.info']));

/**
 * Builds the documentation.
 */
gulp.task('doc:api', () => _exec('typedoc'));
gulp.task('doc:web', () => _exec('mkdocs', ['build']));
gulp.task('doc', gulp.series('doc:api', 'doc:web'));

/**
 * Fixes the coding standards issues.
 */
gulp.task('fix', () => _exec('tslint', ['--fix', ...sources]));

/**
 * Performs static analysis of source code.
 */
gulp.task('lint', () => _exec('tslint', sources));

/**
 * Runs the unit tests.
 */
gulp.task('test', () => _exec('nyc', [normalize('node_modules/.bin/mocha')]));

/**
 * Upgrades the project to the latest revision.
 */
gulp.task('upgrade', async () => {
  await _exec('git', ['reset', '--hard']);
  await _exec('git', ['fetch', '--all', '--prune']);
  await _exec('git', ['pull', '--rebase']);
  await _exec('npm', ['install', '--ignore-scripts']);
  return _exec('npm', ['update', '--dev']);
});

/**
 * Watches for file changes.
 */
gulp.task('watch', () => {
  gulp.watch('src/**/*.ts', {ignoreInitial: false}, gulp.task('build'));
  gulp.watch('test/**/*.ts', gulp.task('test:node'));
});

/**
 * Runs the default tasks.
 */
gulp.task('default', gulp.task('build'));

/**
 * Spawns a new process using the specified command.
 * @param {string} command The command to run.
 * @param {string[]} [args] The command arguments.
 * @param {Object} [options] The settings to customize how the process is spawned.
 * @return {Promise} Completes when the command is finally terminated.
 */
function _exec(command, args = [], options = {shell: true, stdio: 'inherit'}) {
  if (!process.env.PATH.includes(normalize('node_modules/.bin'))) process.env.PATH = `${resolve('node_modules/.bin')}${delimiter}${process.env.PATH}`;
  return new Promise((fulfill, reject) => spawn(normalize(command), args, options)
    .on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill())
  );
}
<|endoftext|>


<commit_before>// Install deps:
// npm install -g gulp bower less
// npm install

var gulp = require('gulp');

var plugins = require("gulp-load-plugins")();
var gconf = require('./gulpconfig.json');

// Download all bower dependencies and 3rd party components
gulp.task('bower', function() {
    return plugins.bower();
});

gulp.task('lint', function() {
    return gulp.src(gconf.scripts)
        .pipe(plugins.jshint({
            eqnull: true,
            sub: true
        }))
        .pipe(plugins.jshint.reporter('default'));
});

/**
 * Minify and copy all scripts to build path.
 *
 * @return {[type]} [description]
 */
gulp.task('scripts', ['bower'], function() {
    // Minify and copy all JavaScript (except vendor script)
    for (var outputFile in gconf.scripts) {
        console.log('creating '+outputFile+'...');
        gulp.src(gconf.scripts[outputFile].files)
        .pipe(plugins.concat(outputFile))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(gconf.build_path+gconf.scripts[outputFile].output_path))
        .pipe(plugins.connect.reload());
    }
    return;
});

gulp.task('styles', ['bower'], function() {
    // Minify and copy all Styles
    for (var outputFile in gconf.stylesheets) {
        console.log('creating '+outputFile+'...');
        gulp.src(gconf.stylesheets[outputFile].files)
        .pipe(plugins.less({
            gconf: ".",
            sourceMap: true,
            compress: true
        }))
        //.pipe(plugins.minifyCss())
        .pipe(plugins.concat(outputFile))
        .pipe(gulp.dest(gconf.build_path+gconf.stylesheets[outputFile].output_path))
        .pipe(plugins.connect.reload());
    }

    return;
});

// Copy all static images
gulp.task('images', function() {

    for (var outputPath in gconf.images) {
        console.log('compressing images to '+outputPath+'...');
        gulp.src(gconf.images[outputPath].files)
        .pipe(plugins.imagemin(gconf.images[outputPath].options))
        .pipe(gulp.dest(gconf.build_path+outputPath))
        .pipe(plugins.connect.reload());
    }

    return;
});

// Compile templates
gulp.task('views', function () {
    for (var outputPath in gconf.views) {
        console.log('creating views in '+outputPath+'...');
        gulp.src(gconf.views[outputPath].files)
        .pipe(plugins.nunjucksRender(gconf.views[outputPath].context))
        .pipe(gulp.dest(gconf.build_path+outputPath))
        .pipe(plugins.connect.reload());
    }

    return;
});

gulp.task('server', plugins.connect.server({
    root: [gconf.build_path],
    port: 8080,
    livereload: true,
    open: {
        browser: 'Google Chrome'
    }
}) );

// Rerun the task when a file changes
gulp.task('watch', function () {

    for (var o in gconf.scripts) {
        gulp.watch(gconf.scripts[o].files, ['scripts']);
    }
    for (var o in gconf.stylesheets) {
        gulp.watch(gconf.stylesheets[o].files, ['styles']);
    }
    for (var o in gconf.images) {
        gulp.watch(gconf.images[o].files, ['images']);
    }
    for (var o in gconf.views) {
        gulp.watch(gconf.views[o].files, ['views']);
    }

});

// The default task (called when you run `gulp` from cli)
gulp.task('default', [
    'server',
    'scripts',
    'styles',
    'images',
    'views',
    'watch',
]);

<commit_msg>Added check for Windows/Livereload.<commit_after>// Install deps:
// npm install -g gulp bower less
// npm install

var gulp = require('gulp');

var plugins = require("gulp-load-plugins")();
var gconf = require('./gulpconfig.json');

// Download all bower dependencies and 3rd party components
gulp.task('bower', function() {
    return plugins.bower();
});

gulp.task('lint', function() {
    return gulp.src(gconf.scripts)
        .pipe(plugins.jshint({
            eqnull: true,
            sub: true
        }))
        .pipe(plugins.jshint.reporter('default'));
});

/**
 * Minify and copy all scripts to build path.
 *
 * @return {[type]} [description]
 */
gulp.task('scripts', ['bower'], function() {
    // Minify and copy all JavaScript (except vendor script)
    for (var outputFile in gconf.scripts) {
        console.log('creating '+outputFile+'...');
        gulp.src(gconf.scripts[outputFile].files)
        .pipe(plugins.concat(outputFile))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(gconf.build_path+gconf.scripts[outputFile].output_path))
        .pipe(plugins.connect.reload());
    }
    return;
});

gulp.task('styles', ['bower'], function() {
    // Minify and copy all Styles
    for (var outputFile in gconf.stylesheets) {
        console.log('creating '+outputFile+'...');
        gulp.src(gconf.stylesheets[outputFile].files)
        .pipe(plugins.less({
            gconf: ".",
            sourceMap: true,
            compress: true
        }))
        //.pipe(plugins.minifyCss())
        .pipe(plugins.concat(outputFile))
        .pipe(gulp.dest(gconf.build_path+gconf.stylesheets[outputFile].output_path))
        .pipe(plugins.connect.reload());
    }

    return;
});

// Copy all static images
gulp.task('images', function() {

    for (var outputPath in gconf.images) {
        console.log('compressing images to '+outputPath+'...');
        gulp.src(gconf.images[outputPath].files)
        .pipe(plugins.imagemin(gconf.images[outputPath].options))
        .pipe(gulp.dest(gconf.build_path+outputPath))
        .pipe(plugins.connect.reload());
    }

    return;
});

// Compile templates
gulp.task('views', function () {
    for (var outputPath in gconf.views) {
        console.log('creating views in '+outputPath+'...');
        gulp.src(gconf.views[outputPath].files)
        .pipe(plugins.nunjucksRender(gconf.views[outputPath].context))
        .pipe(gulp.dest(gconf.build_path+outputPath))
        .pipe(plugins.connect.reload());
    }

    return;
});

gulp.task('server', plugins.connect.server({
    root: [gconf.build_path],
    port: 8080,
    livereload: true,
    open: {
        browser: (process.platform === 'win32' ? 'chrome' : 'Google Chrome')
    }
}) );

// Rerun the task when a file changes
gulp.task('watch', function () {

    for (var o in gconf.scripts) {
        gulp.watch(gconf.scripts[o].files, ['scripts']);
    }
    for (o in gconf.stylesheets) {
        gulp.watch(gconf.stylesheets[o].files, ['styles']);
    }
    for (o in gconf.images) {
        gulp.watch(gconf.images[o].files, ['images']);
    }
    for (o in gconf.views) {
        gulp.watch(gconf.views[o].files, ['views']);
    }

});

// The default task (called when you run `gulp` from cli)
gulp.task('default', [
    'server',
    'scripts',
    'styles',
    'images',
    'views',
    'watch',
]);

<|endoftext|>


<commit_before>
var fs = require('fs');
var path = require('path');

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')(); // Load all gulp plugins automatically

var runSequence = require('run-sequence');    // Temporary solution until gulp 4 (https://github.com/gulpjs/gulp/issues/355)

var pkg = require('./package.json');
var dirs = pkg.configs.directories;

// ---------------------------------------------------------------------
// | Helper tasks                                                      |
// ---------------------------------------------------------------------

gulp.task('archive:create_archive_dir', function () {
	'use strict';
	fs.mkdirSync(path.resolve(dirs.archive), '0755');
});

gulp.task('archive:zip', function (done) {
	'use strict';

	var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
	var archiver = require('archiver')('zip');
	var files = require('glob').sync('**/*.*', {
		'cwd': dirs.dist,
		'dot': true // include hidden files
	});
	var output = fs.createWriteStream(archiveName);

	archiver.on('error', function (error) {
		done();
		throw error;
	});

	output.on('close', done);

	files.forEach(function (file) {
		var filePath = path.resolve(dirs.dist, file);

		// `archiver.bulk` does not maintain the file
		// permissions, so we need to add files individually
		archiver.append(fs.createReadStream(filePath), {
			'name': file,
			'mode': fs.statSync(filePath)
		});
	});

	archiver.pipe(output);
	archiver.finalize();
});

gulp.task('clean', function (done) {
	'use strict';
	require('del')([
		dirs.archive,
		dirs.dist
	], done);
});

gulp.task('copy', [
	'copy:.htaccess',
	'copy:sql',
	'copy:index.html',
	'copy:license',
	'copy:misc',
	'copy:bootstrap',
	'copy:normalize'
]);

gulp.task('copy:.htaccess', function () {
	'use strict';
	return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
			.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:.sql', function () {
	'use strict';
	return gulp.src('*.sql')
		.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:index.html', function () {
	'use strict';
	return gulp.src(dirs.src + '/index.html')
			.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:license', function () {
	'use strict';
	return gulp.src('LICENSE.txt')
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:misc', function () {
	'use strict';
	return gulp.src([

		// Copy all files
		dirs.src + '/**/*',

		// Exclude the following files
		// (other tasks will handle the copying of these files)
		// '!' + dirs.src + '/css/main.css',
		'!' + dirs.src + '/index.html'

	], {

		// Include hidden files by default
		dot: true

	}).pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:bootstrap', function () {
	'use strict';
	return gulp.src('node_modules/bootstrap/dist/css/bootstrap.min.css')
			.pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('copy:normalize', function () {
	'use strict';
	return gulp.src('node_modules/normalize.css/normalize.css')
			.pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('lint:js', function () {
	'use strict';
	return gulp.src([
		'gulpfile.js',
		dirs.src + '/js/*.js',
		dirs.test + '/*.js'
	]).pipe(plugins.jscs())
			.pipe(plugins.jshint())
			.pipe(plugins.jshint.reporter('jshint-stylish'));
});

// ---------------------------------------------------------------------
// | Main tasks                                                        |
// ---------------------------------------------------------------------

gulp.task('archive', function (done) {
	'use strict';
	runSequence(
		'build',
		'archive:create_archive_dir',
		'archive:zip',
		done);
});

gulp.task('build', function (done) {
	'use strict';
	runSequence(
		['clean', 'lint:js'],
		'copy',
		done);
});

gulp.task('default', ['archive']);
<commit_msg>Fix the build.<commit_after>
var fs = require('fs');
var path = require('path');

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')(); // Load all gulp plugins automatically

var runSequence = require('run-sequence');    // Temporary solution until gulp 4 (https://github.com/gulpjs/gulp/issues/355)

var pkg = require('./package.json');
var dirs = pkg.configs.directories;

// ---------------------------------------------------------------------
// | Helper tasks                                                      |
// ---------------------------------------------------------------------

gulp.task('archive:create_archive_dir', function () {
	'use strict';
	fs.mkdirSync(path.resolve(dirs.archive), '0755');
});

gulp.task('archive:zip', function (done) {
	'use strict';

	var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
	var archiver = require('archiver')('zip');
	var files = require('glob').sync('**/*.*', {
		'cwd': dirs.dist,
		'dot': true // include hidden files
	});
	var output = fs.createWriteStream(archiveName);

	archiver.on('error', function (error) {
		done();
		throw error;
	});

	output.on('close', done);

	files.forEach(function (file) {
		var filePath = path.resolve(dirs.dist, file);

		// `archiver.bulk` does not maintain the file
		// permissions, so we need to add files individually
		archiver.append(fs.createReadStream(filePath), {
			'name': file,
			'mode': fs.statSync(filePath)
		});
	});

	archiver.pipe(output);
	archiver.finalize();
});

gulp.task('clean', function (done) {
	'use strict';
	require('del')([
		dirs.archive,
		dirs.dist
	], done);
});

gulp.task('copy', [
	'copy:.htaccess',
	'copy:sql',
	'copy:index.html',
	'copy:license',
	'copy:misc',
	'copy:bootstrap',
	'copy:normalize'
]);

gulp.task('copy:.htaccess', function () {
	'use strict';
	return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
			.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:sql', function () {
	'use strict';
	return gulp.src('*.sql')
		.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:index.html', function () {
	'use strict';
	return gulp.src(dirs.src + '/index.html')
			.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:license', function () {
	'use strict';
	return gulp.src('LICENSE.txt')
			.pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:misc', function () {
	'use strict';
	return gulp.src([

		// Copy all files
		dirs.src + '/**/*',

		// Exclude the following files
		// (other tasks will handle the copying of these files)
		// '!' + dirs.src + '/css/main.css',
		'!' + dirs.src + '/index.html'

	], {

		// Include hidden files by default
		dot: true

	}).pipe(gulp.dest(dirs.dist));
});

gulp.task('copy:bootstrap', function () {
	'use strict';
	return gulp.src('node_modules/bootstrap/dist/css/bootstrap.min.css')
			.pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('copy:normalize', function () {
	'use strict';
	return gulp.src('node_modules/normalize.css/normalize.css')
			.pipe(gulp.dest(dirs.dist + '/css'));
});

gulp.task('lint:js', function () {
	'use strict';
	return gulp.src([
		'gulpfile.js',
		dirs.src + '/js/*.js',
		dirs.test + '/*.js'
	]).pipe(plugins.jscs())
			.pipe(plugins.jshint())
			.pipe(plugins.jshint.reporter('jshint-stylish'));
});

// ---------------------------------------------------------------------
// | Main tasks                                                        |
// ---------------------------------------------------------------------

gulp.task('archive', function (done) {
	'use strict';
	runSequence(
		'build',
		'archive:create_archive_dir',
		'archive:zip',
		done);
});

gulp.task('build', function (done) {
	'use strict';
	runSequence(
		['clean', 'lint:js'],
		'copy',
		done);
});

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


<commit_before>'use strict';

var gulp = require( 'gulp' );
var karma = require( 'karma' ).server;
var jshint = require( 'gulp-jshint' );
var concat = require( 'gulp-concat' );
var uglify = require( 'gulp-uglify' );
var plato = require( 'plato' );
var exec = require( 'child_process' ).exec;

var coreFiles = 'src/**/*.js';
var allFiles = '{test,src}/**/*.js';

gulp.task( 'lint', function() {
  gulp.src( allFiles )
    .pipe( jshint() )
    .pipe( jshint.reporter( 'default' ) );
});

gulp.task( 'uglify', function() {
  gulp.src( coreFiles )
    .pipe( concat( 'ajax.min.js' ) )
    .pipe( uglify() )
    .pipe( gulp.dest( './dist' ) );
});

gulp.task( 'test', function( done ) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done );
});

gulp.task( 'webserver', function( done ) {
  require( './api/app' );
  exec( 'python -m SimpleHTTPServer 9001', function() {
    console.log( 'Server listen on port 9001' );
    done();
  });
});

gulp.task( 'watch', [ 'test', 'lint' ], function() {
  gulp.watch( '{test,src}/**/*.js', [ 'test', 'lint' ]);
});

gulp.task( 'plato', function( done ) {
  var files = [ coreFiles ];
  var outputDir = './plato';
  var options = { title: '#Ajax', jshint: './.jshintrc' };
  function callback( report ) { done(); };
  plato.inspect( files, outputDir, options, callback );
});

gulp.task( 'deploy', function( done ) {
  console.log( 'Deploying...' );
  var date = new Date( Date.now() );
  var commands = [
    'gulp uglify',
    'git add .',
    'git commit -m "Minifying"',
    'gulp plato',
    'rm -rf .tmp',
    'mkdir .tmp',
    'cd .tmp',
    'git clone git@github.com:reportz/ajax.git ./',
    'cp -R ../coverage ../plato ./',
    'git add -A',
    'git commit -m "Update reports at ' + date + ' "',
    'git push origin gh-pages',
    'cd ../',
    'rm -rf .tmp',
    'git checkout master',
    'git merge dev',
    'git push origin master',
    'git checkout dev'
  ];
  exec( commands.join( ' && ' ), function( err, stdout, stderr ) {
    console.log( 'Done!' );
    if( stdout ) console.log( 'STDOUT:', stdout );
    if( stderr ) console.log( 'STDERR:', stderr );
    if( err ) console.log( 'ERROR:', err );
    process.exit(1);
    done();
  });
});

gulp.task( 'default', [ 'webserver', 'watch' ]);<commit_msg>Minifying<commit_after>'use strict';

var gulp = require( 'gulp' );
var karma = require( 'karma' ).server;
var jshint = require( 'gulp-jshint' );
var concat = require( 'gulp-concat' );
var uglify = require( 'gulp-uglify' );
var plato = require( 'plato' );
var exec = require( 'child_process' ).exec;

var coreFiles = 'src/**/*.js';
var allFiles = '{test,src}/**/*.js';

gulp.task( 'lint', function() {
  gulp.src( allFiles )
    .pipe( jshint() )
    .pipe( jshint.reporter( 'default' ) );
});

gulp.task( 'uglify', function() {
  gulp.src( coreFiles )
    .pipe( concat( 'ajax.min.js' ) )
    .pipe( uglify() )
    .pipe( gulp.dest( './dist' ) );
});

gulp.task( 'test', function( done ) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done );
});

gulp.task( 'webserver', function( done ) {
  require( './api/app' );
  exec( 'python -m SimpleHTTPServer 9001', function() {
    console.log( 'Server listen on port 9001' );
    done();
  });
});

gulp.task( 'watch', [ 'test', 'lint' ], function() {
  gulp.watch( '{test,src}/**/*.js', [ 'test', 'lint' ]);
});

gulp.task( 'plato', function( done ) {
  var files = [ coreFiles ];
  var outputDir = './plato';
  var options = { title: '#Ajax' };
  function callback( report ) { done(); };
  plato.inspect( files, outputDir, options, callback );
});

gulp.task( 'deploy', function( done ) {
  console.log( 'Deploying...' );
  var date = new Date( Date.now() );
  var commands = [
    'gulp uglify',
    'git add .',
    'git commit -m "Minifying"',
    'gulp plato',
    'rm -rf .tmp',
    'mkdir .tmp',
    'cd .tmp',
    'git clone git@github.com:reportz/ajax.git ./',
    'cp -R ../coverage ../plato ./',
    'git add -A',
    'git commit -m "Update reports at ' + date + ' "',
    'git push origin gh-pages',
    'cd ../',
    'rm -rf .tmp',
    'git checkout master',
    'git merge dev',
    'git push origin master',
    'git checkout dev'
  ];
  exec( commands.join( ' && ' ), function( err, stdout, stderr ) {
    console.log( 'Done!' );
    if( stdout ) console.log( 'STDOUT:', stdout );
    if( stderr ) console.log( 'STDERR:', stderr );
    if( err ) console.log( 'ERROR:', err );
    process.exit(1);
    done();
  });
});

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


<commit_before>/*eslint-disable */

var fs = require('fs')
var gulp = require('gulp')
var source = require('vinyl-source-stream')
var rename = require('gulp-rename')
var browserify = require('browserify')
var buffer = require('vinyl-buffer')
var uglify = require('gulp-uglify')
var taskListing = require('gulp-task-listing')
var awspublish = require('gulp-awspublish')
var injectVersion = require('gulp-inject-version')
var derequire = require('gulp-derequire')
var es = require('event-stream')
var karma = require('karma')
var runSequence = require('run-sequence')
var webdriver = require('gulp-webdriver')
var selenium = require('selenium-standalone')
var replace = require('gulp-replace')

var connect = require('gulp-connect')

require('gulp-release-tasks')(gulp)

var jeditor = require('gulp-json-editor')

var webdriverConfig = {
  user: process.env.SAUCE_USERNAME || 'opbeat-angular',
  key: process.env.SAUCE_ACCESS_KEY || 'bfc1a656-542b-4893-bdef-a7ac20256fa9',
  host: process.env.SAUCE_HOST || 'ondemand.saucelabs.com',
  port: process.env.SAUCE_PORT || 80,
  baseUrl: process.env.SAUCE_BASEURL || 'http://localhost:8000'
}

// Static file server
gulp.task('examples:serve', function () {
  connect.server({
    root: ['examples', 'dist'],
    port: 7000,
    livereload: false,
    open: false
  })
})

function createBuildStream (mainFilePath, version) {
  if (typeof version !== 'string') {
    throw new Error(mainFilePath + ' Expected version as string but got:' + version)
  }

  return browserify({
    entries: [mainFilePath],
    standalone: '',
    insertGlobalVars: { define: function () { return 'undefined'; }, process: function () { return 'undefined'; } }
  })
    .bundle()
    .pipe(source(mainFilePath))
    .pipe(rename({ dirname: '' }))
    .pipe(buffer())
    .pipe(replace(
      new RegExp(RegExp.escape('%%VERSION%%'), 'g'),
      'v' + version
    ))
    .pipe(derequire())
}

function writeToDestinations (stream, dests) {
  var tasks = dests.map(function (destPath) {
    return stream.pipe(gulp.dest(versionPath))
  })
  return es.merge.apply(null, tasks)
}

function getMajorVersion () {
  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]
  return majorVersion
}

gulp.task('build:release', function () {
  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]

  var versionPath = './dist/cdn/' + majorVersion
  var prodPath = './dist/'

  var integrations = require('./release/integrations')
  var version = require('./package.json').version

  var tasks = Object.keys(integrations).map(function (key) {
    var integration = integrations[key]
    var integrationName = key
    var mainStream = createBuildStream(integration.entry, version)
      .pipe(gulp.dest(versionPath))
      .pipe(gulp.dest(prodPath))
      .pipe(gulp.dest(prodPath + integrationName))
      .pipe(rename({
        extname: '.min.js'
      }))
      .pipe(uglify())
      .pipe(gulp.dest(versionPath))
      .pipe(gulp.dest(prodPath))
      .pipe(gulp.dest(prodPath + integrationName))

    var filename = integration.entry.split('/')
    filename = filename[filename.length - 1]

    var packagejson = gulp.src(['./release/templates/*.json'])
      .pipe(jeditor({
        'name': integrationName,
        'version': version,
        'main': filename,
        'description': integration.description
      }))
      .pipe(gulp.dest(prodPath + integrationName))

    return es.merge.apply(null, [mainStream, packagejson, gulp.src(['LICENSE']).pipe(gulp.dest(prodPath + integrationName))])
  })

  return es.merge.apply(null, tasks)
})

gulp.task('build', function () {
  var integrations = require('./release/integrations')
  var version = require('./package.json').version

  integrations['opbeat-angular.e2e'] = {
    entry: './test/e2e/angular/opbeat-angular.e2e.js'
  }

  var tasks = Object.keys(integrations).map(function (key) {
    var entry = integrations[key].entry
    // var version = integrations[key].version
    return createBuildStream(entry, version)
      .pipe(gulp.dest('./dist/dev/'))
      .pipe(rename({
        extname: '.min.js'
      }))
      .pipe(uglify())
      .pipe(gulp.dest('./dist/dev/'))
  })

  return es.merge.apply(null, tasks)
})

// Development mode
gulp.task('watch', [], function (cb) {
  gulp.run(
    'build',
    'server'
  )

  // Watch JS files
  gulp.watch(['libs/**', 'src/**'], function () { runSequence('build', 'karma-run') })
  console.log('\nExample site running on http://localhost:7000/\n')
})

//
// Deploy task
//
gulp.task('deploy', ['build:release'], function () {
  // Load options from file
  awsoptions = JSON.parse(fs.readFileSync('aws.json'))

  // Hardcoded bucketname, to avoid mistakes
  awsoptions.params = {
    Bucket: 'opbeat-js-cdn'
  }

  // Create new publisher
  var publisher = awspublish.create(awsoptions)

  // Set headers
  var headers = {
    'Cache-Control': 'max-age=1800, public'
  }

  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]

  var versionPath = './dist/cdn/**'

  console.warn('Uploading All files in:', versionPath)

  return gulp.src([versionPath])
    // Gzip
    .pipe(awspublish.gzip())
    // Publish files with headers
    .pipe(publisher.publish(headers))
    // Create a cache file to speed up consecutive uploads
    .pipe(publisher.cache())
    // Print upload updates to console
    .pipe(awspublish.reporter())
})

function runKarma (configFile, done) {
  var exec = require('child_process').exec

  var cmd = process.platform === 'win32' ? 'node_modules\\.bin\\karma run ' :
    'node node_modules/.bin/karma run '
  cmd += configFile
  exec(cmd, function (e, stdout) {
    // ignore errors, we don't want to fail the build in the interactive (non-ci) mode
    // karma server will print all test failures
    done()
  })
}

gulp.task('karma-run', function (done) {
  // run the run command in a new process to avoid duplicate logging by both server and runner from
  // a single process
  runKarma('karma.conf.js', done)
})

gulp.task('test', function (done) {
  new karma.Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start()
})

gulp.task('test:e2e:protractor', function () {
  var protractor = require('gulp-protractor').protractor

  return gulp.src(['test/e2e/**/*.pspec.js'])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('error', function (e) { throw e })
})

// Run end-to-end tests on the local machine using webdriver configuration
gulp.task('test:e2e:run', ['test:e2e:protractor'], function (done) {
  gulp.src('wdio.conf.js')
    .pipe(webdriver())
    .on('error', function () {
      return process.exit(1)
    })
    .on('end', function () {
      return process.exit(0)
    })
})

gulp.task('test:e2e:phantomjs', function () {
  var failSafeStream = gulp.src('wdio.phantomjs.conf.js')
    .pipe(webdriver())
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return failSafeStream
})

gulp.task('test:e2e:sauceconnect:failsafe', function () {
  var failSafeStream = gulp.src('wdio.failsafe.conf.js')
    .pipe(webdriver(webdriverConfig))
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return failSafeStream
})

// Run end-to-end tests remotely in saucelabs using webdriver configuration
gulp.task('test:e2e:sauceconnect', ['test:e2e:sauceconnect:failsafe'], function () {
  var e2eStream = gulp.src('wdio.sauce.conf.js')
    .pipe(webdriver(webdriverConfig))
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return e2eStream
})

// Launch sauce connect and connect
gulp.task('test:e2e:launchsauceconnect', function (done) {
  var sauceConnectLauncher = require('sauce-connect-launcher')

  var config = {
    username: webdriverConfig.user,
    accessKey: webdriverConfig.key,
    logger: console.log
  }

  var tryConnect = function (maxAttempts, currAttempts, done) {
    sauceConnectLauncher(config, function (err, sauceConnectProcess) {
      if (err) {
        console.error(err.message)
        if (currAttempts <= maxAttempts) {
          console.log('Retrying... (attempt ' + currAttempts + ' of ' + maxAttempts + ')')
          tryConnect(maxAttempts, ++currAttempts, done)
        } else {
          return process.exit(1)
        }
      } else {
        console.log('Sauce Connect ready')
        done()
      }
    })
  }

  tryConnect(3, 1, done)
})

// Serve test application
gulp.task('test:e2e:serve', function () {
  return connect.server({
    root: ['test/e2e', 'src', './'],
    port: 8000,
    livereload: false,
    open: false,
    middleware: function (connect, opt) {
      var middlewares = []
      middlewares.push(connect.favicon())
      return middlewares
    }
  })
})

function onExit (callback) {
  function exitHandler (err) {
    try {
      callback(err)
    }
    finally {
      if (err) console.log(err.stack)
    }
  }

  process.on('exit', exitHandler)

  process.on('SIGINT', exitHandler)

  process.on('uncaughtException', exitHandler)
}

function startSelenium (callback, manualStop) {
  selenium.install({ logger: console.log }, function (installError) {
    if (installError) {
      console.log('Error while installing selenium:', installError)
    }
    selenium.start(function (startError, child) {
      if (startError) {
        console.log('Error while starting selenium:', startError)
        return process.exit(1)
      } else {
        console.log('Selenium started!')
        function killSelenium () {
          child.kill()
          console.log('Just killed selenium!')
        }
        if (manualStop) {
          callback(killSelenium)
        }else {
          onExit(killSelenium)
          callback()
        }
      }
    })
  })
}

// Install and start selenium
gulp.task('test:e2e:selenium', function (done) {
  startSelenium(function () {
    done()
  })
})

gulp.task('test:e2e:start-local', ['test:e2e:serve', 'test:e2e:selenium'])

// Run all required tasks to perform remote end-to-end testing
gulp.task('test:e2e:start-sauce', function (done) {
  runSequence('build', 'test:e2e:launchsauceconnect', function () {
    console.log('All tasks completed.')
  })
})

gulp.task('test:e2e', function (done) {
  runSequence(['build', 'build:release', 'test:e2e:start-local'], ['test:e2e:protractor', 'test:e2e:phantomjs', 'test:e2e:launchsauceconnect'], 'test:e2e:sauceconnect', function (err) {
    if (err) {
      return taskFailed(err)
    } else {
      return sequenceSucceeded(done)
    }
  })
})

function taskFailed (err) {
  var exitCode = 2
  console.log('[ERROR] gulp build task failed', err)
  console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode)
  return process.exit(exitCode)
}

function sequenceSucceeded (done) {
  console.log('All tasks completed.')
  done()
  return process.exit(0)
}

gulp.task('test:unit:sauce', function (done) {
  runSequence(['build', 'test:e2e:launchsauceconnect'], 'test', function (err) {
    if (err) {
      return taskFailed(err)
    } else {
      return sequenceSucceeded(done)
    }
  })
})

gulp.task('watch:e2e', ['e2e-serve', 'selenium-start'], function (done) {
  gulp.watch(['test/e2e/**'], function () {
    runSequence('test:e2e')
  })
})

gulp.task('default', taskListing)
<commit_msg>add no-ssl-bump-domains option to sauce launcher<commit_after>/*eslint-disable */

var fs = require('fs')
var gulp = require('gulp')
var source = require('vinyl-source-stream')
var rename = require('gulp-rename')
var browserify = require('browserify')
var buffer = require('vinyl-buffer')
var uglify = require('gulp-uglify')
var taskListing = require('gulp-task-listing')
var awspublish = require('gulp-awspublish')
var injectVersion = require('gulp-inject-version')
var derequire = require('gulp-derequire')
var es = require('event-stream')
var karma = require('karma')
var runSequence = require('run-sequence')
var webdriver = require('gulp-webdriver')
var selenium = require('selenium-standalone')
var replace = require('gulp-replace')

var connect = require('gulp-connect')

require('gulp-release-tasks')(gulp)

var jeditor = require('gulp-json-editor')

var webdriverConfig = {
  user: process.env.SAUCE_USERNAME || 'opbeat-angular',
  key: process.env.SAUCE_ACCESS_KEY || 'bfc1a656-542b-4893-bdef-a7ac20256fa9',
  host: process.env.SAUCE_HOST || 'ondemand.saucelabs.com',
  port: process.env.SAUCE_PORT || 80,
  baseUrl: process.env.SAUCE_BASEURL || 'http://localhost:8000'
}

// Static file server
gulp.task('examples:serve', function () {
  connect.server({
    root: ['examples', 'dist'],
    port: 7000,
    livereload: false,
    open: false
  })
})

function createBuildStream (mainFilePath, version) {
  if (typeof version !== 'string') {
    throw new Error(mainFilePath + ' Expected version as string but got:' + version)
  }

  return browserify({
    entries: [mainFilePath],
    standalone: '',
    insertGlobalVars: { define: function () { return 'undefined'; }, process: function () { return 'undefined'; } }
  })
    .bundle()
    .pipe(source(mainFilePath))
    .pipe(rename({ dirname: '' }))
    .pipe(buffer())
    .pipe(replace(
      new RegExp(RegExp.escape('%%VERSION%%'), 'g'),
      'v' + version
    ))
    .pipe(derequire())
}

function writeToDestinations (stream, dests) {
  var tasks = dests.map(function (destPath) {
    return stream.pipe(gulp.dest(versionPath))
  })
  return es.merge.apply(null, tasks)
}

function getMajorVersion () {
  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]
  return majorVersion
}

gulp.task('build:release', function () {
  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]

  var versionPath = './dist/cdn/' + majorVersion
  var prodPath = './dist/'

  var integrations = require('./release/integrations')
  var version = require('./package.json').version

  var tasks = Object.keys(integrations).map(function (key) {
    var integration = integrations[key]
    var integrationName = key
    var mainStream = createBuildStream(integration.entry, version)
      .pipe(gulp.dest(versionPath))
      .pipe(gulp.dest(prodPath))
      .pipe(gulp.dest(prodPath + integrationName))
      .pipe(rename({
        extname: '.min.js'
      }))
      .pipe(uglify())
      .pipe(gulp.dest(versionPath))
      .pipe(gulp.dest(prodPath))
      .pipe(gulp.dest(prodPath + integrationName))

    var filename = integration.entry.split('/')
    filename = filename[filename.length - 1]

    var packagejson = gulp.src(['./release/templates/*.json'])
      .pipe(jeditor({
        'name': integrationName,
        'version': version,
        'main': filename,
        'description': integration.description
      }))
      .pipe(gulp.dest(prodPath + integrationName))

    return es.merge.apply(null, [mainStream, packagejson, gulp.src(['LICENSE']).pipe(gulp.dest(prodPath + integrationName))])
  })

  return es.merge.apply(null, tasks)
})

gulp.task('build', function () {
  var integrations = require('./release/integrations')
  var version = require('./package.json').version

  integrations['opbeat-angular.e2e'] = {
    entry: './test/e2e/angular/opbeat-angular.e2e.js'
  }

  var tasks = Object.keys(integrations).map(function (key) {
    var entry = integrations[key].entry
    // var version = integrations[key].version
    return createBuildStream(entry, version)
      .pipe(gulp.dest('./dist/dev/'))
      .pipe(rename({
        extname: '.min.js'
      }))
      .pipe(uglify())
      .pipe(gulp.dest('./dist/dev/'))
  })

  return es.merge.apply(null, tasks)
})

// Development mode
gulp.task('watch', [], function (cb) {
  gulp.run(
    'build',
    'server'
  )

  // Watch JS files
  gulp.watch(['libs/**', 'src/**'], function () { runSequence('build', 'karma-run') })
  console.log('\nExample site running on http://localhost:7000/\n')
})

//
// Deploy task
//
gulp.task('deploy', ['build:release'], function () {
  // Load options from file
  awsoptions = JSON.parse(fs.readFileSync('aws.json'))

  // Hardcoded bucketname, to avoid mistakes
  awsoptions.params = {
    Bucket: 'opbeat-js-cdn'
  }

  // Create new publisher
  var publisher = awspublish.create(awsoptions)

  // Set headers
  var headers = {
    'Cache-Control': 'max-age=1800, public'
  }

  var version = require('./package').version
  var majorVersion = version.match(/^(\d).(\d).(\d)/)[1]

  var versionPath = './dist/cdn/**'

  console.warn('Uploading All files in:', versionPath)

  return gulp.src([versionPath])
    // Gzip
    .pipe(awspublish.gzip())
    // Publish files with headers
    .pipe(publisher.publish(headers))
    // Create a cache file to speed up consecutive uploads
    .pipe(publisher.cache())
    // Print upload updates to console
    .pipe(awspublish.reporter())
})

function runKarma (configFile, done) {
  var exec = require('child_process').exec

  var cmd = process.platform === 'win32' ? 'node_modules\\.bin\\karma run ' :
    'node node_modules/.bin/karma run '
  cmd += configFile
  exec(cmd, function (e, stdout) {
    // ignore errors, we don't want to fail the build in the interactive (non-ci) mode
    // karma server will print all test failures
    done()
  })
}

gulp.task('karma-run', function (done) {
  // run the run command in a new process to avoid duplicate logging by both server and runner from
  // a single process
  runKarma('karma.conf.js', done)
})

gulp.task('test', function (done) {
  new karma.Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start()
})

gulp.task('test:e2e:protractor', function () {
  var protractor = require('gulp-protractor').protractor

  return gulp.src(['test/e2e/**/*.pspec.js'])
    .pipe(protractor({
      configFile: 'protractor.conf.js'
    }))
    .on('error', function (e) { throw e })
})

// Run end-to-end tests on the local machine using webdriver configuration
gulp.task('test:e2e:run', ['test:e2e:protractor'], function (done) {
  gulp.src('wdio.conf.js')
    .pipe(webdriver())
    .on('error', function () {
      return process.exit(1)
    })
    .on('end', function () {
      return process.exit(0)
    })
})

gulp.task('test:e2e:phantomjs', function () {
  var failSafeStream = gulp.src('wdio.phantomjs.conf.js')
    .pipe(webdriver())
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return failSafeStream
})

gulp.task('test:e2e:sauceconnect:failsafe', function () {
  var failSafeStream = gulp.src('wdio.failsafe.conf.js')
    .pipe(webdriver(webdriverConfig))
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return failSafeStream
})

// Run end-to-end tests remotely in saucelabs using webdriver configuration
gulp.task('test:e2e:sauceconnect', ['test:e2e:sauceconnect:failsafe'], function () {
  var e2eStream = gulp.src('wdio.sauce.conf.js')
    .pipe(webdriver(webdriverConfig))
    .on('error', function () {
      console.log('Exiting process with status 1')
      process.exit(1)
    })
    .on('end', function () {
      console.log('Tests complete')
    })
  return e2eStream
})

// Launch sauce connect and connect
gulp.task('test:e2e:launchsauceconnect', function (done) {
  var sauceConnectLauncher = require('sauce-connect-launcher')

  var config = {
    username: webdriverConfig.user,
    accessKey: webdriverConfig.key,
    logger: console.log,
    noSslBumpDomains: 'all'
  }

  var tryConnect = function (maxAttempts, currAttempts, done) {
    sauceConnectLauncher(config, function (err, sauceConnectProcess) {
      if (err) {
        console.error(err.message)
        if (currAttempts <= maxAttempts) {
          console.log('Retrying... (attempt ' + currAttempts + ' of ' + maxAttempts + ')')
          tryConnect(maxAttempts, ++currAttempts, done)
        } else {
          return process.exit(1)
        }
      } else {
        console.log('Sauce Connect ready')
        done()
      }
    })
  }

  tryConnect(3, 1, done)
})

// Serve test application
gulp.task('test:e2e:serve', function () {
  return connect.server({
    root: ['test/e2e', 'src', './'],
    port: 8000,
    livereload: false,
    open: false,
    middleware: function (connect, opt) {
      var middlewares = []
      middlewares.push(connect.favicon())
      return middlewares
    }
  })
})

function onExit (callback) {
  function exitHandler (err) {
    try {
      callback(err)
    }
    finally {
      if (err) console.log(err.stack)
    }
  }

  process.on('exit', exitHandler)

  process.on('SIGINT', exitHandler)

  process.on('uncaughtException', exitHandler)
}

function startSelenium (callback, manualStop) {
  selenium.install({ logger: console.log }, function (installError) {
    if (installError) {
      console.log('Error while installing selenium:', installError)
    }
    selenium.start(function (startError, child) {
      if (startError) {
        console.log('Error while starting selenium:', startError)
        return process.exit(1)
      } else {
        console.log('Selenium started!')
        function killSelenium () {
          child.kill()
          console.log('Just killed selenium!')
        }
        if (manualStop) {
          callback(killSelenium)
        }else {
          onExit(killSelenium)
          callback()
        }
      }
    })
  })
}

// Install and start selenium
gulp.task('test:e2e:selenium', function (done) {
  startSelenium(function () {
    done()
  })
})

gulp.task('test:e2e:start-local', ['test:e2e:serve', 'test:e2e:selenium'])

// Run all required tasks to perform remote end-to-end testing
gulp.task('test:e2e:start-sauce', function (done) {
  runSequence('build', 'test:e2e:launchsauceconnect', function () {
    console.log('All tasks completed.')
  })
})

gulp.task('test:e2e', function (done) {
  runSequence(['build', 'build:release', 'test:e2e:start-local'], ['test:e2e:protractor', 'test:e2e:phantomjs', 'test:e2e:launchsauceconnect'], 'test:e2e:sauceconnect', function (err) {
    if (err) {
      return taskFailed(err)
    } else {
      return sequenceSucceeded(done)
    }
  })
})

function taskFailed (err) {
  var exitCode = 2
  console.log('[ERROR] gulp build task failed', err)
  console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode)
  return process.exit(exitCode)
}

function sequenceSucceeded (done) {
  console.log('All tasks completed.')
  done()
  return process.exit(0)
}

gulp.task('test:unit:sauce', function (done) {
  runSequence(['build', 'test:e2e:launchsauceconnect'], 'test', function (err) {
    if (err) {
      return taskFailed(err)
    } else {
      return sequenceSucceeded(done)
    }
  })
})

gulp.task('watch:e2e', ['e2e-serve', 'selenium-start'], function (done) {
  gulp.watch(['test/e2e/**'], function () {
    runSequence('test:e2e')
  })
})

gulp.task('default', taskListing)
<|endoftext|>