<commit_before>// GULPFILE
// - - - - - - - - - - - - - - -
// This file processes all of the assets in the "src" folder
// and outputs the finished files in the "dist" folder.

// 1. LIBRARIES
// - - - - - - - - - - - - - - -
const { src, pipe, dest, series, parallel, watch } = require('gulp');
const rollupPluginCommonjs = require('rollup-plugin-commonjs');
const rollupPluginNodeResolve = require('rollup-plugin-node-resolve');
const streamqueue = require('streamqueue');
const stylish = require('jshint-stylish');

const plugins = {};
plugins.addSrc = require('gulp-add-src');
plugins.babel = require('gulp-babel');
plugins.cleanCSS = require('gulp-clean-css');
plugins.concat = require('gulp-concat');
plugins.cssUrlAdjuster = require('gulp-css-url-adjuster');
plugins.jshint = require('gulp-jshint');
plugins.prettyerror = require('gulp-prettyerror');
plugins.rollup = require('gulp-better-rollup')
plugins.sass = require('gulp-sass')(require('sass'));
plugins.sassLint = require('gulp-sass-lint');
plugins.uglify = require('gulp-uglify');

// 2. CONFIGURATION
// - - - - - - - - - - - - - - -
const paths = {
  src: 'app/assets/',
  dist: 'app/static/',
  templates: 'app/templates/',
  npm: 'node_modules/',
  toolkit: 'node_modules/govuk_frontend_toolkit/',
  govuk_frontend: 'node_modules/govuk-frontend/'
};
// Rewrite /static prefix for URLs in CSS files
let staticPathMatcher = new RegExp('^\/static\/');
if (process.env.NOTIFY_ENVIRONMENT == 'development') { // pass through if on development
  staticPathMatcher = url => url;
}

// 3. TASKS
// - - - - - - - - - - - - - - -

// Move GOV.UK template resources

const copy = {
  error_pages: () => {
    return src(paths.src + 'error_pages/**/*')
      .pipe(dest(paths.dist + 'error_pages/'))
  },
  govuk_frontend: {
    fonts: () => {
      return src(paths.govuk_frontend + 'assets/fonts/**/*')
        .pipe(dest(paths.dist + 'fonts/'));
    },
    templates: (cb) => {
      // Put names of GOVUK Frontend templates here
      const _templates = [
        'template',
        'skip-link',
        'header',
        'footer',
        'back-link',
        'details',
        'button',
        'error-message',
        'fieldset',
        'hint',
        'label',
        'checkboxes',
        'radios',
        'input',
        'inset-text',
        'textarea',
        'summary-list'
      ];
      let done = 0;

      // Copy the templates for each component across, preserving their folder structure
      _templates.forEach(name => {
        let _src = [
          paths.govuk_frontend + 'components/' + name + '/macro.njk',
          paths.govuk_frontend + 'components/' + name + '/template.njk'
        ];
        let _dest = paths.templates + 'vendor/govuk-frontend/components/' + name;

        // template.njk isn't a component
        if (name === 'template') {
          _src = paths.govuk_frontend + 'template.njk';
          _dest = paths.templates + 'vendor/govuk-frontend';
        }

        src(_src)
        .pipe(
          dest(_dest)
          .on('end', () => { // resolve promise if all copied
            done = done + 1;
            if (done === _templates.length) {
              cb();
            }
          })
        )
      });
    }
  },
  leaflet: {
    js: () => {
      return src(paths.npm + 'leaflet/dist/leaflet.js')
        .pipe(dest(paths.dist + 'javascripts/'))
    }
  }
};

const javascripts = () => {
  // JS from third-party sources
  // We assume none of it will need to pass through Babel
  const vendored = src(paths.src + 'javascripts/esm/all.mjs')
    // Use Rollup to combine all JS in ECMAScript module format into a Immediately Invoked Function
    // Expression (IIFE) to:
    // - deliver it in one bundle
    // - allow it to run in browsers without support for JS Modules
    .pipe(plugins.rollup(
      {
        plugins: [
          // determine module entry points from either 'module' or 'main' fields in package.json
          rollupPluginNodeResolve({
            mainFields: ['module', 'main']
          }),
          // gulp rollup runs on nodeJS so reads modules in commonJS format
          // this adds node_modules to the require path so it can find the GOVUK Frontend modules
          rollupPluginCommonjs({
            include: 'node_modules/**'
          })
        ]
      },
      {
        format: 'iife',
        name: 'GOVUK'
      }
    ))
    // return a stream which pipes these files before the ECMAScript modules bundle
    .pipe(plugins.addSrc.prepend([
      paths.npm + 'hogan.js/dist/hogan-3.0.2.js',
      paths.npm + 'jquery/dist/jquery.min.js',
      paths.npm + 'query-command-supported/dist/queryCommandSupported.min.js',
      paths.npm + 'timeago/jquery.timeago.js',
      paths.npm + 'textarea-caret/index.js',
      paths.npm + 'cbor-js/cbor.js'
    ]));

  // JS local to this application
  const local = src([
    paths.src + 'javascripts/modules.js',
    paths.src + 'javascripts/govuk-frontend-toolkit/show-hide-content.js',
    paths.src + 'javascripts/govuk/cookie-functions.js',
    paths.src + 'javascripts/consent.js',
    paths.src + 'javascripts/analytics/analytics.js',
    paths.src + 'javascripts/analytics/init.js',
    paths.src + 'javascripts/cookieMessage.js',
    paths.src + 'javascripts/cookieSettings.js',
    paths.src + 'javascripts/stick-to-window-when-scrolling.js',
    paths.src + 'javascripts/copyToClipboard.js',
    paths.src + 'javascripts/autofocus.js',
    paths.src + 'javascripts/enhancedTextbox.js',
    paths.src + 'javascripts/fileUpload.js',
    paths.src + 'javascripts/radioSelect.js',
    paths.src + 'javascripts/updateContent.js',
    paths.src + 'javascripts/listEntry.js',
    paths.src + 'javascripts/liveSearch.js',
    paths.src + 'javascripts/errorTracking.js',
    paths.src + 'javascripts/preventDuplicateFormSubmissions.js',
    paths.src + 'javascripts/fullscreenTable.js',
    paths.src + 'javascripts/previewPane.js',
    paths.src + 'javascripts/colourPreview.js',
    paths.src + 'javascripts/templateFolderForm.js',
    paths.src + 'javascripts/addEmailBrandingOptionsForm.js',
    paths.src + 'javascripts/collapsibleCheckboxes.js',
    paths.src + 'javascripts/radioSlider.js',
    paths.src + 'javascripts/registerSecurityKey.js',
    paths.src + 'javascripts/authenticateSecurityKey.js',
    paths.src + 'javascripts/updateStatus.js',
    paths.src + 'javascripts/errorBanner.js',
    paths.src + 'javascripts/homepage.js',
    paths.src + 'javascripts/main.js',
  ])
  .pipe(plugins.prettyerror())
  .pipe(plugins.babel({
    presets: ['@babel/preset-env']
  }));

  // return single stream of all vinyl objects piped from the end of the vendored stream, then
  // those from the end of the local stream
  return streamqueue({ objectMode: true }, vendored, local)
    .pipe(plugins.uglify())
    .pipe(plugins.concat('all.js'))
    .pipe(dest(paths.dist + 'javascripts/'))
};

const sass = () => {
  return src([
      paths.src + '/stylesheets/main*.scss',
      paths.src + '/stylesheets/map.scss',
      paths.src + '/stylesheets/print.scss'
    ])
    .pipe(plugins.prettyerror())
    .pipe(plugins.sass.sync({
      includePaths: [
        paths.npm + 'govuk-elements-sass/public/sass/',
        paths.toolkit + 'stylesheets/',
        paths.govuk_frontend,
        paths.npm
      ]
    }))
    .pipe(plugins.cssUrlAdjuster({
      replace: [staticPathMatcher, '/']
    }))
    // cssUrlAdjuster outputs uncompressed CSS so we need to perform the compression here
    .pipe(plugins.cleanCSS({ compatibility: '*' }))
    .pipe(dest(paths.dist + 'stylesheets/'))
};

// Copy images

const images = () => {
  return src([
      paths.src + 'images/**/*',
      paths.toolkit + 'images/**/*',
      paths.template + 'assets/images/**/*',
      paths.govuk_frontend + 'assets/images/**/*'
    ])
    .pipe(dest(paths.dist + 'images/'))
};

const watchFiles = {
  javascripts: (cb) => {
    watch([paths.src + 'javascripts/**/*'], javascripts);
    cb();
  },
  sass: (cb) => {
    watch([paths.src + 'stylesheets/**/*'], sass);
    cb();
  },
  images: (cb) => {
    watch([paths.src + 'images/**/*'], images);
    cb();
  },
  self: (cb) => {
    watch(['gulpfile.js'], defaultTask);
    cb();
  }
};

const lint = {
  'sass': () => {
    return src([
        paths.src + 'stylesheets/*.scss',
        paths.src + 'stylesheets/components/*.scss',
        paths.src + 'stylesheets/views/*.scss',
      ])
      .pipe(plugins.sassLint({
        'options': { 'formatter': 'stylish' },
        'rules': { 'mixins-before-declarations': [2, { 'exclude': ['media', 'govuk-media-query'] } ] }
      }))
      .pipe(plugins.sassLint.format())
      .pipe(plugins.sassLint.failOnError());
  },
  'js': (cb) => {
    return src(
        paths.src + 'javascripts/**/*.js'
      )
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter(stylish))
      .pipe(plugins.jshint.reporter('fail'))
  }
};

// Default: compile everything
const defaultTask = parallel(
  parallel(
    copy.govuk_frontend.fonts,
    copy.govuk_frontend.templates,
    images,
    copy.leaflet.js
  ),
  series(
    copy.error_pages,
    series(
      javascripts
    ),
    sass
  )
);

// Watch for changes and re-run tasks
const watchForChanges = parallel(
  watchFiles.javascripts,
  watchFiles.sass,
  watchFiles.images,
  watchFiles.self
);

exports.default = defaultTask;

exports.lint = series(lint.sass, lint.js);

// Optional: recompile on changes
exports.watch = series(defaultTask, watchForChanges);
<commit_msg>Stop importing images from GOV.UK Frontend Toolkit<commit_after>// GULPFILE
// - - - - - - - - - - - - - - -
// This file processes all of the assets in the "src" folder
// and outputs the finished files in the "dist" folder.

// 1. LIBRARIES
// - - - - - - - - - - - - - - -
const { src, pipe, dest, series, parallel, watch } = require('gulp');
const rollupPluginCommonjs = require('rollup-plugin-commonjs');
const rollupPluginNodeResolve = require('rollup-plugin-node-resolve');
const streamqueue = require('streamqueue');
const stylish = require('jshint-stylish');

const plugins = {};
plugins.addSrc = require('gulp-add-src');
plugins.babel = require('gulp-babel');
plugins.cleanCSS = require('gulp-clean-css');
plugins.concat = require('gulp-concat');
plugins.cssUrlAdjuster = require('gulp-css-url-adjuster');
plugins.jshint = require('gulp-jshint');
plugins.prettyerror = require('gulp-prettyerror');
plugins.rollup = require('gulp-better-rollup')
plugins.sass = require('gulp-sass')(require('sass'));
plugins.sassLint = require('gulp-sass-lint');
plugins.uglify = require('gulp-uglify');

// 2. CONFIGURATION
// - - - - - - - - - - - - - - -
const paths = {
  src: 'app/assets/',
  dist: 'app/static/',
  templates: 'app/templates/',
  npm: 'node_modules/',
  toolkit: 'node_modules/govuk_frontend_toolkit/',
  govuk_frontend: 'node_modules/govuk-frontend/'
};
// Rewrite /static prefix for URLs in CSS files
let staticPathMatcher = new RegExp('^\/static\/');
if (process.env.NOTIFY_ENVIRONMENT == 'development') { // pass through if on development
  staticPathMatcher = url => url;
}

// 3. TASKS
// - - - - - - - - - - - - - - -

// Move GOV.UK template resources

const copy = {
  error_pages: () => {
    return src(paths.src + 'error_pages/**/*')
      .pipe(dest(paths.dist + 'error_pages/'))
  },
  govuk_frontend: {
    fonts: () => {
      return src(paths.govuk_frontend + 'assets/fonts/**/*')
        .pipe(dest(paths.dist + 'fonts/'));
    },
    templates: (cb) => {
      // Put names of GOVUK Frontend templates here
      const _templates = [
        'template',
        'skip-link',
        'header',
        'footer',
        'back-link',
        'details',
        'button',
        'error-message',
        'fieldset',
        'hint',
        'label',
        'checkboxes',
        'radios',
        'input',
        'inset-text',
        'textarea',
        'summary-list'
      ];
      let done = 0;

      // Copy the templates for each component across, preserving their folder structure
      _templates.forEach(name => {
        let _src = [
          paths.govuk_frontend + 'components/' + name + '/macro.njk',
          paths.govuk_frontend + 'components/' + name + '/template.njk'
        ];
        let _dest = paths.templates + 'vendor/govuk-frontend/components/' + name;

        // template.njk isn't a component
        if (name === 'template') {
          _src = paths.govuk_frontend + 'template.njk';
          _dest = paths.templates + 'vendor/govuk-frontend';
        }

        src(_src)
        .pipe(
          dest(_dest)
          .on('end', () => { // resolve promise if all copied
            done = done + 1;
            if (done === _templates.length) {
              cb();
            }
          })
        )
      });
    }
  },
  leaflet: {
    js: () => {
      return src(paths.npm + 'leaflet/dist/leaflet.js')
        .pipe(dest(paths.dist + 'javascripts/'))
    }
  }
};

const javascripts = () => {
  // JS from third-party sources
  // We assume none of it will need to pass through Babel
  const vendored = src(paths.src + 'javascripts/esm/all.mjs')
    // Use Rollup to combine all JS in ECMAScript module format into a Immediately Invoked Function
    // Expression (IIFE) to:
    // - deliver it in one bundle
    // - allow it to run in browsers without support for JS Modules
    .pipe(plugins.rollup(
      {
        plugins: [
          // determine module entry points from either 'module' or 'main' fields in package.json
          rollupPluginNodeResolve({
            mainFields: ['module', 'main']
          }),
          // gulp rollup runs on nodeJS so reads modules in commonJS format
          // this adds node_modules to the require path so it can find the GOVUK Frontend modules
          rollupPluginCommonjs({
            include: 'node_modules/**'
          })
        ]
      },
      {
        format: 'iife',
        name: 'GOVUK'
      }
    ))
    // return a stream which pipes these files before the ECMAScript modules bundle
    .pipe(plugins.addSrc.prepend([
      paths.npm + 'hogan.js/dist/hogan-3.0.2.js',
      paths.npm + 'jquery/dist/jquery.min.js',
      paths.npm + 'query-command-supported/dist/queryCommandSupported.min.js',
      paths.npm + 'timeago/jquery.timeago.js',
      paths.npm + 'textarea-caret/index.js',
      paths.npm + 'cbor-js/cbor.js'
    ]));

  // JS local to this application
  const local = src([
    paths.src + 'javascripts/modules.js',
    paths.src + 'javascripts/govuk-frontend-toolkit/show-hide-content.js',
    paths.src + 'javascripts/govuk/cookie-functions.js',
    paths.src + 'javascripts/consent.js',
    paths.src + 'javascripts/analytics/analytics.js',
    paths.src + 'javascripts/analytics/init.js',
    paths.src + 'javascripts/cookieMessage.js',
    paths.src + 'javascripts/cookieSettings.js',
    paths.src + 'javascripts/stick-to-window-when-scrolling.js',
    paths.src + 'javascripts/copyToClipboard.js',
    paths.src + 'javascripts/autofocus.js',
    paths.src + 'javascripts/enhancedTextbox.js',
    paths.src + 'javascripts/fileUpload.js',
    paths.src + 'javascripts/radioSelect.js',
    paths.src + 'javascripts/updateContent.js',
    paths.src + 'javascripts/listEntry.js',
    paths.src + 'javascripts/liveSearch.js',
    paths.src + 'javascripts/errorTracking.js',
    paths.src + 'javascripts/preventDuplicateFormSubmissions.js',
    paths.src + 'javascripts/fullscreenTable.js',
    paths.src + 'javascripts/previewPane.js',
    paths.src + 'javascripts/colourPreview.js',
    paths.src + 'javascripts/templateFolderForm.js',
    paths.src + 'javascripts/addEmailBrandingOptionsForm.js',
    paths.src + 'javascripts/collapsibleCheckboxes.js',
    paths.src + 'javascripts/radioSlider.js',
    paths.src + 'javascripts/registerSecurityKey.js',
    paths.src + 'javascripts/authenticateSecurityKey.js',
    paths.src + 'javascripts/updateStatus.js',
    paths.src + 'javascripts/errorBanner.js',
    paths.src + 'javascripts/homepage.js',
    paths.src + 'javascripts/main.js',
  ])
  .pipe(plugins.prettyerror())
  .pipe(plugins.babel({
    presets: ['@babel/preset-env']
  }));

  // return single stream of all vinyl objects piped from the end of the vendored stream, then
  // those from the end of the local stream
  return streamqueue({ objectMode: true }, vendored, local)
    .pipe(plugins.uglify())
    .pipe(plugins.concat('all.js'))
    .pipe(dest(paths.dist + 'javascripts/'))
};

const sass = () => {
  return src([
      paths.src + '/stylesheets/main*.scss',
      paths.src + '/stylesheets/map.scss',
      paths.src + '/stylesheets/print.scss'
    ])
    .pipe(plugins.prettyerror())
    .pipe(plugins.sass.sync({
      includePaths: [
        paths.npm + 'govuk-elements-sass/public/sass/',
        paths.toolkit + 'stylesheets/',
        paths.govuk_frontend,
        paths.npm
      ]
    }))
    .pipe(plugins.cssUrlAdjuster({
      replace: [staticPathMatcher, '/']
    }))
    // cssUrlAdjuster outputs uncompressed CSS so we need to perform the compression here
    .pipe(plugins.cleanCSS({ compatibility: '*' }))
    .pipe(dest(paths.dist + 'stylesheets/'))
};

// Copy images

const images = () => {
  return src([
      paths.src + 'images/**/*',
      paths.template + 'assets/images/**/*',
      paths.govuk_frontend + 'assets/images/**/*'
    ])
    .pipe(dest(paths.dist + 'images/'))
};

const watchFiles = {
  javascripts: (cb) => {
    watch([paths.src + 'javascripts/**/*'], javascripts);
    cb();
  },
  sass: (cb) => {
    watch([paths.src + 'stylesheets/**/*'], sass);
    cb();
  },
  images: (cb) => {
    watch([paths.src + 'images/**/*'], images);
    cb();
  },
  self: (cb) => {
    watch(['gulpfile.js'], defaultTask);
    cb();
  }
};

const lint = {
  'sass': () => {
    return src([
        paths.src + 'stylesheets/*.scss',
        paths.src + 'stylesheets/components/*.scss',
        paths.src + 'stylesheets/views/*.scss',
      ])
      .pipe(plugins.sassLint({
        'options': { 'formatter': 'stylish' },
        'rules': { 'mixins-before-declarations': [2, { 'exclude': ['media', 'govuk-media-query'] } ] }
      }))
      .pipe(plugins.sassLint.format())
      .pipe(plugins.sassLint.failOnError());
  },
  'js': (cb) => {
    return src(
        paths.src + 'javascripts/**/*.js'
      )
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter(stylish))
      .pipe(plugins.jshint.reporter('fail'))
  }
};

// Default: compile everything
const defaultTask = parallel(
  parallel(
    copy.govuk_frontend.fonts,
    copy.govuk_frontend.templates,
    images,
    copy.leaflet.js
  ),
  series(
    copy.error_pages,
    series(
      javascripts
    ),
    sass
  )
);

// Watch for changes and re-run tasks
const watchForChanges = parallel(
  watchFiles.javascripts,
  watchFiles.sass,
  watchFiles.images,
  watchFiles.self
);

exports.default = defaultTask;

exports.lint = series(lint.sass, lint.js);

// Optional: recompile on changes
exports.watch = series(defaultTask, watchForChanges);
<|endoftext|>


<commit_before>/*******************************
            Set-up
*******************************/

var
  gulp         = require('gulp-help')(require('gulp')),

  // read user config to know what task to load
  config       = require('./tasks/config/user'),

  // watch for file changes and build
  watch        = require('./tasks/watch'),

  // build all files
  build        = require('./tasks/build'),
  buildJS      = require('./tasks/build/javascript'),
  buildCSS     = require('./tasks/build/css'),
  buildAssets  = require('./tasks/build/assets'),

  // utility tasks
  clean        = require('./tasks/clean'),
  version      = require('./tasks/version'),

  // install tasks
  install      = require('./tasks/install'),
  checkInstall = require('./tasks/check-install'),

  // docs tasks
  serveDocs    = require('./tasks/docs/serve'),
  buildDocs    = require('./tasks/docs/build')
;

/*******************************
             Tasks
*******************************/

gulp.task('default', false, [
  'check-install'
]);

gulp.task('watch', 'Watch for site/theme changes', watch);

gulp.task('build', 'Builds all files from source', build);
gulp.task('build-javascript', 'Builds all javascript from source', buildJS);
gulp.task('build-css', 'Builds all css from source', buildCSS);
gulp.task('build-assets', 'Copies all assets from source', buildAssets);

gulp.task('clean', 'Clean dist folder', clean);
gulp.task('version', 'Displays current version of pegaMultiselect', version);

gulp.task('install', 'Runs set-up', install);
gulp.task('check-install', 'Displays current version of pegaMultiselect', checkInstall);

/*--------------
      Docs
---------------*/

/*
  Lets you serve files to a local documentation instance
  https://github.com/pegaMultiselect/Multiselect-Pega-Docs/
*/

gulp.task('serve-docs', 'Serve file changes to SUI Docs', serveDocs);
gulp.task('build-docs', 'Build all files and add to SUI Docs', buildDocs);

/*--------------
      RTL
---------------*/

if(config.rtl) {
  gulp.task('watch-rtl', 'Watch files as RTL', watchRTL);
  gulp.task('build-rtl', 'Build all files as RTL', buildRTL);
}

/* Admin Tasks */
if(config.admin) {
  require('./tasks/collections/admin')(gulp);
}
<commit_msg>js build<commit_after>/*******************************
            Set-up
*******************************/

var
  gulp         = require('gulp-help')(require('gulp')),

  // read user config to know what task to load
  config       = require('./tasks/config/user'),

  // watch for file changes and build
  watch        = require('./tasks/watch'),

  // build all files
  build        = require('./tasks/build'),
  buildJS      = require('./tasks/build/javascript'),
  buildCSS     = require('./tasks/build/css'),
  buildAssets  = require('./tasks/build/assets'),

  // utility tasks
  clean        = require('./tasks/clean'),
  version      = require('./tasks/version'),

  // install tasks
  install      = require('./tasks/install'),
  checkInstall = require('./tasks/check-install'),

  // docs tasks
  serveDocs    = require('./tasks/docs/serve'),
  buildDocs    = require('./tasks/docs/build')
;

/*******************************
             Tasks
*******************************/

gulp.task('default', false, [
  'check-install'
]);

gulp.task('watch', 'Watch for site/theme changes', watch);

gulp.task('build', 'Builds all files from source', build);
gulp.task('build-js', 'Builds all javascript from source', buildJS);
gulp.task('build-css', 'Builds all css from source', buildCSS);
gulp.task('build-assets', 'Copies all assets from source', buildAssets);

gulp.task('clean', 'Clean dist folder', clean);
gulp.task('version', 'Displays current version of pegaMultiselect', version);

gulp.task('install', 'Runs set-up', install);
gulp.task('check-install', 'Displays current version of pegaMultiselect', checkInstall);

/*--------------
      Docs
---------------*/

/*
  Lets you serve files to a local documentation instance
  https://github.com/pegaMultiselect/Multiselect-Pega-Docs/
*/

gulp.task('serve-docs', 'Serve file changes to SUI Docs', serveDocs);
gulp.task('build-docs', 'Build all files and add to SUI Docs', buildDocs);

/*--------------
      RTL
---------------*/

if(config.rtl) {
  gulp.task('watch-rtl', 'Watch files as RTL', watchRTL);
  gulp.task('build-rtl', 'Build all files as RTL', buildRTL);
}

/* Admin Tasks */
if(config.admin) {
  require('./tasks/collections/admin')(gulp);
}
<|endoftext|>


<commit_before>// 获取依赖
const gulp = require("gulp"),
  childProcess = require("child_process"),
  electron = require("electron"),
  electron_packger = require("electron-packager"),
  os = require("os");

var packger_options = {
  dir: ".",
  icon: `${__dirname}/doc/logo.ico`,
  ignore: [
    "node_modules/.bin",
    "node_modules/electron",
    "node_modules/electron-prebuilt",
    "node_modules/electron-prebuilt-compile",
    "node_modules/electron-packager",
    ".git",
    ".gitignore",
    ".vscode",
  ],
  out: "out",
  platform: "all",
  arch: "all",
  overwrite: true,
  prune: true,
  asar: true,
};

// if ("darwin" == os.platform().toLowerCase()) {
//   packger_options.asar = false; // macOS can not read from asar
// }

function extend_options(ret) {
  for (var src_i = 1; src_i < arguments.length; ++src_i) {
    const src = arguments[src_i] || {};
    ret = ret || {};
    for (const i in src) {
      if ("object" == typeof src[i] && "object" == typeof ret[i]) {
        ret[i] = extend_options(ret[i], src[i]);
      } else {
        ret[i] = src[i];
      }
    }
  }

  return ret;
}

// 创建 gulp 任务
gulp.task("copy-libs", function (done) {
  // gulp.src('./node_modules/bootstrap/**')
  //   .pipe(gulp.dest('./src/node_modules/bootstrap'))
  //   ;
  // gulp.src('./node_modules/jquery/**')
  //   .pipe(gulp.dest('./src/node_modules/jquery'))
  //   ;
  // gulp.src('./node_modules/jquery.fancytree/**')
  //   .pipe(gulp.dest('./src/node_modules/jquery.fancytree'))
  //   ;
  // gulp.src('./node_modules/popper.js/**')
  //   .pipe(gulp.dest('./src/node_modules/popper.js'))
  //   ;

  done();
});

gulp.task(
  "run",
  gulp.series("copy-libs", function (done) {
    const args = ["."];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "debug-run",
  gulp.series("copy-libs", function (done) {
    const args = [".", "--debug"];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "debug",
  gulp.series("copy-libs", function (done) {
    const args = ["--inspect-brk=5858", "."];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "package-win32",
  gulp.series("copy-libs", function (done) {
    const os = require("os");
    if (os.platform() === "win32") {
      process.env["PATH"] =
        process.env["PATH"] + ";C:/Windows/System32/WindowsPowerShell/v1.0";
    }
    var opts = extend_options({}, packger_options, {
      platform: "win32",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-linux",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "linux",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-darwin",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "darwin",
      arch: "all",
      icon: `${__dirname}/doc/logo.icns`,
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-all",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "all",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-test",
  gulp.series("copy-libs", function (done) {
    const test_packger_options = {};
    for (const key in packger_options) {
      if (key != "icon") {
        test_packger_options[key] = packger_options[key];
      }
    }

    var opts = extend_options({}, test_packger_options, {
      platform: os.platform(),
      arch: "all",
    });

    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);
<commit_msg>Disable asar again<commit_after>// 获取依赖
const gulp = require("gulp"),
  childProcess = require("child_process"),
  electron = require("electron"),
  electron_packger = require("electron-packager"),
  os = require("os");

var packger_options = {
  dir: ".",
  icon: `${__dirname}/doc/logo.ico`,
  ignore: [
    "node_modules/.bin",
    "node_modules/electron",
    "node_modules/electron-prebuilt",
    "node_modules/electron-prebuilt-compile",
    "node_modules/electron-packager",
    ".git",
    ".gitignore",
    ".vscode",
  ],
  out: "out",
  platform: "all",
  arch: "all",
  overwrite: true,
  prune: true,
  asar: true,
};

if ("darwin" == os.platform().toLowerCase()) {
  packger_options.asar = false; // macOS can not read from asar
}

function extend_options(ret) {
  for (var src_i = 1; src_i < arguments.length; ++src_i) {
    const src = arguments[src_i] || {};
    ret = ret || {};
    for (const i in src) {
      if ("object" == typeof src[i] && "object" == typeof ret[i]) {
        ret[i] = extend_options(ret[i], src[i]);
      } else {
        ret[i] = src[i];
      }
    }
  }

  return ret;
}

// 创建 gulp 任务
gulp.task("copy-libs", function (done) {
  // gulp.src('./node_modules/bootstrap/**')
  //   .pipe(gulp.dest('./src/node_modules/bootstrap'))
  //   ;
  // gulp.src('./node_modules/jquery/**')
  //   .pipe(gulp.dest('./src/node_modules/jquery'))
  //   ;
  // gulp.src('./node_modules/jquery.fancytree/**')
  //   .pipe(gulp.dest('./src/node_modules/jquery.fancytree'))
  //   ;
  // gulp.src('./node_modules/popper.js/**')
  //   .pipe(gulp.dest('./src/node_modules/popper.js'))
  //   ;

  done();
});

gulp.task(
  "run",
  gulp.series("copy-libs", function (done) {
    const args = ["."];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "debug-run",
  gulp.series("copy-libs", function (done) {
    const args = [".", "--debug"];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "debug",
  gulp.series("copy-libs", function (done) {
    const args = ["--inspect-brk=5858", "."];
    for (const v of process.argv.slice(3)) {
      args.push(v);
    }
    console.log(args);
    childProcess.spawn(electron, args, {
      stdio: "inherit",
    });

    done();
  })
);

gulp.task(
  "package-win32",
  gulp.series("copy-libs", function (done) {
    const os = require("os");
    if (os.platform() === "win32") {
      process.env["PATH"] =
        process.env["PATH"] + ";C:/Windows/System32/WindowsPowerShell/v1.0";
    }
    var opts = extend_options({}, packger_options, {
      platform: "win32",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-linux",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "linux",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-darwin",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "darwin",
      arch: "all",
      icon: `${__dirname}/doc/logo.icns`,
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-all",
  gulp.series("copy-libs", function (done) {
    var opts = extend_options({}, packger_options, {
      platform: "all",
      arch: "all",
    });
    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);

gulp.task(
  "package-test",
  gulp.series("copy-libs", function (done) {
    const test_packger_options = {};
    for (const key in packger_options) {
      if (key != "icon") {
        test_packger_options[key] = packger_options[key];
      }
    }

    var opts = extend_options({}, test_packger_options, {
      platform: os.platform(),
      arch: "all",
    });

    electron_packger(opts, function (err, appPaths) {
      if (err) {
        console.log(`${appPaths}: ${err}`);
      }
    })
      .then(function () {
        done();
      })
      .catch(function (reason) {
        console.error(`Package failed: ${reason}`);
        done();
      });
  })
);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');

gulp.task('coverage', function(){
  return gulp.src('lib/*.js')
    .pipe($.istanbul())
    .pipe($.istanbul.hookRequire());
});

gulp.task('coverage:clean', function(callback){
  del(['coverage', 'string'], callback);
});

gulp.task('mocha', ['coverage'], function(){
  return gulp.src('test/index.js')
    .pipe($.mocha({
      reporter: 'progress',
      bail: true
    }))
    .pipe($.istanbul.writeReports());
});

gulp.task('jshint', function(){
  return gulp.src('lib/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('watch', function(){
  gulp.watch('lib/*.js', ['mocha', 'jshint']);
  gulp.watch(['test/index.js'], ['mocha']);
});

gulp.task('test', ['mocha', 'jshint']);
<commit_msg>reverted the mocha reporter<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');

gulp.task('coverage', function(){
  return gulp.src('lib/*.js')
    .pipe($.istanbul())
    .pipe($.istanbul.hookRequire());
});

gulp.task('coverage:clean', function(callback){
  del(['coverage', 'string'], callback);
});

gulp.task('mocha', ['coverage'], function(){
  return gulp.src('test/index.js')
    .pipe($.mocha({
      reporter: 'spec',
      bail: true
    }))
    .pipe($.istanbul.writeReports());
});

gulp.task('jshint', function(){
  return gulp.src('lib/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('watch', function(){
  gulp.watch('lib/*.js', ['mocha', 'jshint']);
  gulp.watch(['test/index.js'], ['mocha']);
});

gulp.task('test', ['mocha', 'jshint']);
<|endoftext|>


<commit_before>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    bower = require('gulp-bower'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    exit = require('gulp-exit'),
    watchify = require('watchify'),
    protractor = require('gulp-protractor').protractor,
    mocha = require('gulp-mocha');
    protractor = require("gulp-protractor").protractor;
    // webdriver_standalone = require("selenium-webdriver");

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    staticFiles: [
      '!app/**/*.+(less|css|jade|js)',
      'app/**/*.*'
    ],
    libTest: ['lib/tests/service.spec.js'],
    unitTest: [
      'public/lib/angular/angular.js',
      'public/lib/angular-mocks/angular-mocks.js',
      'public/lib/moment/moment.js',
      'public/lib/firebase/firebase.js',
      'public/lib/angular-aria/angular-aria.js',
      'public/lib/angular-ui-router/release/angular-ui-router.min.js',
      'public/lib/hammerjs/hammer.min.js',
      'public/lib/angular-material/angular-material.js',
      'public/lib/angular-route/angular-route.js',
      'public/lib/angular-cookies/angular-cookies.js',
      'public/lib/angular-bootstrap/ui-bootstrap.js',
      'public/lib/angular-animate/angular-animate.js',
      'public/lib/angular-sanitize/angular-sanitize.js',
      'public/lib/angularfire/dist/angularfire.js',
      'public/lib/lodash/dist/lodash.min.js',
      'public/js/index.js',
      'app/test/specs.js'
    ],
    styles: 'app/styles/*.+(less|css)'
};

gulp.task('bower', function() {
  return bower()
    .pipe(gulp.dest('public/lib/'))
});

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

gulp.task('less', function() {
    gulp.src(paths.styles)
        .pipe(less({
            paths: [path.join(__dirname, 'styles')]
        }))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('lint', function() {
    gulp.src(['index.js','./app/**/*.js']).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    gulp.watch(paths.scripts, ['browserify']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('static-files', function() {
   return gulp.src(paths.staticFiles)
    .pipe(gulp.dest('public/'));
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

gulp.task('browserify', function() {
 var b = browserify();
 b.add('./app/application.js');
 return b.bundle()
 .on('success', gutil.log.bind(gutil, 'Browserify Rebundled'))
 .on('error', gutil.log.bind(gutil, 'Browserify Error: in browserify gulp task'))
 .pipe(source('index.js'))
 .pipe(gulp.dest('./public/js'));
});
// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('test:lib', function() {
    return gulp.src(paths.libTest)
        .pipe(mocha({
            reporter: 'dot',
            timeout: 60000
        }));
});

gulp.task('test:ui',['browserify'], function() {
    // Be sure to return the stream
    return gulp.src(paths.unitTest)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }))
        .pipe(exit());
                // .on('error', function(err) {
        //     // Make sure failed tests cause gulp to exit non-zero
        //     throw err;
        // });
});
//gulp.task('webdriver_update', webdriver_update);
// seleniumServerJar in your protractor.conf.js
gulp.task('protractor',function(cb){

  //app.listen(8000);
  gulp.src(["./lib/protractor/tests/**/*.js"])
  .pipe(protractor({
      configFile: "protractor.conf.js",
      args: ['--baseUrl', 'http://127.0.0.1:8000']
  }))
  .on('error', function(e) {
        console.log(e)
  })
  .on('end', cb);
});

gulp.task('protractor',function(cb){
//app.listen(8000);
  gulp.src(["./e2e/*_spec.js"])
  .pipe(protractor({
      configFile: "e2e/protractor.conf.js",
      args: ['--baseUrl', 'http://127.0.0.1:8000']
  }))
  .on('error', function(e) {
        console.log(e)
  })
  .on('end', cb);
});

gulp.task('test',['test:ui','test:lib']);
gulp.task('build', ['jade', 'less', 'browserify','static-files','bower']);
gulp.task('production', ['nodemon','build']);
gulp.task('e2e',['protractor']);
gulp.task('heroku:production', ['build']);
gulp.task('default', ['nodemon', 'watch', 'build']);

<commit_msg>modified gulp file to run protractor<commit_after>var browserify = require('browserify'),
    concat = require('gulp-concat'),
    es6ify = require('es6ify'),
    gulp = require('gulp'),
    bower = require('gulp-bower'),
    jshint = require('gulp-jshint'),
    gutil = require('gulp-util'),
    jade = require('gulp-jade'),
    jshint = require('gulp-jshint'),
    less = require('gulp-less'),
    minifyCss = require('gulp-minify-css'),
    minifyHtml = require('gulp-minify-html'),
    nodemon = require('gulp-nodemon'),
    path = require('path'),
    rev = require('gulp-rev'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    stringify = require('stringify'),
    uglify = require('gulp-uglify'),
    karma = require('gulp-karma'),
    exit = require('gulp-exit'),
    watchify = require('watchify'),
    protractor = require('gulp-protractor').protractor,
    mocha = require('gulp-mocha');

var paths = {
    public: 'public/**',
    jade: 'app/**/*.jade',
    scripts: 'app/**/*.js',
    staticFiles: [
      '!app/**/*.+(less|css|jade|js)',
      'app/**/*.*'
    ],
    libTest: ['lib/tests/service.spec.js'],
    unitTest: [
      'public/lib/angular/angular.js',
      'public/lib/angular-mocks/angular-mocks.js',
      'public/lib/moment/moment.js',
      'public/lib/firebase/firebase.js',
      'public/lib/angular-aria/angular-aria.js',
      'public/lib/angular-ui-router/release/angular-ui-router.min.js',
      'public/lib/hammerjs/hammer.min.js',
      'public/lib/angular-material/angular-material.js',
      'public/lib/angular-route/angular-route.js',
      'public/lib/angular-cookies/angular-cookies.js',
      'public/lib/angular-bootstrap/ui-bootstrap.js',
      'public/lib/angular-animate/angular-animate.js',
      'public/lib/angular-sanitize/angular-sanitize.js',
      'public/lib/angularfire/dist/angularfire.js',
      'public/lib/lodash/dist/lodash.min.js',
      'public/js/index.js',
      'app/test/specs.js'
    ],
    styles: 'app/styles/*.+(less|css)'
};

gulp.task('bower', function() {
  return bower()
    .pipe(gulp.dest('public/lib/'))
});

gulp.task('lint', function() {
  return gulp.src('./lib/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('YOUR_REPORTER_HERE'));
});

gulp.task('jade', function() {
    gulp.src('./app/**/*.jade')
        .pipe(jade())
        .pipe(gulp.dest('./public/'))
});

gulp.task('less', function() {
    gulp.src(paths.styles)
        .pipe(less({
            paths: [path.join(__dirname, 'styles')]
        }))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('lint', function() {
    gulp.src(['index.js','./app/**/*.js']).pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//'app/**',
gulp.task('nodemon', function() {
    nodemon({
            script: 'index.js',
            ext: 'js',
            ignore: ['public/']
        })
        .on('change', ['lint'])
        .on('restart', function() {
            console.log('>> node restart');
        })
});

gulp.task('watch', function() {
    // livereload.listen({ port: 35729 });
    gulp.watch(paths.jade, ['jade']);
    gulp.watch(paths.styles, ['less']);
    gulp.watch(paths.scripts, ['browserify']);
    // gulp.watch(paths.public).on('change', livereload.changed);
});

gulp.task('static-files', function() {
   return gulp.src(paths.staticFiles)
    .pipe(gulp.dest('public/'));
});

gulp.task('watchify', function() {
    var bundler = watchify(browserify('./app/application.js', watchify.args));

    bundler.transform(stringify(['.html']));
    // bundler.transform(es6ify);

    bundler.on('update', rebundle);

    function rebundle() {
        return bundler.bundle()
            // log errors if they happen
            .on('error', gutil.log.bind(gutil, 'Browserify Error'))
            .pipe(source('index.js'))
            .pipe(gulp.dest('./public/js'));
    }

    return rebundle();
});

gulp.task('browserify', function() {
 var b = browserify();
 b.add('./app/application.js');
 return b.bundle()
 .on('success', gutil.log.bind(gutil, 'Browserify Rebundled'))
 .on('error', gutil.log.bind(gutil, 'Browserify Error: in browserify gulp task'))
 .pipe(source('index.js'))
 .pipe(gulp.dest('./public/js'));
});
// gulp.task('usemin', function() {
//   gulp.src('public/*.html')
//     .pipe(usemin({
//       css: [minifyCss(), 'concat'],
//       html: [minifyHtml({empty: true})],
//       js: [uglify(), rev()]
//     }))
//     .pipe(gulp.dest('public'));
// });

gulp.task('test:lib', function() {
    return gulp.src(paths.libTest)
        .pipe(mocha({
            reporter: 'dot',
            timeout: 60000
        }));
});

gulp.task('test:ui',['browserify'], function() {
    // Be sure to return the stream
    return gulp.src(paths.unitTest)
        .pipe(karma({
            configFile: 'karma.conf.js',
            action: 'run'
        }))
        .pipe(exit());
                // .on('error', function(err) {
        //     // Make sure failed tests cause gulp to exit non-zero
        //     throw err;
        // });
});
//gulp.task('webdriver_update', webdriver_update);
// seleniumServerJar in your protractor.conf.js

gulp.task('protractor',function(cb){
//app.listen(8000);
  gulp.src(["./e2e/*_spec.js"])
  .pipe(protractor({
      configFile: "e2e/protractor.conf.js",
      args: ['--baseUrl', 'http://127.0.0.1:8000']
  }))
  .on('error', function(e) {
        console.log(e)
  })
  .on('end', cb);
});

gulp.task('test',['test:ui','test:lib']);
gulp.task('build', ['jade', 'less', 'browserify','static-files','bower']);
gulp.task('production', ['nodemon','build']);
gulp.task('e2e',['protractor']);
gulp.task('heroku:production', ['build']);
gulp.task('default', ['nodemon', 'watch', 'build']);

<|endoftext|>


<commit_before>var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-continuous-concat'),
    uglify = require('gulp-uglify'),
    gzip = require('gulp-gzip'),
    babel = require('gulp-babel'),
    rimraf = require('rimraf'),
    watch = require('gulp-watch'),
    plumber = require('gulp-plumber'),
    debug = require('gulp-debug'),
    addsrc = require('gulp-add-src'),
    livereload = require('gulp-livereload'),

    files = [
        './js/*.jsx',
        './js/*.js'
    ],
    deps = [
        './bower_components/react/react.js',
        './bower_components/react/react-dom.js'
    ];

gulp.task('clean-scripts', function (cb) {
    return rimraf('./resources/public', cb);
});

gulp.task('deploy', function() {
    gulp.src(files)
        .pipe(babel())
    .pipe(addsrc(deps))
    .pipe(concat('questionmark.js'))
    .pipe(uglify())
    .pipe(gzip())
    .pipe(gulp.dest('./resources/public'));
});

gulp.task('dev', function() {
    gulp.src(files)
        .pipe(watch('js/*.jsx'))
        .pipe(debug())
        .pipe(babel())
        .pipe(plumber())
        .pipe(addsrc.prepend(deps))
        .pipe(concat('questionmark.js'))
        .pipe(debug())
        .pipe(gulp.dest('./resources/public'))
        .pipe(livereload({start: true}));
});

gulp.task('lint', function () {
   gulp.src(['file.js'])
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});
<commit_msg>fix deploy gulp file<commit_after>var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-continuous-concat'),
    concatOnce = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    gzip = require('gulp-gzip'),
    babel = require('gulp-babel'),
    rimraf = require('rimraf'),
    watch = require('gulp-watch'),
    plumber = require('gulp-plumber'),
    debug = require('gulp-debug'),
    addsrc = require('gulp-add-src'),
    livereload = require('gulp-livereload'),

    files = [
        './js/*.jsx',
        './js/*.js'
    ],
    deps = [
        './bower_components/react/react.js',
        './bower_components/react/react-dom.js'
    ];

gulp.task('clean-scripts', function (cb) {
    return rimraf('./resources/public', cb);
});

gulp.task('deploy', function() {
    gulp.src(files)
        .pipe(babel())
        .pipe(addsrc.prepend(deps))
        .pipe(concatOnce('questionmark.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./resources/public'))
        .pipe(gzip({ append: true }))
        .pipe(gulp.dest('./resources/public'));
});

gulp.task('dev', function() {
    gulp.src(files)
        .pipe(watch('js/*.jsx'))
        .pipe(debug())
        .pipe(babel())
        .pipe(plumber())
        .pipe(addsrc.prepend(deps))
        .pipe(concat('questionmark.js'))
        .pipe(debug())
        .pipe(gulp.dest('./resources/public'))
        .pipe(livereload({start: true}));
});

gulp.task('lint', function () {
   gulp.src(['file.js'])
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var bem = require('gulp-bem');
var concat = require('gulp-concat');
var del = require('del');
var jade = require('gulp-jade');
var sass = require('gulp-sass');
var pack = require('gulp-bem-pack');
var autoprefixer = require('gulp-autoprefixer');
var uglify = require('gulp-uglify');
var buildBranch = require('buildbranch');

var levels = [
    'levels/js',
    'libs/bootstrap/levels/*',
    'levels/base',
    'levels/blocks',
    'levels/pages'
];

var tree;
gulp.task('tree', function () {
    tree = bem.objects(levels).pipe(bem.deps()).pipe(bem.tree());
});

gulp.task('js', ['tree'], function () {
    return tree.deps('levels/pages/index')
        .pipe(bem.src('{bem}.js'))
        .pipe(pack('index.js'))
        .pipe(gulp.dest('./dist'));
});

gulp.task('uglify', ['js'], function () {
    return gulp.src('dist/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('css', ['tree'], function () {
    function buildCss(page) {
        return tree.deps('levels/pages/' + page.id)
            .pipe(bem.src('{bem}.{css,scss}'))
            .pipe(concat(page.id + '.css'))
            .pipe(sass())
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(gulp.dest('./dist'));
    }

    return bem.objects('levels/pages').map(buildCss);
});

gulp.task('html', ['tree'], function () {
    function buildHtml(page) {
        return tree.deps('levels/pages/' + page.id)
            .pipe(bem.src('{bem}.jade'))
            .pipe(concat({
                path: page.path + '/' + page.id + '.jade',
                base: page.path
            }))
            .pipe(jade({pretty: true}))
            .pipe(gulp.dest('./dist'));
    }

    return bem.objects('levels/pages').map(buildHtml);
});

gulp.task('cname', function () {
    return gulp.src('CNAME').pipe(gulp.dest('dist'));
});

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

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

gulp.task('build', ['html', 'css', 'js', 'assets', 'cname']);

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

gulp.task('gh', ['production'], function(done) {
    buildBranch({ folder: 'dist', ignore: ['libs'] }, done);
});

gulp.task('express', function() {
    var express = require('express');
    var app = express();
    app.use(express.static('dist'));
    app.listen(4000);
    console.log('Server is running on http://localhost:4000');
});

var watch = require('gulp-watch');
gulp.task('watch', ['express', 'build'], function() {
    watch('assets/**/*', function () { gulp.start('assets'); });
    watch('levels/**/*.js', function () { gulp.start('js'); });
    watch('levels/**/*.{scss,css}', function () { gulp.start('css'); });
    watch('levels/**/*.jade', function () { gulp.start('html'); });
});

gulp.task('default', ['watch']);
<commit_msg>fix(gulpfile): place articles in folders<commit_after>var gulp = require('gulp');
var bem = require('gulp-bem');
var concat = require('gulp-concat');
var del = require('del');
var jade = require('gulp-jade');
var sass = require('gulp-sass');
var pack = require('gulp-bem-pack');
var autoprefixer = require('gulp-autoprefixer');
var uglify = require('gulp-uglify');
var buildBranch = require('buildbranch');
var rename = require('gulp-rename');

var levels = [
    'levels/js',
    'libs/bootstrap/levels/*',
    'levels/base',
    'levels/blocks',
    'levels/pages'
];

var tree;
gulp.task('tree', function () {
    tree = bem.objects(levels).pipe(bem.deps()).pipe(bem.tree());
});

gulp.task('js', ['tree'], function () {
    return tree.deps('levels/pages/index')
        .pipe(bem.src('{bem}.js'))
        .pipe(pack('index.js'))
        .pipe(gulp.dest('./dist'));
});

gulp.task('uglify', ['js'], function () {
    return gulp.src('dist/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('css', ['tree'], function () {
    function buildCss(page) {
        return tree.deps('levels/pages/' + page.id)
            .pipe(bem.src('{bem}.{css,scss}'))
            .pipe(concat(page.id + '.css'))
            .pipe(sass())
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(gulp.dest('./dist'));
    }

    return bem.objects('levels/pages').map(buildCss);
});

gulp.task('html', ['tree'], function () {
    function buildHtml(page) {
        return tree.deps('levels/pages/' + page.id)
            .pipe(bem.src('{bem}.jade'))
            .pipe(concat({
                path: page.path + '/' + page.id + '.jade',
                base: page.path
            }))
            .pipe(jade({pretty: true}))
            .pipe(rename({basename: 'index'}))
            .pipe(gulp.dest('./dist' +
                (page.id === 'index' ? '' : '/' + page.id)
            ));
    }

    return bem.objects('levels/pages').map(buildHtml);
});

gulp.task('cname', function () {
    return gulp.src('CNAME').pipe(gulp.dest('dist'));
});

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

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

gulp.task('build', ['html', 'css', 'js', 'assets', 'cname']);

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

gulp.task('gh', ['production'], function(done) {
    buildBranch({ folder: 'dist', ignore: ['libs'] }, done);
});

gulp.task('express', function() {
    var express = require('express');
    var app = express();
    app.use(express.static('dist'));
    app.listen(4000);
    console.log('Server is running on http://localhost:4000');
});

var watch = require('gulp-watch');
gulp.task('watch', ['express', 'build'], function() {
    watch('assets/**/*', function () { gulp.start('assets'); });
    watch('levels/**/*.js', function () { gulp.start('js'); });
    watch('levels/**/*.{scss,css}', function () { gulp.start('css'); });
    watch('levels/**/*.jade', function () { gulp.start('html'); });
});

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


<commit_before>'use strict';

/* eslint-disable eqeqeq, prefer-template, no-loop-func */

/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	$ = require('gulp-load-plugins')();

const
	fs = require('fs'),
	path = require('path'),
	{Transform} = require('stream');

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

function getVersion() {
	const file = fs.readFileSync('./src/escaper.js');
	return /VERSION\s*[:=]\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return (
		'/*!\n' +
		` * Escaper${opt_version ? ` v${getVersion()}` : ''}\n` +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n'
	);
}

gulp.task('predefs:build', () =>
	gulp.src('./predefs/src/index.js')
		.pipe($.plumber())
		.pipe($.monic())
		.pipe(gulp.dest('./predefs/build'))
);

gulp.task('predefs:externs', () =>
	$.download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe($.plumber())
		.pipe(gulp.dest('./predefs/src/ws'))
);

gulp.task('predefs:bower', () =>
	$.run('bower install').exec()
);

gulp.task('predefs', gulp.parallel(
	'predefs:build',
	'predefs:externs',
	'predefs:bower'
));

gulp.task('build:js', () => {
	const
		File = require('vinyl'),
		through = require('through2'),
		rollup = require('rollup');

	const fullHead =
		getHead(true) +
		' *\n' +
		` * Date: ${new Date().toUTCString()}\n` +
		' */\n\n';

	const stream = new Transform({
		readableObjectMode: true
	});

	rollup.rollup({
		input: './src/escaper.js',
		plugins: [require('rollup-plugin-babel')()]
	})
		.then((bundle) => bundle.generate({
			name: 'Escaper',
			format: 'umd',
			exports: 'named',
			amd: {id: 'Escaper'}
		}))

		.then(({output}) => {
			for (let i = 0; i < output.length; i++) {
				const
					el = output[i];

				stream.push(new File({
					path: el.facadeModuleId,
					base: path.dirname(el.facadeModuleId),
					contents: Buffer.from(el.code)
				}));
			}

			stream.push(null);
		})

		.catch((err) => {
			stream.push(err);
			stream.push(null);
		});

	return stream
		.pipe($.plumber())
		.pipe(through.obj((data, enc, cb) => {
			if (data instanceof File) {
				cb(null, data);

			} else {
				cb(data);
			}
		}))

		.pipe($.header(fullHead))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
});

function compile() {
	const
		glob = require('glob'),
		config = require('./gcc.json');

	return gulp.src('./dist/escaper.js')
		.pipe($.plumber())
		.pipe($.closureCompiler(Object.assign(config, {compilerPath: glob.sync(config.compilerPath)[0]})))
		.pipe($.replace(/^\/\*[\s\S]*?\*\//, ''))
		.pipe($.wrap('(function(){\'use strict\';<%= contents %>}).call(this);'))
		.pipe($.header(`/*! Escaper v${getVersion()} | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n`))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
}

gulp.task('build:compile', gulp.series(gulp.parallel('predefs', 'build:js'), compile));
gulp.task('build:compile:fast', gulp.series('build:js', compile));
gulp.task('build', gulp.series('build:compile', test()));

function test(dev) {
	return () => {
		return gulp.src(`./dist/escaper${dev ? '' : '.min'}.js`)
			.pipe($.istanbul())
			.pipe($.istanbul.hookRequire())
			.on('finish', runTests);

		function runTests() {
			return gulp.src(`./spec/${dev ? 'dev' : 'index'}-spec.js`)
				.pipe($.plumber())
				.pipe($.jasmine())
				.pipe($.istanbul.writeReports());
		}
	};
}

gulp.task('test', test());
gulp.task('test:dev', gulp.series('build:js', test(true)));
gulp.task('yaspeller', () => $.run('yaspeller ./').exec().on('error', console.error));

gulp.task('copyright', () =>
	gulp.src('./LICENSE')
		.pipe($.plumber())
		.pipe($.replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (str, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? `-${year}` : '');
		}))

		.pipe(gulp.dest('./'))
);

gulp.task('bump', () =>
	gulp.src('./@(package-lock|package|bower).json')
		.pipe($.plumber())
		.pipe($.bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
);

gulp.task('npmignore', () =>
	gulp.src('./.npmignore')
		.pipe($.plumber())
		.pipe($.replace(/([\s\S]*?)(?=# NPM ignore list)/, `${require('fs').readFileSync('./.gitignore')}\n`))
		.pipe(gulp.dest('./'))
);

gulp.task('head', () => {
	const
		fullHead = `${getHead()} */\n\n`;

	function filter(file) {
		return !headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead;
	}

	const paths = [
		'./@(src|spec)/*.js',
		'./@(externs|gulpfile).js',
		'./escaper.d.ts',
		'./predefs/src/index.js'
	];

	return gulp.src(paths, {base: './'})
		.pipe($.plumber())
		.pipe($.ignore.include(filter))
		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe(gulp.dest('./'));
});

gulp.task('default', gulp.parallel(
	gulp.series(
		gulp.parallel('bump', 'head'),
		'build'
	),

	'copyright',
	'yaspeller',
	'npmignore'
));

gulp.task('dev', gulp.parallel(
	gulp.series(
		gulp.parallel('bump', 'head'),
		'build:js'
	),

	'copyright',
	'yaspeller',
	'npmignore'
));

gulp.task('watch', gulp.series('default', () => {
	gulp.watch('./src/escaper.js', gulp.series(
		'bump',
		'build:compile:fast',
		'test'
	));

	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}));

gulp.task('watch:dev', gulp.series('dev', () => {
	gulp.watch('./src/escaper.js', gulp.series('bump', 'test:dev'));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}));
<commit_msg>Refactoring<commit_after>'use strict';

/* eslint-disable eqeqeq, prefer-template, no-loop-func */

/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	$ = require('gulp-load-plugins')();

const
	fs = require('fs'),
	path = require('path'),
	{Transform} = require('stream');

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

function getVersion() {
	const file = fs.readFileSync('./src/escaper.js');
	return /VERSION\s*[:=]\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return (
		'/*!\n' +
		` * Escaper${opt_version ? ` v${getVersion()}` : ''}\n` +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n'
	);
}

gulp.task('predefs:build', () =>
	gulp.src('./predefs/src/index.js')
		.pipe($.plumber())
		.pipe($.monic())
		.pipe(gulp.dest('./predefs/build'))
);

gulp.task('predefs:externs', () =>
	$.download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe($.plumber())
		.pipe(gulp.dest('./predefs/src/ws'))
);

gulp.task('predefs:bower', () =>
	$.run('bower install').exec()
);

gulp.task('predefs', gulp.parallel(
	'predefs:build',
	'predefs:externs',
	'predefs:bower'
));

gulp.task('build:js', () => {
	const
		File = require('vinyl'),
		through = require('through2'),
		rollup = require('rollup');

	const fullHead =
		getHead(true) +
		' *\n' +
		` * Date: ${new Date().toUTCString()}\n` +
		' */\n\n';

	const stream = new Transform({
		readableObjectMode: true
	});

	rollup.rollup({
		input: './src/escaper.js',
		plugins: [require('rollup-plugin-babel')()]
	})
		.then((bundle) => bundle.generate({
			name: 'Escaper',
			format: 'umd',
			exports: 'named',
			amd: {id: 'Escaper'}
		}))

		.then(({output}) => {
			for (let i = 0; i < output.length; i++) {
				const
					el = output[i];

				stream.push(new File({
					path: el.facadeModuleId,
					base: path.dirname(el.facadeModuleId),
					contents: Buffer.from(el.code)
				}));
			}

			stream.push(null);
		})

		.catch((err) => {
			stream.push(err);
			stream.push(null);
		});

	return stream
		.pipe($.plumber())
		.pipe(through.obj((data, enc, cb) => {
			if (data instanceof File) {
				cb(null, data);

			} else {
				cb(data);
			}
		}))

		.pipe($.header(fullHead))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
});

function compile() {
	const
		glob = require('glob'),
		config = require('./gcc.json');

	return gulp.src('./dist/escaper.js')
		.pipe($.plumber())
		.pipe($.closureCompiler(Object.assign(config, {compilerPath: glob.sync(config.compilerPath)[0]})))
		.pipe($.replace(/^\/\*[\s\S]*?\*\//, ''))
		.pipe($.wrap('(function(){\'use strict\';<%= contents %>}).call(this);'))
		.pipe($.header(`/*! Escaper v${getVersion()} | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n`))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
}

gulp.task('build', gulp.series(gulp.parallel('predefs', 'build:js'), compile));
gulp.task('build:fast', gulp.series('build:js', compile));

function test(dev) {
	return () => {
		return gulp.src(`./dist/escaper${dev ? '' : '.min'}.js`)
			.pipe($.istanbul())
			.pipe($.istanbul.hookRequire())
			.on('finish', runTests);

		function runTests() {
			return gulp.src(`./spec/${dev ? 'dev' : 'index'}-spec.js`)
				.pipe($.plumber())
				.pipe($.jasmine())
				.pipe($.istanbul.writeReports());
		}
	};
}

gulp.task('test', test());
gulp.task('build:test', gulp.series('build', test()));

gulp.task('test:dev', test(true));
gulp.task('build:test:dev', gulp.series('build:js', test(true)));
gulp.task('yaspeller', () => $.run('yaspeller ./').exec().on('error', console.error));

gulp.task('copyright', () =>
	gulp.src('./LICENSE')
		.pipe($.plumber())
		.pipe($.replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (str, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? `-${year}` : '');
		}))

		.pipe(gulp.dest('./'))
);

gulp.task('bump', () =>
	gulp.src('./@(package-lock|package|bower).json')
		.pipe($.plumber())
		.pipe($.bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
);

gulp.task('npmignore', () =>
	gulp.src('./.npmignore')
		.pipe($.plumber())
		.pipe($.replace(/([\s\S]*?)(?=# NPM ignore list)/, `${require('fs').readFileSync('./.gitignore')}\n`))
		.pipe(gulp.dest('./'))
);

gulp.task('head', () => {
	const
		fullHead = `${getHead()} */\n\n`;

	function filter(file) {
		return !headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead;
	}

	const paths = [
		'./@(src|spec)/*.js',
		'./@(externs|gulpfile).js',
		'./escaper.d.ts',
		'./predefs/src/index.js'
	];

	return gulp.src(paths, {base: './'})
		.pipe($.plumber())
		.pipe($.ignore.include(filter))
		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe(gulp.dest('./'));
});

gulp.task('default', gulp.parallel(
	gulp.series(
		gulp.parallel('bump', 'head'),
		'build:test'
	),

	'copyright',
	'yaspeller',
	'npmignore'
));

gulp.task('dev', gulp.parallel(
	gulp.series(
		gulp.parallel('bump', 'head'),
		'build:test:dev'
	),

	'copyright',
	'yaspeller',
	'npmignore'
));

gulp.task('watch', gulp.series('default', () => {
	gulp.watch('./src/escaper.js', gulp.series('bump', 'build:test'));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}));

gulp.task('watch:dev', gulp.series('dev', () => {
	gulp.watch('./src/escaper.js', gulp.series('bump', 'build:test:dev'));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}));
<|endoftext|>


<commit_before>/* eslint-disable global-require */
// Allow require() to exist only in specific tasks if they are only used once.
const gulp = require('gulp');
const gutil = require('gulp-util');
const notify = require('gulp-notify');
const sourcemaps = require('gulp-sourcemaps');
const browserSync = require('browser-sync');

const server = browserSync.create();

const paths = {
  styles: {
    src: 'src/css/**/*.css',
    entry: 'src/css/main.css',
    dest: 'public/stylesheets',
  },
  scripts: {
    src: 'src/js/**/*.{js,jsx,json}',
    entry: ['src/js/main.js', 'src/js/embedded.js'],
    dest: 'public/scripts',
  },
  app: 'public/index.html',
};

function handleErrors(...args) {
  notify.onError({
    title: 'Tangram Play · Compile Error',
    message: '<%= error.message %>',
    sound: 'Sosumi', // Mac OSX alert sound
  }).apply(this, args);
  this.emit('end'); // Keep gulp from hanging on this task
}

// Build stylesheets
gulp.task('css', () => {
  const postcss = require('gulp-postcss');
  const autoprefixer = require('autoprefixer');
  const cssimport = require('postcss-import');
  const nested = require('postcss-nested');
  const customProperties = require('postcss-custom-properties');
  const colorHexAlpha = require('postcss-color-hex-alpha');
  const csswring = require('csswring');
  const reporter = require('postcss-reporter');

  const plugins = [
    cssimport,
    nested,
    customProperties(),
    colorHexAlpha(),
    autoprefixer({ browsers: ['last 2 versions', 'IE >= 11'] }),
    // preserveHacks is true because NOT preserving them doesn't mean
    // delete the hack, it means turn it into real CSS. Which is not
    // what we want!
    csswring({ removeAllComments: true, preserveHacks: true }),
    reporter(),
  ];

  return gulp.src(paths.styles.entry)
    .on('error', handleErrors)
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.styles.dest))
    // Since we generate sourcemaps, this causes browserSync.reload() to do
    // a full page reload because `.map` files are not found in the DOM. So we
    // pass the `match` option to only stream `.css` files to prevent injection
    // from also causing a full page reload.
    .pipe(browserSync.stream({ match: '**/*.css' }));
});

// Build Javascripts
gulp.task('js', () => {
  const browserify = require('browserify');
  const browserifyInc = require('browserify-incremental');
  const shim = require('browserify-shim');
  const babelify = require('babelify');
  const buffer = require('vinyl-buffer');
  const uglify = require('gulp-uglify');
  const envify = require('loose-envify');
  const tap = require('gulp-tap');

  const opts = {
    debug: true,
    extensions: ['.jsx'],
    transform: [
      babelify,
      shim,
      envify,
    ],
    // Option for browserify-incremental
    cacheFile: './browserify-cache.json',
  };

  // Set which browserify type to use for different environments.
  // In development, we use incremental browserify so rebuilds are faster.
  let browserifyEnv = browserifyInc;

  // In production, we use normal browserify because loose-envify only works
  // for normal browserify - not for incremental browserify.
  if (process.env.NODE_ENV === 'production') {
    browserifyEnv = browserify;
  }

  // Only uglify for deployment/production build,
  // because this doubles build time locally!
  if (process.env.NODE_ENV === 'production') {
    return gulp.src(paths.scripts.entry, {
      read: false, // no need to read files because browserify does.
    })
    // transform file objects using gulp-tap plugin
    .pipe(tap((file) => {
      gutil.log(`bundling ${file.path}`);

      // replace file contents with browserify's bundle stream
      // eslint-disable-next-line no-param-reassign
      file.contents = browserifyEnv(file.path, opts).bundle();
    }))
    // transform streaming contents into buffer contents (because
    // gulp-sourcemaps does not support streaming contents)
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
        // Add transformation tasks to the pipeline here.
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.scripts.dest));
  }

  return gulp.src(paths.scripts.entry, {
    read: false, // no need to read files because browserify does.
  })
    // transform file objects using gulp-tap plugin
    .pipe(tap((file) => {
      gutil.log(`bundling ${file.path}`);

      // replace file contents with browserify's bundle stream
      // eslint-disable-next-line no-param-reassign
      file.contents = browserifyEnv(file.path, opts).bundle();
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(paths.scripts.dest));
});

// https://github.com/gulpjs/gulp/blob/4.0/docs/recipes/minimal-browsersync-setup-with-gulp4.md
function reload(done) {
  server.reload();
  done();
}

// Build files, do not watch
gulp.task('build', gulp.parallel('css', 'js'));

// Watch files, but do not run browsersync
gulp.task('watch', gulp.series('build', watch = () => {
  gulp.watch(paths.styles.src, gulp.series('css'));
  gulp.watch(paths.scripts.src, gulp.series('js'));
}));

// Re-load the browser when a file changes
function initServer() {
  server.init({
    port: 8080,
    open: false,
    server: {
      baseDir: './public',
    },
    ui: {
      port: 8081,
    },
    ghostMode: false,
  });

  gulp.watch(paths.styles.src, gulp.series('css'));
  gulp.watch(paths.scripts.src, gulp.series('js', reload));
  gulp.watch(paths.app).on('change', reload);
}

// build and serve
gulp.task('serve', gulp.series('build', initServer));

// The default task (called when you run `gulp` from cli)
gulp.task('default', gulp.series('serve'));
<commit_msg>extract and name anonymous watch function<commit_after>/* eslint-disable global-require */
// Allow require() to exist only in specific tasks if they are only used once.
const gulp = require('gulp');
const gutil = require('gulp-util');
const notify = require('gulp-notify');
const sourcemaps = require('gulp-sourcemaps');
const browserSync = require('browser-sync');

const server = browserSync.create();

const paths = {
  styles: {
    src: 'src/css/**/*.css',
    entry: 'src/css/main.css',
    dest: 'public/stylesheets',
  },
  scripts: {
    src: 'src/js/**/*.{js,jsx,json}',
    entry: ['src/js/main.js', 'src/js/embedded.js'],
    dest: 'public/scripts',
  },
  app: 'public/index.html',
};

function handleErrors(...args) {
  notify.onError({
    title: 'Tangram Play · Compile Error',
    message: '<%= error.message %>',
    sound: 'Sosumi', // Mac OSX alert sound
  }).apply(this, args);
  this.emit('end'); // Keep gulp from hanging on this task
}

// Build stylesheets
gulp.task('css', () => {
  const postcss = require('gulp-postcss');
  const autoprefixer = require('autoprefixer');
  const cssimport = require('postcss-import');
  const nested = require('postcss-nested');
  const customProperties = require('postcss-custom-properties');
  const colorHexAlpha = require('postcss-color-hex-alpha');
  const csswring = require('csswring');
  const reporter = require('postcss-reporter');

  const plugins = [
    cssimport,
    nested,
    customProperties(),
    colorHexAlpha(),
    autoprefixer({ browsers: ['last 2 versions', 'IE >= 11'] }),
    // preserveHacks is true because NOT preserving them doesn't mean
    // delete the hack, it means turn it into real CSS. Which is not
    // what we want!
    csswring({ removeAllComments: true, preserveHacks: true }),
    reporter(),
  ];

  return gulp.src(paths.styles.entry)
    .on('error', handleErrors)
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.styles.dest))
    // Since we generate sourcemaps, this causes browserSync.reload() to do
    // a full page reload because `.map` files are not found in the DOM. So we
    // pass the `match` option to only stream `.css` files to prevent injection
    // from also causing a full page reload.
    .pipe(browserSync.stream({ match: '**/*.css' }));
});

// Build Javascripts
gulp.task('js', () => {
  const browserify = require('browserify');
  const browserifyInc = require('browserify-incremental');
  const shim = require('browserify-shim');
  const babelify = require('babelify');
  const buffer = require('vinyl-buffer');
  const uglify = require('gulp-uglify');
  const envify = require('loose-envify');
  const tap = require('gulp-tap');

  const opts = {
    debug: true,
    extensions: ['.jsx'],
    transform: [
      babelify,
      shim,
      envify,
    ],
    // Option for browserify-incremental
    cacheFile: './browserify-cache.json',
  };

  // Set which browserify type to use for different environments.
  // In development, we use incremental browserify so rebuilds are faster.
  let browserifyEnv = browserifyInc;

  // In production, we use normal browserify because loose-envify only works
  // for normal browserify - not for incremental browserify.
  if (process.env.NODE_ENV === 'production') {
    browserifyEnv = browserify;
  }

  // Only uglify for deployment/production build,
  // because this doubles build time locally!
  if (process.env.NODE_ENV === 'production') {
    return gulp.src(paths.scripts.entry, {
      read: false, // no need to read files because browserify does.
    })
    // transform file objects using gulp-tap plugin
    .pipe(tap((file) => {
      gutil.log(`bundling ${file.path}`);

      // replace file contents with browserify's bundle stream
      // eslint-disable-next-line no-param-reassign
      file.contents = browserifyEnv(file.path, opts).bundle();
    }))
    // transform streaming contents into buffer contents (because
    // gulp-sourcemaps does not support streaming contents)
    .pipe(buffer())
    .pipe(sourcemaps.init({ loadMaps: true }))
        // Add transformation tasks to the pipeline here.
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.scripts.dest));
  }

  return gulp.src(paths.scripts.entry, {
    read: false, // no need to read files because browserify does.
  })
    // transform file objects using gulp-tap plugin
    .pipe(tap((file) => {
      gutil.log(`bundling ${file.path}`);

      // replace file contents with browserify's bundle stream
      // eslint-disable-next-line no-param-reassign
      file.contents = browserifyEnv(file.path, opts).bundle();
    }))
    .on('error', handleErrors)
    .pipe(gulp.dest(paths.scripts.dest));
});

// https://github.com/gulpjs/gulp/blob/4.0/docs/recipes/minimal-browsersync-setup-with-gulp4.md
function reload(done) {
  server.reload();
  done();
}

// Build files, do not watch
gulp.task('build', gulp.parallel('css', 'js'));

function watching() {
  gulp.watch(paths.styles.src, gulp.series('css'));
  gulp.watch(paths.scripts.src, gulp.series('js'));
}
// Watch files, but do not run browsersync
gulp.task('watch', gulp.series('build', watching));

// Re-load the browser when a file changes
function initServer() {
  server.init({
    port: 8080,
    open: false,
    server: {
      baseDir: './public',
    },
    ui: {
      port: 8081,
    },
    ghostMode: false,
  });

  gulp.watch(paths.styles.src, gulp.series('css'));
  gulp.watch(paths.scripts.src, gulp.series('js', reload));
  gulp.watch(paths.app).on('change', reload);
}

// build and serve
gulp.task('serve', gulp.series('build', initServer));

// The default task (called when you run `gulp` from cli)
gulp.task('default', gulp.series('serve'));
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  shell = require('gulp-shell'),
  jshint = require('gulp-jshint'),
  stylish = require('jshint-stylish'),
  karma = require('karma').server,
  lazypipe = require('lazypipe'),
  runSequence = require('run-sequence');

var testFiles = [
  'src/confetti.js',
  'test/*.spec.js'
];

var jshintTask = lazypipe()
  .pipe(jshint)
  .pipe(jshint.reporter, stylish)
  .pipe(jshint.reporter, 'fail');

gulp.task('jshint', function () {
  return gulp.src(testFiles)
    .pipe(jshintTask());
})

gulp.task('karma', function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true,
    autoWatch: false,
    browsers: ['Firefox']
  }, done);
});

gulp.task('bump:patch', function () {
  return gulp.src(['./bower.json', './package.json'])
    .pipe(bump({ type: 'patch' }))
    .pipe(gulp.dest('./'))
    .on('error', function (err) { throw err; });
});

gulp.task('commit', function () {
  var version = require('./package.json').version;
  return gulp.src('package.json')
    .pipe(shell([
      'git commit -am "v<%= version %>"',
      'git tag -am v<%= version %> "v<%= version %>"',
      'git push',
      'git push --tags'
    ], {
      templateData: {
        version: function () {
          return version;
        }
      }
    }))
    .pipe(gulp.dest('./'))
    .on('error', function (err) { throw err; });
});

gulp.task('release:patch', function (done) {
  runSequence('test', 'bump:patch', 'commit', done);
});

gulp.task('test', ['jshint', 'karma']);
<commit_msg>Fix template function usage<commit_after>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  shell = require('gulp-shell'),
  jshint = require('gulp-jshint'),
  stylish = require('jshint-stylish'),
  karma = require('karma').server,
  lazypipe = require('lazypipe'),
  runSequence = require('run-sequence');

var testFiles = [
  'src/confetti.js',
  'test/*.spec.js'
];

var jshintTask = lazypipe()
  .pipe(jshint)
  .pipe(jshint.reporter, stylish)
  .pipe(jshint.reporter, 'fail');

gulp.task('jshint', function () {
  return gulp.src(testFiles)
    .pipe(jshintTask());
})

gulp.task('karma', function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true,
    autoWatch: false,
    browsers: ['Firefox']
  }, done);
});

gulp.task('bump:patch', function () {
  return gulp.src(['./bower.json', './package.json'])
    .pipe(bump({ type: 'patch' }))
    .pipe(gulp.dest('./'))
    .on('error', function (err) { throw err; });
});

gulp.task('commit', function () {
  var version = require('./package.json').version;
  return gulp.src('package.json')
    .pipe(shell([
      'git commit -am "v<%= version() %>"',
      'git tag -am v<%= version() %> "v<%= version() %>"',
      'git push',
      'git push --tags'
    ], {
      templateData: {
        version: function () {
          return version;
        }
      }
    }))
    .pipe(gulp.dest('./'))
    .on('error', function (err) { throw err; });
});

gulp.task('release:patch', function (done) {
  runSequence('test', 'bump:patch', 'commit', done);
});

gulp.task('test', ['jshint', 'karma']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var clean = require('gulp-clean');
var childProcess = require('child_process');
var concat = require('gulp-concat');

gulp.task('clean', function(){
  return gulp.src('web', {read: false})
    .pipe(clean());
});

gulp.task('build', ['clean'], function(){
  return gulp.src(['src/core/serilog.js', 'src/bower/serilog-console-sink.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(uglify({mangle: false}))
    .pipe(concat('serilog.min.js'))
    .pipe(gulp.dest('web'));
});

gulp.task('test', ['build'], function(cb) {
  childProcess.exec('mocha --reporter=spec', function(error, stdout, stderr){
    console.log(stdout);
    console.log(stderr);

    if (error) {
      console.log(error);
    }

    cb(error);
  });
});

gulp.task('smoke', ['test'], function() {
  var serilog = require('./src/core/serilog.js');
  var terminal = require('./src/npm/serilog-terminal-sink.js');

  var log = serilog.configuration()
    .minimumLevel('TRACE')
    .writeTo(terminal())
    .createLogger();

  log.trace('This is a trace message: {really}', true);
  log('Info: length of {string} is {length}', 'hello', 'hello'.length);
  log.warning('This warning is about {@thing}', {dangerLevel: 'high'});
  log.error('Last one!')
});

gulp.task('default', ['smoke']);
<commit_msg>Changed the existing build task to 'build-bower', it now combines and minifies the serilog scripts to the bower sub-directory.<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var clean = require('gulp-clean');
var childProcess = require('child_process');
var concat = require('gulp-concat');

gulp.task('clean', function(){
  return gulp.src('dist', {read: false})
    .pipe(clean());
});

gulp.task('build-bower', ['clean'], function(){
  return gulp.src(['src/core/serilog.js', 'src/bower/serilog-console-sink.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(uglify({mangle: false}))
    .pipe(concat('serilog.min.js'))
    .pipe(gulp.dest('dist/bower'));
});

gulp.task('test', ['build-bower'], function(cb) {
  childProcess.exec('mocha --reporter=spec', function(error, stdout, stderr){
    console.log(stdout);
    console.log(stderr);

    if (error) {
      console.log(error);
    }

    cb(error);
  });
});

gulp.task('smoke', ['test'], function() {
  var serilog = require('./src/core/serilog.js');
  var terminal = require('./src/npm/serilog-terminal-sink.js');

  var log = serilog.configuration()
    .minimumLevel('TRACE')
    .writeTo(terminal())
    .createLogger();

  log.trace('This is a trace message: {really}', true);
  log('Info: length of {string} is {length}', 'hello', 'hello'.length);
  log.warning('This warning is about {@thing}', {dangerLevel: 'high'});
  log.error('Last one!')
});

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


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

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

gulp.task('pre-test', function () {
  return gulp.src(['generators/**/*.js', '!generators/**/templates/*.js'])
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

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

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

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', '!generators/**/templates/*.js', 'test/**'], ['test']);
});

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

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

gulp.task('prepublish', ['nsp']);
gulp.task('default', ['test', 'coveralls']);
<commit_msg>Include <utils> folder for testing<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');

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

gulp.task('pre-test', function () {
  return gulp.src(['generators/**/*.js', '!generators/**/templates/*.js', 'utils/**/*.js'])
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

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

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

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', '!generators/**/templates/*.js', 'utils/**/*.js', 'test/**'],
    ['test']
  );
});

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

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

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