<commit_before>/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

const cleanCSS = require('gulp-clean-css');
const closureBuilder = require('closure-builder');
const closureCompiler = require('gulp-closure-compiler');
const concatCSS = require('gulp-concat-css');
const connect = require('gulp-connect');
const fse = require('fs-extra');
const flip = require('gulp-css-flip');
const gulp = require('gulp');
const path = require('path');
const sass = require('gulp-sass');
const streamqueue = require('streamqueue');
const util = require('gulp-util');

const glob = closureBuilder.globSupport();

// The optimization level for the JS compiler.
// Valid levels: WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS.
// This can be passed in as a flag:
// $ gulp --compilation_level=WHITESPACE_ONLY
const OPTIMIZATION_LEVEL = util.env.compilation_level ||
    'ADVANCED_OPTIMIZATIONS';

// For minified builds, wrap the output so we avoid leaking global variables.
const OUTPUT_WRAPPER = OPTIMIZATION_LEVEL === 'WHITESPACE_ONLY' ?
    '%output%' : '(function() { %output% })();';

// Adds the firebase module requirement and exports firebaseui.
const NPM_MODULE_WRAPPER = OPTIMIZATION_LEVEL === 'WHITESPACE_ONLY' ?
    'var firebase=require(\'firebase\');%output%module.exports=firebaseui;' :
    '(function() { var firebase=require(\'firebase\');%output% })();' +
    'module.exports=firebaseui;';

// The path to Closure Compiler.
const COMPILER_PATH = 'node_modules/google-closure-compiler/compiler.jar';

// The path to the temporary directory where intermediate results are stored.
const TMP_DIR = 'out';

// The path to the temporary directory where intermediate results are stored.
const DEST_DIR = 'dist';

// The locale that would be produced with no XTBs.
const DEFAULT_LOCALE = 'en';

// The list of all locales that are supported.
const ALL_LOCALES = ['ar-XB', 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en',
    'en-GB', 'en-XA', 'es-419', 'es', 'fa', 'fi', 'fil', 'fr', 'hi', 'hr', 'hu',
    'id', 'it', 'iw', 'ja', 'ko', 'lt', 'lv', 'nl', 'no', 'pl', 'pt-PT', 'pt',
    'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'th', 'tr', 'uk', 'vi', 'zh-CN',
    'zh-TW'];

// Compiles the Closure templates into JavaScript.
gulp.task('build-soy', () => new Promise((resolve, reject) => {
  closureBuilder.build({
    name: 'soy_files',
    srcs: glob([
      'soy/*.soy'
    ]),
    out: TMP_DIR,
    options: {
      soy: {
        shouldGenerateGoogMsgDefs: true,
        bidiGlobalDir: 1
      }
    },
  }, resolve);
}));

// Default arguments to pass into Closure Compiler.
const COMPILER_DEFAULT_ARGS = {
  compilation_level: OPTIMIZATION_LEVEL,
  language_out: 'ES5'
};

/**
 * Invokes Closure Compiler.
 * @param {!Array<string>} srcs The JS sources to compile.
 * @param {string} out The path to the output JS file.
 * @param {!Object} args Additional arguments to Closure compiler.
 * @return {*} A stream that finishes when compliation finishes.
 */
function compile(srcs, out, args) {
  // Get the compiler arguments, using the defaults if not specified.
  const combinedArgs = Object.assign({}, COMPILER_DEFAULT_ARGS, args);
  return gulp
      .src(srcs)
      .pipe(closureCompiler({
        compilerPath: COMPILER_PATH,
        fileName: path.basename(out),
        compilerFlags: combinedArgs
      }))
      .pipe(gulp.dest(path.dirname(out)));
}

/**
 * Normalizes a locale ID for use in a file name (e.g. en-GB -> en_gb).
 * @param {string} locale
 * @return {string} The normalized locale ID.
 */
function getLocaleForFileName(locale) {
  return locale.toLowerCase().replace(/-/g, '_');
}

/**
 * Gets the path to the temporary JS file that contains all FirebaseUI code
 * but no external dependencies.
 * @param {string} locale
 */
function getTmpJsPath(locale) {
  const localeForFileName = getLocaleForFileName(locale);
  return `${TMP_DIR}/firebaseui__${localeForFileName}.js`;
}

/**
 * Repeats a gulp task for all locales.
 * @param {string} taskName The gulp task name to generate. Any $ tokens will be
 *     replaced with the language code (e.g. build-$ becomes build-fr, build-es,
 *     etc.).
 * @param {!Array<string>} dependencies The gulp tasks that each operation
 *     depends on. Any $ tokens will be replaced with the language code.
 * @param {function()} operation The function to execute.
 * @return {!Array<string>} The list of generated task names.
 */
function repeatTaskForAllLocales(taskName, dependencies, operation) {
  const tasks = [];
  ALL_LOCALES.forEach((locale) => {
    // Convert build-js-$ to build-js-fr, for example.
    const replaceTokens = (name) => name.replace(/\$/g, locale);

    const localeTaskName = replaceTokens(taskName);
    tasks.push(localeTaskName);
    const localeDependencies = dependencies.map(replaceTokens);

    gulp.task(localeTaskName, localeDependencies, () => operation(locale));
  });
  return tasks;
}

/**
 * Builds the core FirebaseUI binary in the given locale.
 * @param {string} locale
 */
function buildFirebaseUiJs(locale) {
  const flags = {
    closure_entry_point: 'firebaseui.auth.exports',
    define: `goog.LOCALE='${locale}'`,
    externs: [
      'node_modules/firebase/externs/firebase-app-externs.js',
      'node_modules/firebase/externs/firebase-auth-externs.js',
      'node_modules/firebase/externs/firebase-client-auth-externs.js'
    ],
    only_closure_dependencies: true,
    output_wrapper: OUTPUT_WRAPPER,

    // This is required to match XTB IDs to the JS/Soy messages.
    translations_project: 'FirebaseUI'
  };
  if (locale !== DEFAULT_LOCALE) {
    flags.translations_file = `translations/${locale}.xtb`;
  }
  return compile([
    'node_modules/google-closure-templates/javascript/soyutils_usegoog.js',
    'node_modules/google-closure-library/closure/goog/**/*.js',
    'node_modules/google-closure-library/third_party/closure/goog/**/*.js',
    `${TMP_DIR}/**/*.js`,
    'javascript/**/*.js'
  ], getTmpJsPath(locale), flags);
}

// Builds the core FirebaseUI JS. Generates the gulp tasks
// build-firebaseui-js-de, build-firebaseui-js-fr, etc.
repeatTaskForAllLocales('build-firebaseui-js-$', ['build-soy'],
    buildFirebaseUiJs);

// The external dependencies needed by FirebaseUI.
const JS_DEPS = [
  'node_modules/material-design-lite/src/mdlComponentHandler.js',
  'node_modules/material-design-lite/src/button/button.js',
  'node_modules/material-design-lite/src/progress/progress.js',
  'node_modules/material-design-lite/src/spinner/spinner.js',
  'node_modules/material-design-lite/src/textfield/textfield.js',
  'node_modules/dialog-polyfill/dialog-polyfill.js'
];

/**
 * Concatenates the core FirebaseUI JS with its external dependencies, and
 * cleans up comments and whitespace in the dependencies.
 * @param {string} locale The desired FirebaseUI locale.
 * @param {string} outBaseName The prefix of the output file name.
 * @param {string} outputWrapper A wrapper with which to wrap the output JS.
 * @return {*} A stream that ends when compilation finishes.
 */
function concatWithDeps(locale, outBaseName, outputWrapper) {
  const localeForFileName = getLocaleForFileName(locale);
  // Get a list of the FirebaseUI JS and its dependencies.
  const srcs = JS_DEPS.concat([getTmpJsPath(locale)]);
  const outputPath = `${DEST_DIR}/${outBaseName}__${localeForFileName}.js`;
  return compile(srcs, outputPath, {
    compilation_level: 'WHITESPACE_ONLY',
    output_wrapper: outputWrapper
  });
}

// Bundles the FirebaseUI JS with its dependencies for all locales.
// Generates the gulp tasks build-js-de, build-js-fr, etc.
const buildJsTasks = repeatTaskForAllLocales(
    'build-js-$', ['build-firebaseui-js-$'],
    (locale) => concatWithDeps(locale, 'firebaseui', OUTPUT_WRAPPER));

/**
 * Creates the default FirebaseUI binaries for basic usage without
 * localization. For example, it copies firebaseui__en.js to firebaseui.js.
 * @param {string} fileName
 */
function makeDefaultFile(fileName) {
  const localeForFileName = getLocaleForFileName(DEFAULT_LOCALE);
  const path = `${DEST_DIR}/${fileName}__${localeForFileName}.js`;
  if (fse.existsSync(path)) {
    return fse.copy(path, `${DEST_DIR}/${fileName}.js`);
  }
}

gulp.task('build-all-js', buildJsTasks, () => makeDefaultFile('firebaseui'));
gulp.task('build-js', ['build-js-' + DEFAULT_LOCALE],
    () => makeDefaultFile('firebaseui'));

// Bundles the FirebaseUI JS with its dependencies as a NPM module.
repeatTaskForAllLocales(
    'build-npm-$', ['build-firebaseui-js-$'],
    (locale) => concatWithDeps(locale, 'npm', NPM_MODULE_WRAPPER));

gulp.task('build-npm', ['build-npm-' + DEFAULT_LOCALE],
    () => makeDefaultFile('npm'));

/**
 * Builds the CSS for FirebaseUI.
 * @param {boolean} isRtl Whether to build in right-to-left mode.
 * @return {*} A stream that finishes when compilation finishes.
 */
function buildCss(isRtl) {
  const mdlSrcs = gulp.src('stylesheet/mdl.scss')
      .pipe(sass.sync().on('error', sass.logError));
  const dialogPolyfillSrcs = gulp.src(
      'node_modules/dialog-polyfill/dialog-polyfill.css');
  let firebaseSrcs = gulp.src('stylesheet/*.css');

  // Flip left/right, ltr/rtl for RTL languages.
  if (isRtl) {
    firebaseSrcs = firebaseSrcs.pipe(flip.gulp());
  }

  const outFile = isRtl ? 'firebaseui-rtl.css' : 'firebaseui.css';
  return streamqueue({objectMode: true},
      mdlSrcs, dialogPolyfillSrcs, firebaseSrcs)
      .pipe(concatCSS(outFile))
      .pipe(cleanCSS())
      .pipe(gulp.dest(DEST_DIR));
}

// Concatenates and minifies the CSS sources.
gulp.task('build-css', () => buildCss(false));
gulp.task('build-css-rtl', () => buildCss(true));

// Creates a webserver that serves all files from the root of the package.
gulp.task('serve', () => {
  connect.server({
    port: 4000
  });
});

// Deletes intermediate files.
gulp.task('clean', () => fse.remove(TMP_DIR));

// Executes the basic tasks.
gulp.task('default', ['build-js', 'build-npm', 'build-css', 'build-css-rtl'],
    () => gulp.start('clean'));

// Builds everything.
gulp.task('build-all',
    ['build-all-js', 'build-npm', 'build-css', 'build-css-rtl'],
    () => gulp.start('clean'));
<commit_msg>Update l10n gulpfile comments<commit_after>/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

const cleanCSS = require('gulp-clean-css');
const closureBuilder = require('closure-builder');
const closureCompiler = require('gulp-closure-compiler');
const concatCSS = require('gulp-concat-css');
const connect = require('gulp-connect');
const fse = require('fs-extra');
const flip = require('gulp-css-flip');
const gulp = require('gulp');
const path = require('path');
const sass = require('gulp-sass');
const streamqueue = require('streamqueue');
const util = require('gulp-util');

const glob = closureBuilder.globSupport();

// The optimization level for the JS compiler.
// Valid levels: WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS.
// This can be passed in as a flag:
// $ gulp --compilation_level=WHITESPACE_ONLY
const OPTIMIZATION_LEVEL = util.env.compilation_level ||
    'ADVANCED_OPTIMIZATIONS';

// For minified builds, wrap the output so we avoid leaking global variables.
const OUTPUT_WRAPPER = OPTIMIZATION_LEVEL === 'WHITESPACE_ONLY' ?
    '%output%' : '(function() { %output% })();';

// Adds the firebase module requirement and exports firebaseui.
const NPM_MODULE_WRAPPER = OPTIMIZATION_LEVEL === 'WHITESPACE_ONLY' ?
    'var firebase=require(\'firebase\');%output%module.exports=firebaseui;' :
    '(function() { var firebase=require(\'firebase\');%output% })();' +
    'module.exports=firebaseui;';

// The path to Closure Compiler.
const COMPILER_PATH = 'node_modules/google-closure-compiler/compiler.jar';

// The path to the temporary directory where intermediate results are stored.
const TMP_DIR = 'out';

// The path to the temporary directory where intermediate results are stored.
const DEST_DIR = 'dist';

// The locale that would be produced with no XTBs.
const DEFAULT_LOCALE = 'en';

// The list of all locales that are supported.
const ALL_LOCALES = ['ar-XB', 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en',
    'en-GB', 'en-XA', 'es-419', 'es', 'fa', 'fi', 'fil', 'fr', 'hi', 'hr', 'hu',
    'id', 'it', 'iw', 'ja', 'ko', 'lt', 'lv', 'nl', 'no', 'pl', 'pt-PT', 'pt',
    'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'th', 'tr', 'uk', 'vi', 'zh-CN',
    'zh-TW'];

// Default arguments to pass into Closure Compiler.
const COMPILER_DEFAULT_ARGS = {
  compilation_level: OPTIMIZATION_LEVEL,
  language_out: 'ES5'
};

// The external dependencies needed by FirebaseUI.
const JS_DEPS = [
  'node_modules/material-design-lite/src/mdlComponentHandler.js',
  'node_modules/material-design-lite/src/button/button.js',
  'node_modules/material-design-lite/src/progress/progress.js',
  'node_modules/material-design-lite/src/spinner/spinner.js',
  'node_modules/material-design-lite/src/textfield/textfield.js',
  'node_modules/dialog-polyfill/dialog-polyfill.js'
];

// Compiles the Closure templates into JavaScript.
gulp.task('build-soy', () => new Promise((resolve, reject) => {
  closureBuilder.build({
    name: 'soy_files',
    srcs: glob([
      'soy/*.soy'
    ]),
    out: TMP_DIR,
    options: {
      soy: {
        shouldGenerateGoogMsgDefs: true,
        bidiGlobalDir: 1
      }
    },
  }, resolve);
}));

/**
 * Invokes Closure Compiler.
 * @param {!Array<string>} srcs The JS sources to compile.
 * @param {string} out The path to the output JS file.
 * @param {!Object} args Additional arguments to Closure compiler.
 * @return {*} A stream that finishes when compliation finishes.
 */
function compile(srcs, out, args) {
  // Get the compiler arguments, using the defaults if not specified.
  const combinedArgs = Object.assign({}, COMPILER_DEFAULT_ARGS, args);
  return gulp
      .src(srcs)
      .pipe(closureCompiler({
        compilerPath: COMPILER_PATH,
        fileName: path.basename(out),
        compilerFlags: combinedArgs
      }))
      .pipe(gulp.dest(path.dirname(out)));
}

/**
 * Normalizes a locale ID for use in a file name (e.g. en-GB -> en_gb).
 * @param {string} locale
 * @return {string} The normalized locale ID.
 */
function getLocaleForFileName(locale) {
  return locale.toLowerCase().replace(/-/g, '_');
}

/**
 * Gets the path to the temporary JS file that contains all FirebaseUI code
 * but no external dependencies.
 * @param {string} locale
 */
function getTmpJsPath(locale) {
  const localeForFileName = getLocaleForFileName(locale);
  return `${TMP_DIR}/firebaseui__${localeForFileName}.js`;
}

/**
 * Repeats a gulp task for all locales.
 * @param {string} taskName The gulp task name to generate. Any $ tokens will be
 *     replaced with the language code (e.g. build-$ becomes build-fr, build-es,
 *     etc.).
 * @param {!Array<string>} dependencies The gulp tasks that each operation
 *     depends on. Any $ tokens will be replaced with the language code.
 * @param {function()} operation The function to execute.
 * @return {!Array<string>} The list of generated task names.
 */
function repeatTaskForAllLocales(taskName, dependencies, operation) {
  const tasks = [];
  ALL_LOCALES.forEach((locale) => {
    // Convert build-js-$ to build-js-fr, for example.
    const replaceTokens = (name) => name.replace(/\$/g, locale);

    const localeTaskName = replaceTokens(taskName);
    tasks.push(localeTaskName);
    const localeDependencies = dependencies.map(replaceTokens);

    gulp.task(localeTaskName, localeDependencies, () => operation(locale));
  });
  return tasks;
}

/**
 * Builds the core FirebaseUI binary in the given locale.
 * @param {string} locale
 */
function buildFirebaseUiJs(locale) {
  const flags = {
    closure_entry_point: 'firebaseui.auth.exports',
    define: `goog.LOCALE='${locale}'`,
    externs: [
      'node_modules/firebase/externs/firebase-app-externs.js',
      'node_modules/firebase/externs/firebase-auth-externs.js',
      'node_modules/firebase/externs/firebase-client-auth-externs.js'
    ],
    only_closure_dependencies: true,
    output_wrapper: OUTPUT_WRAPPER,

    // This is required to match XTB IDs to the JS/Soy messages.
    translations_project: 'FirebaseUI'
  };
  if (locale !== DEFAULT_LOCALE) {
    flags.translations_file = `translations/${locale}.xtb`;
  }
  return compile([
    'node_modules/google-closure-templates/javascript/soyutils_usegoog.js',
    'node_modules/google-closure-library/closure/goog/**/*.js',
    'node_modules/google-closure-library/third_party/closure/goog/**/*.js',
    `${TMP_DIR}/**/*.js`,
    'javascript/**/*.js'
  ], getTmpJsPath(locale), flags);
}

// Builds the core FirebaseUI JS. Generates the gulp tasks
// build-firebaseui-js-de, build-firebaseui-js-fr, etc.
repeatTaskForAllLocales('build-firebaseui-js-$', ['build-soy'],
    buildFirebaseUiJs);

/**
 * Concatenates the core FirebaseUI JS with its external dependencies, and
 * cleans up comments and whitespace in the dependencies.
 * @param {string} locale The desired FirebaseUI locale.
 * @param {string} outBaseName The prefix of the output file name.
 * @param {string} outputWrapper A wrapper with which to wrap the output JS.
 * @return {*} A stream that ends when compilation finishes.
 */
function concatWithDeps(locale, outBaseName, outputWrapper) {
  const localeForFileName = getLocaleForFileName(locale);
  // Get a list of the FirebaseUI JS and its dependencies.
  const srcs = JS_DEPS.concat([getTmpJsPath(locale)]);
  const outputPath = `${DEST_DIR}/${outBaseName}__${localeForFileName}.js`;
  return compile(srcs, outputPath, {
    compilation_level: 'WHITESPACE_ONLY',
    output_wrapper: outputWrapper
  });
}

// Bundles the FirebaseUI JS with its dependencies for all locales.
// Generates the gulp tasks build-js-de, build-js-fr, etc.
const buildJsTasks = repeatTaskForAllLocales(
    'build-js-$', ['build-firebaseui-js-$'],
    (locale) => concatWithDeps(locale, 'firebaseui', OUTPUT_WRAPPER));

/**
 * Creates the default FirebaseUI binaries for basic usage without
 * localization. For example, it copies firebaseui__en.js to firebaseui.js.
 * @param {string} fileName
 */
function makeDefaultFile(fileName) {
  const localeForFileName = getLocaleForFileName(DEFAULT_LOCALE);
  const path = `${DEST_DIR}/${fileName}__${localeForFileName}.js`;
  if (fse.existsSync(path)) {
    return fse.copy(path, `${DEST_DIR}/${fileName}.js`);
  }
}

// Builds the final JS file for all supported languages.
gulp.task('build-all-js', buildJsTasks, () => makeDefaultFile('firebaseui'));

// Builds the final JS file for the default language.
gulp.task('build-js', ['build-js-' + DEFAULT_LOCALE],
    () => makeDefaultFile('firebaseui'));

// Bundles the FirebaseUI JS with its dependencies as a NPM module. This builds
// the NPM module for all languages.
repeatTaskForAllLocales(
    'build-npm-$', ['build-firebaseui-js-$'],
    (locale) => concatWithDeps(locale, 'npm', NPM_MODULE_WRAPPER));

// Builds the NPM module for the default language.
gulp.task('build-npm', ['build-npm-' + DEFAULT_LOCALE],
    () => makeDefaultFile('npm'));

/**
 * Builds the CSS for FirebaseUI.
 * @param {boolean} isRtl Whether to build in right-to-left mode.
 * @return {*} A stream that finishes when compilation finishes.
 */
function buildCss(isRtl) {
  const mdlSrcs = gulp.src('stylesheet/mdl.scss')
      .pipe(sass.sync().on('error', sass.logError));
  const dialogPolyfillSrcs = gulp.src(
      'node_modules/dialog-polyfill/dialog-polyfill.css');
  let firebaseSrcs = gulp.src('stylesheet/*.css');

  // Flip left/right, ltr/rtl for RTL languages.
  if (isRtl) {
    firebaseSrcs = firebaseSrcs.pipe(flip.gulp());
  }

  const outFile = isRtl ? 'firebaseui-rtl.css' : 'firebaseui.css';
  return streamqueue({objectMode: true},
      mdlSrcs, dialogPolyfillSrcs, firebaseSrcs)
      .pipe(concatCSS(outFile))
      .pipe(cleanCSS())
      .pipe(gulp.dest(DEST_DIR));
}

// Concatenates and minifies the CSS sources for LTR languages.
gulp.task('build-css', () => buildCss(false));

// Concatenates and minifies the CSS sources for RTL languages.
gulp.task('build-css-rtl', () => buildCss(true));

// Creates a webserver that serves all files from the root of the package.
gulp.task('serve', () => {
  connect.server({
    port: 4000
  });
});

// Deletes intermediate files.
gulp.task('clean', () => fse.remove(TMP_DIR));

// Executes the basic tasks for the default language.
gulp.task('default', ['build-js', 'build-npm', 'build-css', 'build-css-rtl'],
    () => gulp.start('clean'));

// Builds everything (JS for all languages, both LTR and RTL CSS).
gulp.task('build-all',
    ['build-all-js', 'build-npm', 'build-css', 'build-css-rtl'],
    () => gulp.start('clean'));
<|endoftext|>


<commit_before>var gulp = require('gulp');

var imagemin = require('gulp-imagemin');
var jsonminify = require('gulp-jsonminify');
var minifycss = require('gulp-minify-css');
var minifyhtml = require('gulp-minify-html');
var nib = require('nib');
var stylus = require('gulp-stylus');
var zip = require('gulp-zip');

var version = '1.0.4';

var paths = {
  html: './*.html',
  stylus: './css/*.styl',
  js: './js/*.js',
  json: 'manifest.json',
  img: './img/*.png',
  vendor: [
    './bower_components/angular/angular-csp.css',
    './bower_components/jquery/dist/jquery.min.js',
    './bower_components/angular/angular.min.js',
    './bower_components/Sortable/Sortable.min.js',
    './bower_components/Sortable/ng-sortable.js'
  ]
};

var dest = './dist';

gulp.task('html', function () {
  return gulp.src(paths.html)
    .pipe(minifyhtml())
    .pipe(gulp.dest(dest));
});

gulp.task('css', function () {
  return gulp.src(paths.stylus)
    .pipe(stylus({use: [nib()], errors: true}))
    .pipe(minifycss())
    .pipe(gulp.dest(dest));
});

gulp.task('js', function () {
  return gulp.src(paths.js)
    .pipe(gulp.dest(dest));
});

gulp.task('json', function () {
  return gulp.src(paths.json)
    .pipe(jsonminify())
    .pipe(gulp.dest(dest));
})

gulp.task('img', function () {
  return gulp.src(paths.img)
//    .pipe(imagemin())
    .pipe(gulp.dest(dest + '/img'));
});

gulp.task('vendor', function () {
  return gulp.src(paths.vendor)
    .pipe(gulp.dest(dest + '/vendor'));
});

gulp.task('watch', function () {
  gulp.watch(paths.html, ['html']);
  gulp.watch(paths.stylus, ['css']);
  gulp.watch(paths.js, ['js']);
  gulp.watch(paths.json, ['json']);
  gulp.watch(paths.img, ['img']);
  gulp.watch(paths.vendor, ['vendor']);
})

gulp.task('build', ['watch', 'html', 'css', 'js', 'json', 'img', 'vendor']);

gulp.task('zip', function () {
  return gulp.src(dest + '/*')
    .pipe(zip('tabio-' + version + '.zip'))
    .pipe(gulp.dest(dest));
});

/*
gulp.task('stylus', function () {
  gulp.src(paths.stylus)
    .pipe(stylus({use: [nib()], errors: true}))
    .pipe(gulp.dest('./css'));
});

gulp.task('minify', function() {
  gulp.src(paths.css)
    .pipe(minify())
    .pipe(gulp.dest('./css'));
});

gulp.task('watch', function () {
  gulp.watch(paths.stylus, ['stylus']);
  gulp.watch(paths.css, ['minify']);
});

gulp.task('default', ['watch', 'stylus', 'minify']);
*/
<commit_msg>Enable imagemin<commit_after>var gulp = require('gulp');

var imagemin = require('gulp-imagemin');
var jsonminify = require('gulp-jsonminify');
var minifycss = require('gulp-minify-css');
var minifyhtml = require('gulp-minify-html');
var nib = require('nib');
var stylus = require('gulp-stylus');
var zip = require('gulp-zip');

var version = '1.0.4';

var paths = {
  html: './*.html',
  stylus: './css/*.styl',
  js: './js/*.js',
  json: 'manifest.json',
  img: './img/*.png',
  vendor: [
    './bower_components/angular/angular-csp.css',
    './bower_components/jquery/dist/jquery.min.js',
    './bower_components/angular/angular.min.js',
    './bower_components/Sortable/Sortable.min.js',
    './bower_components/Sortable/ng-sortable.js'
  ]
};

var dest = './dist';

gulp.task('html', function () {
  return gulp.src(paths.html)
    .pipe(minifyhtml())
    .pipe(gulp.dest(dest));
});

gulp.task('css', function () {
  return gulp.src(paths.stylus)
    .pipe(stylus({use: [nib()], errors: true}))
    .pipe(minifycss())
    .pipe(gulp.dest(dest));
});

gulp.task('js', function () {
  return gulp.src(paths.js)
    .pipe(gulp.dest(dest));
});

gulp.task('json', function () {
  return gulp.src(paths.json)
    .pipe(jsonminify())
    .pipe(gulp.dest(dest));
})

gulp.task('img', function () {
  return gulp.src(paths.img)
    .pipe(imagemin())
    .pipe(gulp.dest(dest + '/img'));
});

gulp.task('vendor', function () {
  return gulp.src(paths.vendor)
    .pipe(gulp.dest(dest + '/vendor'));
});

gulp.task('watch', function () {
  gulp.watch(paths.html, ['html']);
  gulp.watch(paths.stylus, ['css']);
  gulp.watch(paths.js, ['js']);
  gulp.watch(paths.json, ['json']);
  gulp.watch(paths.img, ['img']);
  gulp.watch(paths.vendor, ['vendor']);
})

gulp.task('build', ['watch', 'html', 'css', 'js', 'json', 'img', 'vendor']);

gulp.task('zip', function () {
  return gulp.src(dest + '/*')
    .pipe(zip('tabio-' + version + '.zip'))
    .pipe(gulp.dest(dest));
});

/*
gulp.task('stylus', function () {
  gulp.src(paths.stylus)
    .pipe(stylus({use: [nib()], errors: true}))
    .pipe(gulp.dest('./css'));
});

gulp.task('minify', function() {
  gulp.src(paths.css)
    .pipe(minify())
    .pipe(gulp.dest('./css'));
});

gulp.task('watch', function () {
  gulp.watch(paths.stylus, ['stylus']);
  gulp.watch(paths.css, ['minify']);
});

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


<commit_before>// partial of https://github.com/google/web-starter-kit/blob/master/gulpfile.js

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var del = require('del');
var reload = browserSync.reload;

var appPath = {};

// if you want to generate special css,
// just run `gulp serve --p #{$projectName}`
// this use in 'css' task now. it will speedup compile speed
var projectName = '*';

appPath.srcDir = 'app';
appPath.distDir = '_dist';

gulp.task('css', function () {
  return gulp.src(appPath.srcDir + '/css/' + projectName + '.{styl,scss}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.styl', $.stylus()))
    .pipe($.if('*.scss', $.sass({
      outputStyle: "expanded"
    })))
    .pipe($.postcss([
      require('autoprefixer')({browsers: ['last 1 version']})
    ]))
    .pipe(gulp.dest(appPath.distDir + '/css/'))
});

gulp.task('js', function () {
  return gulp.src(appPath.srcDir + '/js/' + projectName + '.src.js')
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.uglify())
    .pipe($.rename(function (path) {
      path.basename = path.basename.replace('.src', '.min');
    }))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest(appPath.distDir + '/js/'))
});

gulp.task('html', function () {
  return gulp.src(appPath.srcDir + '/html/*.{html,jade}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.jade', $.jade()))
    .pipe(gulp.dest(appPath.distDir + '/html/'))
});

gulp.task('clean', del.bind(null, [appPath.distDir]));
gulp.task('clean:css', del.bind(null, [appPath.distDir + '/css']));

gulp.task('serve', function () {
  browserSync({
    open: 'external',
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      scroll: false,
      forms: false
    },
    scrollThrottle: 500,
    startPath: ($.util.env.p ? '_dist/html/' + $.util.env.p + '.html' : null),
    server: ''
  });
});

// Watch Files For Changes & Reload
gulp.task('dev', ['serve'], function () {
  projectName = $.util.env.p ? $.util.env.p : '*';
  // watch the folder to reload if files was change
  gulp.watch([appPath.srcDir + '/js/*.js'], ['js', reload]);
  gulp.watch([appPath.srcDir + '/css/*.{styl,scss}'], ['css', reload]);
  gulp.watch([appPath.srcDir + '/html/*.{html,jade}'], ['html', reload]);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  var name = $.util.env.p ? $.util.env.p : '**';
  return gulp.src(appPath.distDir + '/' + name + '/*')
    .pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start(['html', 'css', 'js']);
});
<commit_msg>調整整體 project 結構<commit_after>// partial of https://github.com/google/web-starter-kit/blob/master/gulpfile.js

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var del = require('del');
var reload = browserSync.reload;

var appPath = {
  srcDir: 'app/',
  distDir: '_dist/'
};

// if you want to generate special css,
// just run `gulp serve --p #{$projectName}`
// this use in 'css' task now. it will speedup compile speed
var projectName = '**/';

gulp.task('css', function () {
  return gulp.src(appPath.srcDir + projectName + '*.{styl,scss}', {base: appPath.srcDir})
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.sourcemaps.init())
    .pipe($.if('*.styl', $.stylus()))
    .pipe($.if('*.scss', $.sass({
      outputStyle: "expanded"
    })))
    .pipe($.postcss([
      require('autoprefixer')({browsers: ['last 1 version']})
    ]))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest(appPath.distDir))
});

gulp.task('js', function () {
  return gulp.src(appPath.srcDir + projectName + '*.js', {base: appPath.srcDir})
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.sourcemaps.init())
    .pipe($.babel())
    .pipe($.uglify())
    .pipe($.rename(function (path) {
      path.basename = path.basename.replace('.src', '.min');
    }))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest(appPath.distDir))
});

gulp.task('html', function () {
  return gulp.src(appPath.srcDir + projectName + '*.{html,jade}', {base: appPath.srcDir})
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.jade', $.jade({
      pretty: true
    })))
    .pipe(gulp.dest(appPath.distDir))
});

gulp.task('clean', del.bind(null, [appPath.distDir]));

gulp.task('clean:css', function() {
  del([appPath.distDir + '**/*.css', appPath.distDir + 'css'])
});

gulp.task('serve', function () {
  browserSync({
    open: 'external',
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      scroll: false,
      forms: false
    },
    scrollThrottle: 500,
    startPath: ($.util.env.p ? appPath.distDir + $.util.env.p : null),
    server: ''
  });
});

// Watch Files For Changes & Reload
gulp.task('dev', ['serve'], function () {
  projectName = $.util.env.p ? $.util.env.p + '/' : projectName;

  // watch the folder to reload if files was change
  gulp.watch([appPath.srcDir + projectName + '*.js'], ['js', reload]);
  gulp.watch([appPath.srcDir + projectName + '*.{styl,scss}'], ['css', reload]);
  gulp.watch([appPath.srcDir + projectName + '*.{html,jade}'], ['html', reload]);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  var name = $.util.env.p ? $.util.env.p : '**';
  return gulp.src(appPath.distDir + name + '/*')
    .pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start(['html', 'css', 'js']);
});
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright (c) 2020 JustCoded.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:

 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 */

(() => {
  'use strict';

  const cfg = require('./gulp-config.js');
  const gulp = require('gulp');
  const del = require('del');
  const path = require('path');
  const browserSync = require('browser-sync').create();

  /**
   * Require gulp task from file
   * @param  {string} taskName     Task name
   * @param  {String} path         Path to task file
   * @param  {Object} options      Options for task
   * @param  {Array}  dependencies Task dependencies
   */
  function requireTask(taskName, path, options, dependencies) {
    let settings = options || {};
    const taskFunction = function (callback) {
      if (settings.checkProduction) {
        settings.isProduction = process.argv[process.argv.length - 1] === 'build';
      }
      if (settings.checkFix) {
        settings.isFix = process.argv[process.argv.length - 1] === 'fix-js';
      }

      let task = require(path + taskName + '.js').call(this, settings);

      return task(callback);
    };

    settings.taskName = taskName;

    if (!Array.isArray(dependencies)) {
      gulp.task(taskName, taskFunction);
    } else if (dependencies.length === 1) {
      gulp.task(taskName, gulp.series(dependencies[0], taskFunction));
    } else {
      gulp.task(taskName, gulp.series(dependencies, taskFunction));
    }
  }

  /**
   * Remove image(s) from build folder if corresponding
   * images were deleted from source folder
   * @param  {Object} event    Event object
   * @param  {String} src      Name of the source folder
   * @param  {String} dest     Name of the destination folder
   */
  function deleteFile(file, src, dest) {
    let fileName = file.path.toString().split('/').pop();
    let fileEventWord = file.event == 'unlink' ? 'deleted' : file.event;

    let filePathFromSrc = path.relative(path.resolve(src), file.path);
    let destFilePath = path.resolve(dest, filePathFromSrc);

    try {
      del.sync(destFilePath);
      console.log(` \u{1b}[32m${fileEventWord}: ${fileName}\u{1b}[0m`);
    } catch (error) {
      console.log(` \u{1b}[31mFile has already deleted\u{1b}[0m`);
    }
  }

  /**
   * Template HTML
   */
  requireTask(`${cfg.task.buildHtml}`, `./${cfg.folder.tasks}/`, {
    templates: cfg.buildHtml.templates,
    dest: cfg.buildHtml.dest,
    error: cfg.error,
  });

  /**
   * Lint HTML
   */
  requireTask(`${cfg.task.lintHtml}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.buildHtml.dest,
    error: cfg.error,
  });

  /**
   * Lint JS
   */
  requireTask(`${cfg.task.lintJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    checkFix: true,
  });

  /**
   * Build JS
   */
  requireTask(`${cfg.task.buildJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    mainJs: cfg.file.mainJs,
    mainJsMin: cfg.file.mainJsMin,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build JS vendor (concatenate vendors array)
   */
  requireTask(`${cfg.task.buildJsVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    temp: cfg.folder.temp,
    vendorJs: cfg.file.vendorJs,
    vendorJsMin: cfg.file.vendorJsMin,
    vendorJsTemp: cfg.file.vendorJsTemp,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles for application
   */
  requireTask(`${cfg.task.buildStyles}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    mainScss: cfg.file.mainScss,
    mainScssMin: cfg.file.mainScssMin,
    sortType: cfg.buildStyles.sortType,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles custom files listed in the config
   */
  requireTask(`${cfg.task.buildStylesCustom}`, `./${cfg.folder.tasks}/`, {
    stylesCustomInfo: cfg.getFilesForStylesCustom(),
    dest: cfg.folder.build,
    sortType: cfg.buildStyles.sortType,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles for vendor
   */
  requireTask(`${cfg.task.buildStylesVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    vendorScss: cfg.file.vendorScss,
    vendorScssMin: cfg.file.vendorScssMin,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Copy & minify images
   */
  requireTask(`${cfg.task.buildImages}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    imageExtensions: cfg.buildImages.imageExtensions,
    isImageMin: cfg.buildImages.isImageMin,
    checkProduction: true,
  });

  /**
   * Clean build folder
   */
  requireTask(`${cfg.task.cleanBuild}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build,
  });

  /**
   * Clean production folder
   */
  requireTask(`${cfg.task.cleanProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.prod,
  });

  /**
   * Copy folders to the build folder
   */
  requireTask(`${cfg.task.copyFiles}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.build,
    filesToCopy: cfg.getFilesToCopy(),
  });

  /**
   * Copy folders to the production folder
   */
  requireTask(`${cfg.task.copyFilesProd}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.prod,
    filesToCopyProd: cfg.getFilesToCopyProd(),
  });

  /**
   * Start browserSync server
   */
  requireTask(`${cfg.task.browserSync}`, `./${cfg.folder.tasks}/`, {
    mainHtml: cfg.file.mainHtml,
    dest: cfg.buildHtml.dest,
    browserSync,
  });

  /**
   * Watch for file changes
   */
  requireTask(`${cfg.task.watch}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    filesToCopy: cfg.getFilesToCopy(),
    browserSync,
    deleteFile,
    tasks: {
      lintJs: cfg.task.lintJs,
      buildJs: cfg.task.buildJs,
      buildStyles: cfg.task.buildStyles,
      buildStylesCustom: cfg.task.buildStylesCustom,
      buildHtml: cfg.task.buildHtml,
      lintHtml: cfg.task.lintHtml,
      buildImages: cfg.task.buildImages,
      copyFiles: cfg.task.copyFiles,
    },
  }, false);

  /**
   * Default Gulp task
   */
  gulp.task('default',
    gulp.series(
      cfg.task.cleanBuild,
      cfg.task.lintJs,
      gulp.parallel(
        gulp.series(
          cfg.task.buildHtml,
          cfg.task.lintHtml,
        ),
        gulp.series(
          cfg.task.buildStyles,
          cfg.task.buildStylesCustom,
          cfg.task.buildStylesVendors,
        ),
        gulp.series(
          cfg.task.buildJs,
          cfg.task.buildJsVendors,
        ),
      ),
      cfg.task.buildImages,
      cfg.task.copyFiles,
      gulp.parallel(
        cfg.task.browserSync,
        cfg.task.watch,
      ),
    )
  );

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('build',
    gulp.series(
      gulp.parallel(
        cfg.task.cleanProd,
        cfg.task.cleanBuild,
      ),
      cfg.task.lintJs,
      gulp.parallel(
        gulp.series(
          cfg.task.buildHtml,
          cfg.task.lintHtml,
        ),
        gulp.series(
          cfg.task.buildStyles,
          cfg.task.buildStylesCustom,
          cfg.task.buildStylesVendors,
        ),
        gulp.series(
          cfg.task.buildJs,
          cfg.task.buildJsVendors,
        ),
      ),
      cfg.task.buildImages,
      cfg.task.copyFiles,
      cfg.task.copyFilesProd,
    ), true);

  /**
  * Fix JS files
  */
  gulp.task('fix-js', gulp.series(cfg.task.lintJs));
})();
<commit_msg>Minor fix<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright (c) 2020 JustCoded.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:

 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 */

(() => {
  'use strict';

  const cfg = require('./gulp-config.js');
  const gulp = require('gulp');
  const del = require('del');
  const path = require('path');
  const browserSync = require('browser-sync').create();

  /**
   * Require gulp task from file
   * @param  {string} taskName     Task name
   * @param  {String} path         Path to task file
   * @param  {Object} options      Options for task
   * @param  {Array}  dependencies Task dependencies
   */
  function requireTask(taskName, path, options, dependencies) {
    let settings = options || {};
    const taskFunction = function (callback) {
      if (settings.checkProduction) {
        settings.isProduction = process.argv[process.argv.length - 1] === 'build';
      }
      if (settings.checkFix) {
        settings.isFix = process.argv[process.argv.length - 1] === 'fix-js';
      }

      let task = require(path + taskName + '.js').call(this, settings);

      return task(callback);
    };

    settings.taskName = taskName;

    if (!Array.isArray(dependencies)) {
      gulp.task(taskName, taskFunction);
    } else if (dependencies.length === 1) {
      gulp.task(taskName, gulp.series(dependencies[0], taskFunction));
    } else {
      gulp.task(taskName, gulp.series(dependencies, taskFunction));
    }
  }

  /**
   * Remove image(s) from build folder if corresponding
   * images were deleted from source folder
   * @param  {Object} event    Event object
   * @param  {String} src      Name of the source folder
   * @param  {String} dest     Name of the destination folder
   */
  function deleteFile(file, src, dest) {
    let fileName = file.path.toString().split('/').pop();
    let fileEventWord = file.event == 'unlink' ? 'deleted' : file.event;

    let filePathFromSrc = path.relative(path.resolve(src), file.path);
    let destFilePath = path.resolve(dest, filePathFromSrc);

    try {
      del.sync(destFilePath);
      console.log(` \u{1b}[32m${fileEventWord}: ${fileName}\u{1b}[0m`);
    } catch (error) {
      console.log(` \u{1b}[31mFile has already deleted\u{1b}[0m`);
    }
  }

  /**
   * Template HTML
   */
  requireTask(`${cfg.task.buildHtml}`, `./${cfg.folder.tasks}/`, {
    templates: cfg.buildHtml.templates,
    dest: cfg.buildHtml.dest,
    error: cfg.error,
  });

  /**
   * Lint HTML
   */
  requireTask(`${cfg.task.lintHtml}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.buildHtml.dest,
    error: cfg.error,
  });

  /**
   * Lint JS
   */
  requireTask(`${cfg.task.lintJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    checkFix: true,
  });

  /**
   * Build JS
   */
  requireTask(`${cfg.task.buildJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    mainJs: cfg.file.mainJs,
    mainJsMin: cfg.file.mainJsMin,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build JS vendor (concatenate vendors array)
   */
  requireTask(`${cfg.task.buildJsVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    temp: cfg.folder.temp,
    vendorJs: cfg.file.vendorJs,
    vendorJsMin: cfg.file.vendorJsMin,
    vendorJsTemp: cfg.file.vendorJsTemp,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles for application
   */
  requireTask(`${cfg.task.buildStyles}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    mainScss: cfg.file.mainScss,
    mainScssMin: cfg.file.mainScssMin,
    sortType: cfg.buildStyles.sortType,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles custom files listed in the config
   */
  requireTask(`${cfg.task.buildStylesCustom}`, `./${cfg.folder.tasks}/`, {
    stylesCustomInfo: cfg.getFilesForStylesCustom(),
    dest: cfg.folder.build,
    sortType: cfg.buildStyles.sortType,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Build styles for vendor
   */
  requireTask(`${cfg.task.buildStylesVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    vendorScss: cfg.file.vendorScss,
    vendorScssMin: cfg.file.vendorScssMin,
    error: cfg.error,
    checkProduction: true,
  });

  /**
   * Copy & minify images
   */
  requireTask(`${cfg.task.buildImages}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    imageExtensions: cfg.buildImages.imageExtensions,
    isImageMin: cfg.buildImages.isImageMin,
    checkProduction: true,
  });

  /**
   * Clean build folder
   */
  requireTask(`${cfg.task.cleanBuild}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build,
  });

  /**
   * Clean production folder
   */
  requireTask(`${cfg.task.cleanProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.prod,
  });

  /**
   * Copy folders to the build folder
   */
  requireTask(`${cfg.task.copyFiles}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.build,
    filesToCopy: cfg.getFilesToCopy(),
  });

  /**
   * Copy folders to the production folder
   */
  requireTask(`${cfg.task.copyFilesProd}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.prod,
    filesToCopyProd: cfg.getFilesToCopyProd(),
  });

  /**
   * Start browserSync server
   */
  requireTask(`${cfg.task.browserSync}`, `./${cfg.folder.tasks}/`, {
    mainHtml: cfg.file.mainHtml,
    dest: cfg.buildHtml.dest,
    browserSync,
  });

  /**
   * Watch for file changes
   */
  requireTask(`${cfg.task.watch}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    filesToCopy: cfg.getFilesToCopy(),
    browserSync,
    deleteFile,
    tasks: {
      lintJs: cfg.task.lintJs,
      buildJs: cfg.task.buildJs,
      buildStyles: cfg.task.buildStyles,
      buildStylesCustom: cfg.task.buildStylesCustom,
      buildHtml: cfg.task.buildHtml,
      lintHtml: cfg.task.lintHtml,
      buildImages: cfg.task.buildImages,
      copyFiles: cfg.task.copyFiles,
    },
  }, false);

  /**
   * Default Gulp task
   */
  gulp.task('default', gulp.series(
    cfg.task.cleanBuild,
    cfg.task.lintJs,
    gulp.parallel(
      gulp.series(
        cfg.task.buildHtml,
        cfg.task.lintHtml,
      ),
      gulp.series(
        cfg.task.buildStyles,
        cfg.task.buildStylesCustom,
        cfg.task.buildStylesVendors,
      ),
      gulp.series(
        cfg.task.buildJs,
        cfg.task.buildJsVendors,
      ),
    ),
    cfg.task.buildImages,
    cfg.task.copyFiles,
    gulp.parallel(
      cfg.task.browserSync,
      cfg.task.watch,
    ),
  )
  );

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('build', gulp.series(
    gulp.parallel(
      cfg.task.cleanProd,
      cfg.task.cleanBuild,
    ),
    cfg.task.lintJs,
    gulp.parallel(
      gulp.series(
        cfg.task.buildHtml,
        cfg.task.lintHtml,
      ),
      gulp.series(
        cfg.task.buildStyles,
        cfg.task.buildStylesCustom,
        cfg.task.buildStylesVendors,
      ),
      gulp.series(
        cfg.task.buildJs,
        cfg.task.buildJsVendors,
      ),
    ),
    cfg.task.buildImages,
    cfg.task.copyFiles,
    cfg.task.copyFilesProd,
  ), true);

  /**
  * Fix JS files
  */
  gulp.task('fix-js', gulp.series(cfg.task.lintJs));
})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var ts = require('gulp-tsc');
var closureCompiler = require('gulp-closure-compiler');
var gzip = require('gulp-gzip');

gulp.task('browserify', ['compile'], function() {
    return browserify({
        entries: ['./src/browser.js']
    }).bundle().pipe(source('unitary.browser.js')).pipe(gulp.dest('./dist'));
});
gulp.task('compile', function() {
    return gulp.src('src/unitary.ts')
        .pipe(ts())
        .pipe(gulp.dest('dist'));
});
gulp.task('canvas', function() {
    return browserify({
        entries: ['./src/canvas.js']
    }).bundle().pipe(source('canvas.js')).pipe(gulp.dest('./dist'));
});
gulp.task('minify', ['browserify', 'canvas'], function(cb) {
    gulp.src('./dist/canvas.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'canvas.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));

    gulp.src('./dist/unitary.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'unitary.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));

    gulp.src('./dist/unitary.browser.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'unitary.browser.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));
});
gulp.task('default', ['minify']);
<commit_msg>gulp version command will change Unitary.VERSION with version number in package.json<commit_after>var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var ts = require('gulp-tsc');
var closureCompiler = require('gulp-closure-compiler');
var gzip = require('gulp-gzip');
var replace = require('gulp-replace');

gulp.task('browserify', ['compile'], function() {
    return browserify({
        entries: ['./src/browser.js']
    }).bundle().pipe(source('unitary.browser.js')).pipe(gulp.dest('./dist'));
});
gulp.task('compile', function() {
    return gulp.src('src/unitary.ts')
        .pipe(ts())
        .pipe(gulp.dest('dist'));
});
gulp.task('canvas', function() {
    return browserify({
        entries: ['./src/canvas.js']
    }).bundle().pipe(source('canvas.js')).pipe(gulp.dest('./dist'));
});
gulp.task('minify', ['browserify', 'canvas'], function(cb) {
    gulp.src('./dist/canvas.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'canvas.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));

    gulp.src('./dist/unitary.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'unitary.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));

    gulp.src('./dist/unitary.browser.js')
    .pipe(closureCompiler({
        compilerPath: './bower_components/closure-compiler/compiler.jar',
        fileName: 'unitary.browser.min.js',
        compilerFlags: {
            compilation_level: 'SIMPLE_OPTIMIZATIONS',
            language_in: 'ECMASCRIPT5_STRICT',
            warning_level: 'QUIET'
        }
    }))
    .pipe(gulp.dest('./dist/'))
    .pipe(gzip()).pipe(gulp.dest('./dist/'));
});
gulp.task('version', function(cb) {
    gulp.src('./src/unitary.ts')
        .pipe(replace(/^export var VERSION = .+$/m, "export var VERSION = '" + require('./package.json').version + "';"))
        .pipe(gulp.dest('./src'));
});
gulp.task('default', ['minify']);
<|endoftext|>


<commit_before>/* global require */
/* global console */

var gulp = require('gulp')
var jshint = require('gulp-jshint')
var mochaPhantomJS = require('gulp-mocha-phantomjs')
var connect = require('gulp-connect')
var rjs = require('gulp-requirejs')
var exec = require('child_process').exec

// https://github.com/spenceralger/gulp-jshint
gulp.task('jshint', function() {
    var globs = [
        'src/*.js', 'gulpfile.js'
    ]
    return gulp.src(globs)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'))
})

// https://github.com/mrhooray/gulp-mocha-phantomjs
gulp.task('mocha', function() {
    return gulp.src('test/*.html')
        .pipe(mochaPhantomJS({
            reporter: 'spec'
        }))
})

// https://github.com/RobinThrift/gulp-requirejs
gulp.task('rjs', function() {
    var build = {
        baseUrl: 'src',
        out: 'dist/loader.js',
        name: 'loader'
    }
    rjs(build)
        .pipe(gulp.dest('.')) // pipe it to the output DIR
})

// https://github.com/floatdrop/gulp-watch
var watchTasks = ['madge', 'jshint', 'rjs', 'mocha']
gulp.task('watch', function( /*callback*/ ) {
    gulp.watch(['src/*.js', 'gulpfile.js', 'test/*'], watchTasks)
})

// https://github.com/pahen/madge
gulp.task('madge', function( /*callback*/ ) {
    exec('madge --format amd ./src/',
        function(error, stdout /*, stderr*/ ) {
            if (error) console.log('exec error: ' + error)
            console.log('module dependencies:')
            console.log(stdout)
        }
    )
    exec('madge --format amd --image ./doc/dependencies.png ./src/',
        function(error /*, stdout, stderr*/ ) {
            if (error) console.log('exec error: ' + error)
        }
    )
})

// https://github.com/AveVlad/gulp-connect
gulp.task('connect', function() {
    connect.server({
        port: 4244
    })
})

// TODO
// https://github.com/search?utf8=%E2%9C%93&q=gulp-mocha-phantomjs+coveralls&type=Code&ref=searchresults
gulp.task('coveralls', function() {})

//
gulp.task('publish', function() {
    var child_process = require('child_process')
    child_process.exec('ls', function(error, stdout, stderr) {
        console.log(error, stdout, stderr)
    })
})

gulp.task('default', watchTasks.concat(['connect', 'watch']))
gulp.task('build', ['jshint', 'rjs', 'mocha'])<commit_msg>- connect<commit_after>/* global require */
/* global console */

var gulp = require('gulp')
var jshint = require('gulp-jshint')
var mochaPhantomJS = require('gulp-mocha-phantomjs')
var rjs = require('gulp-requirejs')
var exec = require('child_process').exec

// https://github.com/spenceralger/gulp-jshint
gulp.task('jshint', function() {
    var globs = [
        'src/*.js', 'gulpfile.js'
    ]
    return gulp.src(globs)
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'))
})

// https://github.com/mrhooray/gulp-mocha-phantomjs
gulp.task('mocha', function() {
    return gulp.src('test/*.html')
        .pipe(mochaPhantomJS({
            reporter: 'spec'
        }))
})

// https://github.com/RobinThrift/gulp-requirejs
gulp.task('rjs', function() {
    var build = {
        baseUrl: 'src',
        out: 'dist/loader.js',
        name: 'loader'
    }
    rjs(build)
        .pipe(gulp.dest('.')) // pipe it to the output DIR
})

// https://github.com/floatdrop/gulp-watch
var watchTasks = ['madge', 'jshint', 'rjs', 'mocha']
gulp.task('watch', function( /*callback*/ ) {
    gulp.watch(['src/*.js', 'gulpfile.js', 'test/*'], watchTasks)
})

// https://github.com/pahen/madge
gulp.task('madge', function( /*callback*/ ) {
    exec('madge --format amd ./src/',
        function(error, stdout /*, stderr*/ ) {
            if (error) console.log('exec error: ' + error)
            console.log('module dependencies:')
            console.log(stdout)
        }
    )
    exec('madge --format amd --image ./doc/dependencies.png ./src/',
        function(error /*, stdout, stderr*/ ) {
            if (error) console.log('exec error: ' + error)
        }
    )
})

// TODO
// https://github.com/search?utf8=%E2%9C%93&q=gulp-mocha-phantomjs+coveralls&type=Code&ref=searchresults
gulp.task('coveralls', function() {})

//
gulp.task('publish', function() {
    var child_process = require('child_process')
    child_process.exec('ls', function(error, stdout, stderr) {
        console.log(error, stdout, stderr)
    })
})

gulp.task('default', watchTasks.concat(['watch']))
gulp.task('build', ['jshint', 'rjs', 'mocha'])<|endoftext|>


<commit_before>'use strict'

const packageJson = require('./package.json')
const version = packageJson.version

// Gulp utility
const gulp = require('gulp')
const del = require('del')
const rename = require('gulp-rename')
const runSequence = require('run-sequence')

// Templates
const transpiler = require('./lib/transpilation/transpiler.js')

// Styles
const sass = require('gulp-sass')
const sasslint = require('gulp-sass-lint')
const nano = require('gulp-cssnano')

// Javascript
const standard = require('gulp-standard')
const rollup = require('rollup-stream')
const vinylSource = require('vinyl-source-stream')
const vinylBuffer = require('vinyl-buffer')
const uglify = require('gulp-uglify')
const uglifySaveLicense = require('uglify-save-license')

// Testing
const mocha = require('gulp-mocha')

// Configuration
const paths = require('./config/paths.js')

// Task for cleaning the distribution
gulp.task('clean', () => {
  return del([paths.dist + '*'])
})

// Task for transpiling the templates
let transpileRunner = templateLanguage => {
  return gulp.src(paths.templates + '*.html')
    .pipe(transpiler(templateLanguage, version))
    .pipe(rename({extname: '.html.' + templateLanguage}))
    .pipe(gulp.dest(paths.distTemplates))
}
gulp.task('build:templates', ['build:templates:nunjucks', 'build:templates:erb', 'build:templates:handlebars', 'build:templates:django'])
gulp.task('build:templates:nunjucks', transpileRunner.bind(null, 'nunjucks'))
gulp.task('build:templates:erb', transpileRunner.bind(null, 'erb'))
gulp.task('build:templates:handlebars', transpileRunner.bind(null, 'handlebars'))
gulp.task('build:templates:django', transpileRunner.bind(null, 'django'))

// Compile Sass to CSS
gulp.task('build:styles', cb => {
  runSequence('build:styles:lint', ['build:styles:compile', 'build:styles:copy'], cb)
})
gulp.task('build:styles:lint', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sasslint({
      config: paths.config + '.sass-lint.yml'
    }))
    .pipe(sasslint.format())
    .pipe(sasslint.failOnError())
})
gulp.task('build:styles:compile', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.distCSS))
    .pipe(rename({ suffix: '.min' }))
    .pipe(nano())
    .pipe(gulp.dest(paths.distCSS))
})
gulp.task('build:styles:copy', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(gulp.dest(paths.distScss))
})

// Build single Javascript file from modules
let scriptsBuilder = fileName => {
  return rollup({
    entry: paths.assetsJs + 'template/' + fileName + '.js',
    context: 'window'
  })
    .pipe(vinylSource(fileName + '.js'))
    .pipe(gulp.dest(paths.distJs))
    .pipe(vinylBuffer())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      preserveComments: uglifySaveLicense
    }))
    .pipe(gulp.dest(paths.distJs))
}
gulp.task('build:scripts', cb => {
  runSequence('build:scripts:lint', ['build:scripts:govuk-template', 'build:scripts:govuk-template-ie'], cb)
})
gulp.task('build:scripts:lint', () => {
  gulp.src([
    '!' + paths.assetsJs + '**/vendor/**/*.js',
    paths.assetsJs + '**/*.js'
  ])
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})
gulp.task('build:scripts:govuk-template', scriptsBuilder.bind(null, 'govuk-template'))
gulp.task('build:scripts:govuk-template-ie', scriptsBuilder.bind(null, 'govuk-template-ie'))

// Task to run the tests
gulp.task('test', () => gulp.src(paths.specs + '*.js', {read: false})
  .pipe(mocha())
)

// Build distribution
gulp.task('build', cb => {
  runSequence('clean', ['build:templates', 'build:styles', 'build:scripts'], cb)
})
<commit_msg>Copy uncompiled JS to the dist folder<commit_after>'use strict'

const packageJson = require('./package.json')
const version = packageJson.version

// Gulp utility
const gulp = require('gulp')
const del = require('del')
const rename = require('gulp-rename')
const runSequence = require('run-sequence')

// Templates
const transpiler = require('./lib/transpilation/transpiler.js')

// Styles
const sass = require('gulp-sass')
const sasslint = require('gulp-sass-lint')
const nano = require('gulp-cssnano')

// Javascript
const standard = require('gulp-standard')
const rollup = require('rollup-stream')
const vinylSource = require('vinyl-source-stream')
const vinylBuffer = require('vinyl-buffer')
const uglify = require('gulp-uglify')
const uglifySaveLicense = require('uglify-save-license')

// Testing
const mocha = require('gulp-mocha')

// Configuration
const paths = require('./config/paths.js')

// Task for cleaning the distribution
gulp.task('clean', () => {
  return del([paths.dist + '*'])
})

// Task for transpiling the templates
let transpileRunner = templateLanguage => {
  return gulp.src(paths.templates + '*.html')
    .pipe(transpiler(templateLanguage, version))
    .pipe(rename({extname: '.html.' + templateLanguage}))
    .pipe(gulp.dest(paths.distTemplates))
}
gulp.task('build:templates', ['build:templates:nunjucks', 'build:templates:erb', 'build:templates:handlebars', 'build:templates:django'])
gulp.task('build:templates:nunjucks', transpileRunner.bind(null, 'nunjucks'))
gulp.task('build:templates:erb', transpileRunner.bind(null, 'erb'))
gulp.task('build:templates:handlebars', transpileRunner.bind(null, 'handlebars'))
gulp.task('build:templates:django', transpileRunner.bind(null, 'django'))

// Compile Sass to CSS
gulp.task('build:styles', cb => {
  runSequence('build:styles:lint', ['build:styles:copy', 'build:styles:compile'], cb)
})
gulp.task('build:styles:lint', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sasslint({
      config: paths.config + '.sass-lint.yml'
    }))
    .pipe(sasslint.format())
    .pipe(sasslint.failOnError())
})
gulp.task('build:styles:compile', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.distCSS))
    .pipe(rename({ suffix: '.min' }))
    .pipe(nano())
    .pipe(gulp.dest(paths.distCSS))
})
gulp.task('build:styles:copy', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(gulp.dest(paths.distScss))
})

// Build single Javascript file from modules
let scriptsBuilder = fileName => {
  return rollup({
    entry: paths.assetsJs + 'template/' + fileName + '.js',
    context: 'window'
  })
    .pipe(vinylSource(fileName + '.js'))
    .pipe(gulp.dest(paths.distJs))
    .pipe(vinylBuffer())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      preserveComments: uglifySaveLicense
    }))
    .pipe(gulp.dest(paths.distJs))
}
gulp.task('build:scripts', cb => {
  runSequence('build:scripts:lint', ['build:scripts:copy', 'build:scripts:govuk-template', 'build:scripts:govuk-template-ie'], cb)
})
gulp.task('build:scripts:lint', () => {
  gulp.src([
    '!' + paths.assetsJs + '**/vendor/**/*.js',
    paths.assetsJs + '**/*.js'
  ])
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})
gulp.task('build:scripts:govuk-template', scriptsBuilder.bind(null, 'govuk-template'))
gulp.task('build:scripts:govuk-template-ie', scriptsBuilder.bind(null, 'govuk-template-ie'))
gulp.task('build:scripts:copy', () => {
  gulp.src(paths.assetsJs + '**/*.js')
    .pipe(gulp.dest(paths.distJs))
})

// Task to run the tests
gulp.task('test', () => gulp.src(paths.specs + '*.js', {read: false})
  .pipe(mocha())
)

// Build distribution
gulp.task('build', cb => {
  runSequence('clean', ['build:templates', 'build:styles', 'build:scripts'], cb)
})
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    path = require('path'),
    gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    webpack = require('webpack'),
    babelLoader = require('babel-loader');

var BUILD = process.env.NODE_ENV === 'production';

if( ! BUILD ) {
  var browserSync = require('browser-sync').create(),
      reload = browserSync.reload,
      nodemon = require('nodemon');
}

gulp.task('default',['serve'],function() {});

gulp.task('build',['sass','webpack'],function() { return gutil.log("Completed"); });

gulp.task('webpack',function(callback) {
  var init = false;

  webpack({
    entry : './static/js/index.js',

    output : {
      publicPath: '/dist/js/',
      path : path.join(__dirname, 'static/dist/js'),
      filename : 'bundle.js'
    },

    watch : !BUILD,
    devtool : BUILD ? '' : '#source-map',

    resolve : {
      alias : {
        fs : 'browserify-fs'
      }
    },

    node : {
      process: true
    },

    module : {
      loaders : [
        { test: /\.js$/, loader: 'babel-loader', exclude: /(node_modules)/ }
      ]
    },

    plugins : BUILD ? [ new webpack.optimize.UglifyJsPlugin({ sourceMap: false }) ] : []

  }, function( err, stats ) {
    if(err) throw new gutil.PluginError('webpack',err);
    gutil.log("[webpack]",stats.toString({
      cached: false,
      colors: true
    }));
    if(!BUILD) reload();
    if(!init) { callback(); init = true; }
  });
});

gulp.task('sass',function() {
  var stream = gulp.src('./static/sass/**/*.scss')
    .pipe(sass({
      outputStyle : BUILD ? 'compressed' : 'nested'
    })).on('error', sass.logError)
    .pipe(gulp.dest('./static/style'));

    if(!BUILD) return stream.pipe(reload({stream:true}));
    else return stream;
});

gulp.task('serve',['nodemon','webpack'],function() {
  browserSync.init(null,{
    proxy : 'http://localhost:3000',
    port : 7000
  });

  gulp.watch('static/sass/**/*.scss',['sass']);
  gulp.watch(["static/index.html"]).on("change",reload);
});

gulp.task('nodemon',function(cb) {
  var init = true;

  nodemon({
    script: 'app.js',
    watch: ['app.js']
  }).on('start', function() {
    if(init) cb(); // Only call cb once when server is started initially.
    setTimeout(function() { reload(); },1000);
    init = false;
  });
});

<commit_msg>Better webpack error handling<commit_after>var gulp = require('gulp'),
    path = require('path'),
    gutil = require('gulp-util'),
    sass = require('gulp-sass'),
    webpack = require('webpack'),
    babelLoader = require('babel-loader');

var BUILD = process.env.NODE_ENV === 'production';

if( ! BUILD ) {
  var browserSync = require('browser-sync').create(),
      reload = browserSync.reload,
      nodemon = require('nodemon');
}

gulp.task('default',['serve'],function() {});

gulp.task('build',['sass','webpack'],function() { return gutil.log("Completed"); });

gulp.task('webpack',function(callback) {
  var init = false;

  webpack({
    entry : './static/js/index.js',

    output : {
      publicPath: '/dist/js/',
      path : path.join(__dirname, 'static/dist/js'),
      filename : 'bundle.js'
    },

    watch : !BUILD,
    devtool : BUILD ? '' : '#source-map',

    resolve : {
      alias : {
        fs : 'browserify-fs'
      }
    },

    node : {
      process: true
    },

    module : {
      loaders : [
        { test: /\.js$/, loader: 'babel-loader', exclude: /(node_modules)/ }
      ]
    },

    plugins : BUILD ? [ new webpack.optimize.UglifyJsPlugin({ sourceMap: false }) ] : []

  }, function( err, stats ) {
    if(err) throw new gutil.PluginError('webpack',err);

    var jsonStats = stats.toJson();
    if(jsonStats.errors.length > 0)
      jsonStats.errors.forEach(function(error) {
        gutil.log(gutil.colors.magenta('webpack'),gutil.colors.bold.red('error'),error);
      });
    if(jsonStats.warnings.length > 0)
      jsonStats.warnings.forEach(function(warning) {
        gutil.log(gutil.colors.magenta('webpack'),gutil.colors.bold.yellow('warning'),warning);
      });

    if(!BUILD) reload();
    if(!init) { callback(); init = true; }
  });
});

gulp.task('sass',function() {
  var stream = gulp.src('./static/sass/**/*.scss')
    .pipe(sass({
      outputStyle : BUILD ? 'compressed' : 'nested'
    })).on('error', sass.logError)
    .pipe(gulp.dest('./static/style'));

    if(!BUILD) return stream.pipe(reload({stream:true}));
    else return stream;
});

gulp.task('serve',['nodemon','webpack'],function() {
  browserSync.init(null,{
    proxy : 'http://localhost:3000',
    port : 7000
  });

  gulp.watch('static/sass/**/*.scss',['sass']);
  gulp.watch(["static/index.html"]).on("change",reload);
});

gulp.task('nodemon',function(cb) {
  var init = true;

  nodemon({
    script: 'app.js',
    watch: ['app.js']
  }).on('start', function() {
    if(init) cb(); // Only call cb once when server is started initially.
    setTimeout(function() { reload(); },1000);
    init = false;
  });
});

<|endoftext|>


<commit_before>// Generated on 2016-01-26 using generator-angular 0.15.1
'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var openURL = require('open');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var wiredep = require('wiredep').stream;
var runSequence = require('run-sequence');
var ngConstant = require('gulp-ng-constant');
var browserSync = require('browser-sync').create();
var history = require('connect-history-api-fallback');
var express = require('express');
var proxy = require('http-proxy');

var yeoman = {
  app: require('./bower.json').appPath || 'app',
  dist: 'dist'
};

var paths = {
  scripts: [yeoman.app + '/scripts/**/*.js'],
  styles: [yeoman.app + '/styles/**/*.scss'],
  test: ['test/spec/**/*.js'],
  testRequire: [
    yeoman.app + '/bower_components/angular/angular.js',
    yeoman.app + '/bower_components/angular-mocks/angular-mocks.js',
    yeoman.app + '/bower_components/angular-resource/angular-resource.js',
    yeoman.app + '/bower_components/angular-cookies/angular-cookies.js',
    yeoman.app + '/bower_components/angular-sanitize/angular-sanitize.js',
    yeoman.app + '/bower_components/angular-route/angular-route.js',
    'test/mock/**/*.js',
    'test/spec/**/*.js'
  ],
  karma: 'karma.conf.js',
  views: {
    main: yeoman.app + '/index.html',
    files: [yeoman.app + '/views/**/*.html']
  }
};

////////////////////////
// Reusable pipelines //
////////////////////////

var lintScripts = lazypipe()
  .pipe($.jshint, '.jshintrc')
  .pipe($.jshint.reporter, 'jshint-stylish');

var styles = lazypipe()
  .pipe($.sass, {
    outputStyle: 'expanded',
    precision: 10
  })
  .pipe($.autoprefixer, 'last 1 version')
  .pipe(gulp.dest, '.tmp/styles');

///////////
// Tasks //
///////////

var jenkinsServers = process.env.JENKINS_SERVERS || 'http://localhost:8080/jenkins';
jenkinsServers = jenkinsServers.split(/\s*,\s*/);

var solrAddress = process.env.SOLR_ADDRESS || 'http://localhost:8983';
var app = express();
var proxy = proxy.createProxyServer({ target: solrAddress });

gulp.task('config', function () {
    return ngConstant({
        name: 'testReporterApp',
        stream: true,
        deps: false,
        constants: {
          jenkinsServers: jenkinsServers
        }
    })
    // Writes config.js to scripts/ folder
    .pipe(gulp.dest(yeoman.app + '/scripts'));
});

gulp.task('config:prod', function() {
  return ngConstant({
    name: 'testReporterApp',
    stream: true,
    deps: false,
    constants: {
      jenkinsServers: jenkinsServers
    }
  })
  // Writes config.js to scripts/ folder
    .pipe(gulp.dest(yeoman.dist + '/scripts'));
});

gulp.task('styles', function () {
  return gulp.src(paths.styles)
    .pipe(styles());
});

gulp.task('lint:scripts', function () {
  return gulp.src(paths.scripts)
    .pipe(lintScripts());
});

gulp.task('clean:tmp', function (cb) {
  rimraf('./.tmp', cb);
});

gulp.task('start:client', ['start:server', 'styles'], function () {
  openURL('http://localhost:9000');
});

let proxyToSolrInstance = function(req, res) {
  proxy.web(req, res);
};
app.get('/solr*', proxyToSolrInstance);
app.post('/solr*', proxyToSolrInstance);

gulp.task('start:server', function() {
  $.connect.server({
    root: [yeoman.app, '.tmp'],
    livereload: true,
    // Change this to '0.0.0.0' to access the server from outside.
    port: 9000,
    middleware: function(connect) {
        return [
          app,
          connect().use('/bower_components', connect.static('bower_components')),
          connect().use('/node_modules', connect.static('node_modules')),
          history()
        ];
    }
  });
  // browserSync.init({ proxy: 'localhost:9000' });
});

gulp.task('start:server:test', function() {
  $.connect.server({
    root: ['test', yeoman.app, '.tmp'],
    livereload: true,
    port: 9001
  });
});

gulp.task('watch', function () {
  $.watch(paths.styles)
    .pipe($.plumber())
    .pipe(styles())
    .pipe($.connect.reload());

  $.watch(paths.views.files)
    .pipe($.plumber())
    .pipe($.connect.reload());

  $.watch(paths.scripts)
    .pipe($.plumber())
    .pipe(lintScripts())
    .pipe($.connect.reload());

  $.watch(paths.test)
    .pipe($.plumber())
    .pipe(lintScripts());

  gulp.watch('bower.json', ['bower']);
});

gulp.task('serve', function (cb) {
  runSequence('clean:tmp',
    'config',
    ['lint:scripts'],
    ['start:client'],
    'watch', cb);
});

gulp.task('serve:prod', ['config:prod'], function() {
  $.connect.server({
    root: [yeoman.dist],
    livereload: false,
    port: 9000
  });
});

gulp.task('test', ['start:server:test'], function () {
  var testToFiles = paths.testRequire.concat(paths.scripts, paths.test);
  return gulp.src(testToFiles)
    .pipe($.karma({
      configFile: paths.karma,
      action: 'watch'
    }));
});

// inject bower components
gulp.task('bower', function () {
  return gulp.src(paths.views.main)
    .pipe(wiredep({
      ignorePath: '../'
    }))
  .pipe(gulp.dest(yeoman.app));
});

///////////
// Build //
///////////

gulp.task('clean:dist', function (cb) {
  rimraf('./dist', cb);
});

gulp.task('client:build', ['html', 'styles', 'config'], function () {
  var jsFilter = $.filter('**/*.js');
  var cssFilter = $.filter('**/*.css');

  return gulp.src(paths.views.main)
    .pipe($.useref({searchPath: [yeoman.app, '.tmp']}))
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    .pipe($.uglify())
    .on('error', $.util.log)
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.minifyCss({cache: true}))
    .pipe(cssFilter.restore())
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('html', function () {
  return gulp.src(yeoman.app + '/views/**/*')
    .pipe(gulp.dest(yeoman.dist + '/views'));
});

gulp.task('images', function () {
  return gulp.src(yeoman.app + '/images/**/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images'));
});

gulp.task('copy:extras', function () {
  return gulp.src(yeoman.app + '/*/.*', { dot: true })
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('copy:fonts', function () {
  return gulp.src(yeoman.app + '/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('build', ['clean:dist'], function () {
  runSequence(['images', 'copy:extras', 'copy:fonts', 'client:build']);
});

gulp.task('default', ['build']);
<commit_msg>un commented the browser sync proxy<commit_after>// Generated on 2016-01-26 using generator-angular 0.15.1
'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var openURL = require('open');
var lazypipe = require('lazypipe');
var rimraf = require('rimraf');
var wiredep = require('wiredep').stream;
var runSequence = require('run-sequence');
var ngConstant = require('gulp-ng-constant');
var browserSync = require('browser-sync').create();
var history = require('connect-history-api-fallback');
var express = require('express');
var proxy = require('http-proxy');

var yeoman = {
  app: require('./bower.json').appPath || 'app',
  dist: 'dist'
};

var paths = {
  scripts: [yeoman.app + '/scripts/**/*.js'],
  styles: [yeoman.app + '/styles/**/*.scss'],
  test: ['test/spec/**/*.js'],
  testRequire: [
    yeoman.app + '/bower_components/angular/angular.js',
    yeoman.app + '/bower_components/angular-mocks/angular-mocks.js',
    yeoman.app + '/bower_components/angular-resource/angular-resource.js',
    yeoman.app + '/bower_components/angular-cookies/angular-cookies.js',
    yeoman.app + '/bower_components/angular-sanitize/angular-sanitize.js',
    yeoman.app + '/bower_components/angular-route/angular-route.js',
    'test/mock/**/*.js',
    'test/spec/**/*.js'
  ],
  karma: 'karma.conf.js',
  views: {
    main: yeoman.app + '/index.html',
    files: [yeoman.app + '/views/**/*.html']
  }
};

////////////////////////
// Reusable pipelines //
////////////////////////

var lintScripts = lazypipe()
  .pipe($.jshint, '.jshintrc')
  .pipe($.jshint.reporter, 'jshint-stylish');

var styles = lazypipe()
  .pipe($.sass, {
    outputStyle: 'expanded',
    precision: 10
  })
  .pipe($.autoprefixer, 'last 1 version')
  .pipe(gulp.dest, '.tmp/styles');

///////////
// Tasks //
///////////

var jenkinsServers = process.env.JENKINS_SERVERS || 'http://localhost:8080/jenkins';
jenkinsServers = jenkinsServers.split(/\s*,\s*/);

var solrAddress = process.env.SOLR_ADDRESS || 'http://localhost:8983';
var app = express();
var proxy = proxy.createProxyServer({ target: solrAddress });

gulp.task('config', function () {
    return ngConstant({
        name: 'testReporterApp',
        stream: true,
        deps: false,
        constants: {
          jenkinsServers: jenkinsServers
        }
    })
    // Writes config.js to scripts/ folder
    .pipe(gulp.dest(yeoman.app + '/scripts'));
});

gulp.task('config:prod', function() {
  return ngConstant({
    name: 'testReporterApp',
    stream: true,
    deps: false,
    constants: {
      jenkinsServers: jenkinsServers
    }
  })
  // Writes config.js to scripts/ folder
    .pipe(gulp.dest(yeoman.dist + '/scripts'));
});

gulp.task('styles', function () {
  return gulp.src(paths.styles)
    .pipe(styles());
});

gulp.task('lint:scripts', function () {
  return gulp.src(paths.scripts)
    .pipe(lintScripts());
});

gulp.task('clean:tmp', function (cb) {
  rimraf('./.tmp', cb);
});

gulp.task('start:client', ['start:server', 'styles'], function () {
  openURL('http://localhost:9000');
});

let proxyToSolrInstance = function(req, res) {
  proxy.web(req, res);
};
app.get('/solr*', proxyToSolrInstance);
app.post('/solr*', proxyToSolrInstance);

gulp.task('start:server', function() {
  $.connect.server({
    root: [yeoman.app, '.tmp'],
    livereload: true,
    // Change this to '0.0.0.0' to access the server from outside.
    port: 9000,
    middleware: function(connect) {
        return [
          app,
          connect().use('/bower_components', connect.static('bower_components')),
          connect().use('/node_modules', connect.static('node_modules')),
          history()
        ];
    }
  });
  browserSync.init({ proxy: 'localhost:9000' });
});

gulp.task('start:server:test', function() {
  $.connect.server({
    root: ['test', yeoman.app, '.tmp'],
    livereload: true,
    port: 9001
  });
});

gulp.task('watch', function () {
  $.watch(paths.styles)
    .pipe($.plumber())
    .pipe(styles())
    .pipe($.connect.reload());

  $.watch(paths.views.files)
    .pipe($.plumber())
    .pipe($.connect.reload());

  $.watch(paths.scripts)
    .pipe($.plumber())
    .pipe(lintScripts())
    .pipe($.connect.reload());

  $.watch(paths.test)
    .pipe($.plumber())
    .pipe(lintScripts());

  gulp.watch('bower.json', ['bower']);
});

gulp.task('serve', function (cb) {
  runSequence('clean:tmp',
    'config',
    ['lint:scripts'],
    ['start:client'],
    'watch', cb);
});

gulp.task('serve:prod', ['config:prod'], function() {
  $.connect.server({
    root: [yeoman.dist],
    livereload: false,
    port: 9000
  });
});

gulp.task('test', ['start:server:test'], function () {
  var testToFiles = paths.testRequire.concat(paths.scripts, paths.test);
  return gulp.src(testToFiles)
    .pipe($.karma({
      configFile: paths.karma,
      action: 'watch'
    }));
});

// inject bower components
gulp.task('bower', function () {
  return gulp.src(paths.views.main)
    .pipe(wiredep({
      ignorePath: '../'
    }))
  .pipe(gulp.dest(yeoman.app));
});

///////////
// Build //
///////////

gulp.task('clean:dist', function (cb) {
  rimraf('./dist', cb);
});

gulp.task('client:build', ['html', 'styles', 'config'], function () {
  var jsFilter = $.filter('**/*.js');
  var cssFilter = $.filter('**/*.css');

  return gulp.src(paths.views.main)
    .pipe($.useref({searchPath: [yeoman.app, '.tmp']}))
    .pipe(jsFilter)
    .pipe($.ngAnnotate())
    .pipe($.uglify())
    .on('error', $.util.log)
    .pipe(jsFilter.restore())
    .pipe(cssFilter)
    .pipe($.minifyCss({cache: true}))
    .pipe(cssFilter.restore())
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('html', function () {
  return gulp.src(yeoman.app + '/views/**/*')
    .pipe(gulp.dest(yeoman.dist + '/views'));
});

gulp.task('images', function () {
  return gulp.src(yeoman.app + '/images/**/*')
    .pipe($.cache($.imagemin({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(yeoman.dist + '/images'));
});

gulp.task('copy:extras', function () {
  return gulp.src(yeoman.app + '/*/.*', { dot: true })
    .pipe(gulp.dest(yeoman.dist));
});

gulp.task('copy:fonts', function () {
  return gulp.src(yeoman.app + '/fonts/**/*')
    .pipe(gulp.dest(yeoman.dist + '/fonts'));
});

gulp.task('build', ['clean:dist'], function () {
  runSequence(['images', 'copy:extras', 'copy:fonts', 'client:build']);
});

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


<commit_before>var gulp       = require('gulp'),
    gutil      = require('gulp-util'),
    less       = require('gulp-less'),
    concat     = require('gulp-concat'),
    minifyCSS  = require('gulp-minify-css'),
    uglify     = require('gulp-uglify'),
    watch      = require('gulp-watch'),
    livereload = require('gulp-livereload'),
    rename     = require('gulp-rename'),
    prefix     = require('gulp-autoprefixer'),
    ngAnnotate = require('gulp-ng-annotate'),
    del        = require('del'),
    rev        = require('gulp-rev'),
    vinylPaths = require('vinyl-paths');

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

// Compile Less and save to css directory
gulp.task('less-public', function () {

    return gulp.src('resources/assets/less/public/master.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('> 1%', 'ie >= 8'))
        .pipe(minifyCSS())
        .pipe(rename('public.css'))
        .pipe(gulp.dest('public/css'))
        .pipe(livereload());

});

gulp.task('less-admin', function () {

    return gulp.src('resources/assets/less/admin/master.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('last 2 versions', '> 1%', 'Explorer 7', 'Android 2'))
        .pipe(minifyCSS())
        .pipe(rename('admin.css'))
        .pipe(gulp.dest('public/css'))
        .pipe(livereload());

});

// version
gulp.task('version', function() {

    var publicDir = 'public',
        buildDir = publicDir + '/build',
        files = vinylPaths();

    del.sync(buildDir + '/*', { force: true });

    return gulp.src([
            publicDir + '/css/*',
            publicDir + '/js/admin/*',
            publicDir + '/js/public/*'
        ], { base: './' + publicDir })
        .pipe(gulp.dest(buildDir))
        .pipe(files)
        .pipe(rev())
        .pipe(gulp.dest(buildDir))
        .pipe(rev.manifest())
        .pipe(gulp.dest(buildDir))
        .on('end', function() {
            del(files.paths);
        });
});

// Publish fonts
gulp.task('fonts', function () {

    var destDir = 'public/fonts';

    return gulp.src([
            'node_modules/font-awesome/fonts/*'
        ])
        .pipe(gulp.dest(destDir));

});

// Publish angular locales
gulp.task('angular-locales', function () {

    var destDir = 'public/js/angular-locales';

    return gulp.src([
            'node_modules/angular-i18n/angular-locale_fr-fr.js',
            'node_modules/angular-i18n/angular-locale_nl-nl.js'
        ])
        .pipe(gulp.dest(destDir));

});

// Publish Fancybox images
gulp.task('fancybox-img', function () {

    var destDir = 'public/components/fancybox/source';

    return gulp.src('node_modules/fancybox/dist/img/*')
        .pipe(gulp.dest(destDir));

});

// Publish CKEditor
gulp.task('ckeditor', function () {

    // Base files
    gulp.src([
        'bower_components/ckeditor/ckeditor.js',
        'bower_components/ckeditor/styles.js',
        'bower_components/ckeditor/contents.css'
    ])
    .pipe(gulp.dest('public/components/ckeditor'));

    // Lang files
    gulp.src([
            'bower_components/ckeditor/lang/fr.js',
            'bower_components/ckeditor/lang/es.js',
            'bower_components/ckeditor/lang/pt.js',
            'bower_components/ckeditor/lang/de.js',
            'bower_components/ckeditor/lang/en.js',
            'bower_components/ckeditor/lang/nl.js'
        ])
        .pipe(gulp.dest('public/components/ckeditor/lang'));

    // Plugins
    var plugins = ['clipboard', 'image', 'image2', 'justify', 'lineutils', 'link', 'magicline', 'panelbutton', 'showblocks', 'specialchar', 'table', 'widget'];
    for (var i = 0; i < plugins.length; i++) {
        gulp.src(['bower_components/ckeditor/plugins/' + plugins[i] + '/**/*'])
            .pipe(gulp.dest('public/components/ckeditor/plugins/' + plugins[i]));
    }

});

gulp.task('js-admin', function () {

    var destDir = 'public/js/admin',
        destFile = 'components.min.js',
        files = [
            'node_modules/jquery/dist/jquery.js',
            'node_modules/angular/angular.js',
            'node_modules/angular-resource/angular-resource.js',
            'node_modules/angular-smart-table/dist/smart-table.js',
            'node_modules/angular-ui-tree/dist/angular-ui-tree.js',
            'node_modules/jsurl/url.js',
            'node_modules/bootstrap/js/dropdown.js',
            'node_modules/bootstrap/js/collapse.js',
            'node_modules/bootstrap/js/alert.js',
            'node_modules/bootstrap/js/tab.js',
            'node_modules/bootstrap/js/transition.js',
            'node_modules/alertify.js/dist/js/alertify.js',
            'node_modules/dropzone/dist/dropzone.js',
            'node_modules/selectize/dist/js/standalone/selectize.js',
            'node_modules/fancybox/dist/js/jquery.fancybox.js',
            'resources/assets/js/admin/*',
            'resources/assets/typicms/**/*.js'
        ];

    return gulp.src(files)
        .pipe(concat('components.js'))
        .pipe(ngAnnotate())
        .pipe(uglify())
        .on('error', swallowError)
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));

});

gulp.task('js-public', function () {

    var destDir = 'public/js/public',
        destFile = 'components.min.js',
        files = [
            'node_modules/jquery/dist/jquery.js',
            'node_modules/bootstrap/js/dropdown.js',
            'node_modules/bootstrap/js/collapse.js',
            'node_modules/bootstrap/js/alert.js',
            'node_modules/bootstrap/js/tab.js',
            'node_modules/bootstrap/js/transition.js',
            'node_modules/fancybox/dist/js/jquery.fancybox.js',
            'node_modules/swiper/dist/js/swiper.jquery.js',
            'resources/assets/js/public/*'
        ];

    return gulp.src(files)
        .pipe(concat('components.js'))
        .pipe(uglify())
        .on('error', swallowError)
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));

});

// Keep an eye on Less and JS files for changes…
gulp.task('watch', function () {
    livereload.listen();
    gulp.watch('resources/assets/less/public/**/*.less', ['less-public']);
    gulp.watch('resources/assets/less/admin/**/*.less', ['less-admin']);
    gulp.watch('resources/assets/less/*.less', ['less-public', 'less-admin']);
    gulp.watch('resources/assets/js/public/**/*.js', ['js-public']);
    gulp.watch('resources/assets/js/admin/**/*.js', ['js-admin']);
    gulp.watch('resources/assets/typicms/**/*.js', ['js-admin']);
    gulp.watch(['public/css/*.css', 'public/js/admin/*.js', 'public/js/public/*.js'], ['version']);
});

// What tasks does running gulp trigger?
gulp.task('all', [
    'less-public',
    'less-admin',
    'js-public',
    'js-admin',
    'fonts',
    'angular-locales',
    'fancybox-img',
    'ckeditor',
    'watch'
]);

gulp.task('default', [
    'less-public',
    'js-public',
    'watch'
]);
<commit_msg>jsurl removed<commit_after>var gulp       = require('gulp'),
    gutil      = require('gulp-util'),
    less       = require('gulp-less'),
    concat     = require('gulp-concat'),
    minifyCSS  = require('gulp-minify-css'),
    uglify     = require('gulp-uglify'),
    watch      = require('gulp-watch'),
    livereload = require('gulp-livereload'),
    rename     = require('gulp-rename'),
    prefix     = require('gulp-autoprefixer'),
    ngAnnotate = require('gulp-ng-annotate'),
    del        = require('del'),
    rev        = require('gulp-rev'),
    vinylPaths = require('vinyl-paths');

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

// Compile Less and save to css directory
gulp.task('less-public', function () {

    return gulp.src('resources/assets/less/public/master.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('> 1%', 'ie >= 8'))
        .pipe(minifyCSS())
        .pipe(rename('public.css'))
        .pipe(gulp.dest('public/css'))
        .pipe(livereload());

});

gulp.task('less-admin', function () {

    return gulp.src('resources/assets/less/admin/master.less')
        .pipe(less())
        .on('error', swallowError)
        .pipe(prefix('last 2 versions', '> 1%', 'Explorer 7', 'Android 2'))
        .pipe(minifyCSS())
        .pipe(rename('admin.css'))
        .pipe(gulp.dest('public/css'))
        .pipe(livereload());

});

// version
gulp.task('version', function() {

    var publicDir = 'public',
        buildDir = publicDir + '/build',
        files = vinylPaths();

    del.sync(buildDir + '/*', { force: true });

    return gulp.src([
            publicDir + '/css/*',
            publicDir + '/js/admin/*',
            publicDir + '/js/public/*'
        ], { base: './' + publicDir })
        .pipe(gulp.dest(buildDir))
        .pipe(files)
        .pipe(rev())
        .pipe(gulp.dest(buildDir))
        .pipe(rev.manifest())
        .pipe(gulp.dest(buildDir))
        .on('end', function() {
            del(files.paths);
        });
});

// Publish fonts
gulp.task('fonts', function () {

    var destDir = 'public/fonts';

    return gulp.src([
            'node_modules/font-awesome/fonts/*'
        ])
        .pipe(gulp.dest(destDir));

});

// Publish angular locales
gulp.task('angular-locales', function () {

    var destDir = 'public/js/angular-locales';

    return gulp.src([
            'node_modules/angular-i18n/angular-locale_fr-fr.js',
            'node_modules/angular-i18n/angular-locale_nl-nl.js'
        ])
        .pipe(gulp.dest(destDir));

});

// Publish Fancybox images
gulp.task('fancybox-img', function () {

    var destDir = 'public/components/fancybox/source';

    return gulp.src('node_modules/fancybox/dist/img/*')
        .pipe(gulp.dest(destDir));

});

// Publish CKEditor
gulp.task('ckeditor', function () {

    // Base files
    gulp.src([
        'bower_components/ckeditor/ckeditor.js',
        'bower_components/ckeditor/styles.js',
        'bower_components/ckeditor/contents.css'
    ])
    .pipe(gulp.dest('public/components/ckeditor'));

    // Lang files
    gulp.src([
            'bower_components/ckeditor/lang/fr.js',
            'bower_components/ckeditor/lang/es.js',
            'bower_components/ckeditor/lang/pt.js',
            'bower_components/ckeditor/lang/de.js',
            'bower_components/ckeditor/lang/en.js',
            'bower_components/ckeditor/lang/nl.js'
        ])
        .pipe(gulp.dest('public/components/ckeditor/lang'));

    // Plugins
    var plugins = ['clipboard', 'image', 'image2', 'justify', 'lineutils', 'link', 'magicline', 'panelbutton', 'showblocks', 'specialchar', 'table', 'widget'];
    for (var i = 0; i < plugins.length; i++) {
        gulp.src(['bower_components/ckeditor/plugins/' + plugins[i] + '/**/*'])
            .pipe(gulp.dest('public/components/ckeditor/plugins/' + plugins[i]));
    }

});

gulp.task('js-admin', function () {

    var destDir = 'public/js/admin',
        destFile = 'components.min.js',
        files = [
            'node_modules/jquery/dist/jquery.js',
            'node_modules/angular/angular.js',
            'node_modules/angular-resource/angular-resource.js',
            'node_modules/angular-smart-table/dist/smart-table.js',
            'node_modules/angular-ui-tree/dist/angular-ui-tree.js',
            'node_modules/bootstrap/js/dropdown.js',
            'node_modules/bootstrap/js/collapse.js',
            'node_modules/bootstrap/js/alert.js',
            'node_modules/bootstrap/js/tab.js',
            'node_modules/bootstrap/js/transition.js',
            'node_modules/alertify.js/dist/js/alertify.js',
            'node_modules/dropzone/dist/dropzone.js',
            'node_modules/selectize/dist/js/standalone/selectize.js',
            'node_modules/fancybox/dist/js/jquery.fancybox.js',
            'resources/assets/js/admin/*',
            'resources/assets/typicms/**/*.js'
        ];

    return gulp.src(files)
        .pipe(concat('components.js'))
        .pipe(ngAnnotate())
        .pipe(uglify())
        .on('error', swallowError)
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));

});

gulp.task('js-public', function () {

    var destDir = 'public/js/public',
        destFile = 'components.min.js',
        files = [
            'node_modules/jquery/dist/jquery.js',
            'node_modules/bootstrap/js/dropdown.js',
            'node_modules/bootstrap/js/collapse.js',
            'node_modules/bootstrap/js/alert.js',
            'node_modules/bootstrap/js/tab.js',
            'node_modules/bootstrap/js/transition.js',
            'node_modules/fancybox/dist/js/jquery.fancybox.js',
            'node_modules/swiper/dist/js/swiper.jquery.js',
            'resources/assets/js/public/*'
        ];

    return gulp.src(files)
        .pipe(concat('components.js'))
        .pipe(uglify())
        .on('error', swallowError)
        .pipe(rename(destFile))
        .pipe(gulp.dest(destDir));

});

// Keep an eye on Less and JS files for changes…
gulp.task('watch', function () {
    livereload.listen();
    gulp.watch('resources/assets/less/public/**/*.less', ['less-public']);
    gulp.watch('resources/assets/less/admin/**/*.less', ['less-admin']);
    gulp.watch('resources/assets/less/*.less', ['less-public', 'less-admin']);
    gulp.watch('resources/assets/js/public/**/*.js', ['js-public']);
    gulp.watch('resources/assets/js/admin/**/*.js', ['js-admin']);
    gulp.watch('resources/assets/typicms/**/*.js', ['js-admin']);
    gulp.watch(['public/css/*.css', 'public/js/admin/*.js', 'public/js/public/*.js'], ['version']);
});

// What tasks does running gulp trigger?
gulp.task('all', [
    'less-public',
    'less-admin',
    'js-public',
    'js-admin',
    'fonts',
    'angular-locales',
    'fancybox-img',
    'ckeditor',
    'watch'
]);

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