<commit_before>'use strict';

const gulp = require( 'gulp' );
const postcss = require( 'gulp-postcss' );
const sourcemaps = require( 'gulp-sourcemaps' );
// Use terser minifier with gulp-uglify for ES2015 support.
const composer   = require( 'gulp-uglify/composer' );
const terser     = require( 'terser' );
const minify     = composer( terser, console );
const zip = require( 'gulp-zip' );

const paths = {
  styles: {
    src: [ 'assets/styles/*.css', '!assets/styles/variables.css' ],
    dest: 'assets/styles/build/',
    watch: [ 'assets/styles/**/*.css', '!assets/styles/build/**' ]
  },
  scripts: {
    src: 'assets/scripts/*.js',
    dest: 'assets/scripts/build/',
    watch: [ 'assets/scripts/**/*.css', '!assets/scripts/build/**' ]
  }
};

function styles() {
  const processors = [
    require( 'postcss-import' ),
    require( 'postcss-nested' ),
    require( 'postcss-custom-properties' ),
    require( 'postcss-normalize' )( { forceImport: true } ),
    require( 'css-mqpacker' )( { sort: true } ),
    require( 'autoprefixer' ),
    require( 'cssnano' )( {
      preset: [
        'default',
        {
          calc: false,
          mergeLonghand: false // These conflict with processing nested calc() and env values().
        }
      ]
    } )
  ];
  return gulp
    .src( paths.styles.src )
    .pipe( sourcemaps.init() )
    .pipe( postcss( processors ) )
    .pipe( sourcemaps.write( './' ) )
    .pipe( gulp.dest( paths.styles.dest ) );
}

function scripts() {
	return gulp.src( paths.scripts.src )
		.pipe( sourcemaps.init() )
			.pipe( minify() )
		.pipe( sourcemaps.write( './' ) )
		.pipe( gulp.dest( paths.scripts.dest ) );
}

function watch() {
  gulp.watch( paths.styles.watch, styles );
  gulp.watch( paths.scripts.src, scripts );
}

function bundle() {
  return gulp
    .src(
      [
        './*',
        './assets/**',
        './locales/**',
        './partials/**',
        '!./node_modules',
        '!./distribution'
      ],
      { base: '.' }
    )
    .pipe( zip( 'decode.zip' ) )
    .pipe( gulp.dest( './distribution' ) );
}

// Workflows
// $ gulp: Builds, prefixes, and minifies CSS files; concencates and minifies JS files; watches for changes. The works.
const defaultTask = gulp.parallel( styles, scripts, watch );

// $ gulp build: Builds, prefixes, and minifies CSS files; concencates and minifies JS files. For deployments.
const buildTask = gulp.parallel( styles, scripts );

// $ gulp bundle: Builds and bundles theme into a ZIP for simple theme install.
const bundleTask = gulp.parallel( buildTask, bundle );

// Exports
// Externalise individual tasks.
exports.styles = styles;
exports.scripts = scripts;
exports.watch = watch;

// Externalise Workflows.
exports.build = buildTask;
exports.default = defaultTask;
exports.bundle = bundleTask;
<commit_msg>do not bundle invisible files<commit_after>'use strict';

const gulp = require( 'gulp' );
const postcss = require( 'gulp-postcss' );
const sourcemaps = require( 'gulp-sourcemaps' );
// Use terser minifier with gulp-uglify for ES2015 support.
const composer   = require( 'gulp-uglify/composer' );
const terser     = require( 'terser' );
const minify     = composer( terser, console );
const zip = require( 'gulp-zip' );

const paths = {
  styles: {
    src: [ 'assets/styles/*.css', '!assets/styles/variables.css' ],
    dest: 'assets/styles/build/',
    watch: [ 'assets/styles/**/*.css', '!assets/styles/build/**' ]
  },
  scripts: {
    src: 'assets/scripts/*.js',
    dest: 'assets/scripts/build/',
    watch: [ 'assets/scripts/**/*.css', '!assets/scripts/build/**' ]
  }
};

function styles() {
  const processors = [
    require( 'postcss-import' ),
    require( 'postcss-nested' ),
    require( 'postcss-custom-properties' ),
    require( 'postcss-normalize' )( { forceImport: true } ),
    require( 'css-mqpacker' )( { sort: true } ),
    require( 'autoprefixer' ),
    require( 'cssnano' )( {
      preset: [
        'default',
        {
          calc: false,
          mergeLonghand: false // These conflict with processing nested calc() and env values().
        }
      ]
    } )
  ];
  return gulp
    .src( paths.styles.src )
    .pipe( sourcemaps.init() )
    .pipe( postcss( processors ) )
    .pipe( sourcemaps.write( './' ) )
    .pipe( gulp.dest( paths.styles.dest ) );
}

function scripts() {
	return gulp.src( paths.scripts.src )
		.pipe( sourcemaps.init() )
			.pipe( minify() )
		.pipe( sourcemaps.write( './' ) )
		.pipe( gulp.dest( paths.scripts.dest ) );
}

function watch() {
  gulp.watch( paths.styles.watch, styles );
  gulp.watch( paths.scripts.src, scripts );
}

function bundle() {
  return gulp
    .src(
      [
        './*',
        './assets/**',
        './locales/**',
        './partials/**',
        '!./.*',
        '!./node_modules',
        '!./distribution'
      ],
      { base: '.' }
    )
    .pipe( zip( 'decode.zip' ) )
    .pipe( gulp.dest( './distribution' ) );
}

// Workflows
// $ gulp: Builds, prefixes, and minifies CSS files; concencates and minifies JS files; watches for changes. The works.
const defaultTask = gulp.parallel( styles, scripts, watch );

// $ gulp build: Builds, prefixes, and minifies CSS files; concencates and minifies JS files. For deployments.
const buildTask = gulp.parallel( styles, scripts );

// $ gulp bundle: Builds and bundles theme into a ZIP for simple theme install.
const bundleTask = gulp.parallel( buildTask, bundle );

// Exports
// Externalise individual tasks.
exports.styles = styles;
exports.scripts = scripts;
exports.watch = watch;

// Externalise Workflows.
exports.build = buildTask;
exports.default = defaultTask;
exports.bundle = bundleTask;
<|endoftext|>


<commit_before>const gulp = require('gulp')
const uglify = require('gulp-uglify')
const del = require('del')
const sass = require('gulp-sass')
const filelog = require('gulp-filelog')
const include = require('gulp-include')
const colours = require('colors/safe')
const path = require('path')

// Paths
let environment
const repoRoot = path.join(__dirname)
const npmRoot = path.join(repoRoot, 'node_modules')
const govukCountryPickerDist = path.join(npmRoot, 'govuk-country-and-territory-autocomplete', 'dist')
const govukToolkitRoot = path.join(npmRoot, 'govuk_frontend_toolkit')
const govukElementsRoot = path.join(npmRoot, 'govuk-elements-sass')
const govukFrontendRoot = path.join(npmRoot, 'govuk-frontend')
const dmToolkitRoot = path.join(npmRoot, 'digitalmarketplace-frontend-toolkit', 'toolkit')
const sspContentRoot = path.join(npmRoot, 'digitalmarketplace-frameworks')
const assetsFolder = path.join(repoRoot, 'app', 'assets')
const staticFolder = path.join(repoRoot, 'app', 'static')
const govukFrontendFontsFolder = path.join(govukFrontendRoot, 'assets', 'fonts')
const govukFrontendImageFolder = path.join(govukFrontendRoot, 'assets', 'images')

// JavaScript paths
const jsSourceFile = path.join(assetsFolder, 'javascripts', 'application.js')
const jsPageSpecific = path.join(assetsFolder, 'javascripts', 'page_specific')
const jsDistributionFolder = path.join(staticFolder, 'javascripts')
const jsDistributionFile = 'application.js'

// CSS paths
const cssSourceGlob = path.join(assetsFolder, 'scss', 'application*.scss')
const cssDistributionFolder = path.join(staticFolder, 'stylesheets')

// Configuration
const sassOptions = {
  development: {
    outputStyle: 'expanded',
    lineNumbers: true,
    includePaths: [
      path.join(assetsFolder, 'scss'),
      path.join(dmToolkitRoot, 'scss'),
      path.join(govukToolkitRoot, 'stylesheets'),
      path.join(govukElementsRoot, 'public', 'sass')
    ],
    sourceComments: true,
    errLogToConsole: true
  },
  production: {
    outputStyle: 'compressed',
    lineNumbers: true,
    includePaths: [
      path.join(assetsFolder, 'scss'),
      path.join(dmToolkitRoot, 'scss'),
      path.join(govukToolkitRoot, 'stylesheets'),
      path.join(govukElementsRoot, 'public', 'sass')
    ]
  }
}

const uglifyOptions = {
  development: {
    mangle: false,
    output: {
      beautify: true,
      semicolons: true,
      comments: true,
      indent_level: 2
    },
    compress: false
  },
  production: {
    mangle: true
  }
}

const logErrorAndExit = function logErrorAndExit (err) {
  const printError = function (type, message) {
    console.log('gulp ' + colours.red('ERR! ') + type + ': ' + message)
  }

  printError('message', err.message)
  printError('file name', err.fileName)
  printError('line number', err.lineNumber)
  process.exit(1)
}

gulp.task('clean:js', function () {
  return del(jsDistributionFolder + '/**/*').then(function (paths) {
    console.log('💥  Deleted the following JavaScript files:\n', paths.join('\n'))
  })
})

gulp.task('clean:css', function () {
  return del(cssDistributionFolder + '/**/*').then(function (paths) {
    console.log('💥  Deleted the following CSS files:\n', paths.join('\n'))
  })
})

gulp.task('clean', gulp.parallel('clean:js', 'clean:css'))

gulp.task('sass', function () {
  const stream = gulp.src(cssSourceGlob)
    .pipe(filelog('Compressing SCSS files'))
    .pipe(
      sass(sassOptions[environment]))
    .on('error', logErrorAndExit)
    .pipe(gulp.dest(cssDistributionFolder))

  stream.on('end', function () {
    console.log('💾  Compressed CSS saved as .css files in ' + cssDistributionFolder)
  })

  return stream
})

gulp.task('js', function () {
  const stream = gulp.src(jsSourceFile)
    .pipe(filelog('Compressing JavaScript files'))
    .pipe(include({ hardFail: true }))
    .pipe(uglify(
      uglifyOptions[environment]
    ))
    .pipe(gulp.dest(jsDistributionFolder))

  stream.on('end', function () {
    console.log('💾 Compressed JavaScript saved as ' + jsDistributionFolder + '/' + jsDistributionFile)
  })

  return stream
})

function copyFactory (resourceName, sourceFolder, targetFolder) {
  return function () {
    return gulp
      .src(sourceFolder + '/**/*', { base: sourceFolder })
      .pipe(gulp.dest(targetFolder))
      .on('end', function () {
        console.log('📂  Copied ' + resourceName)
      })
  }
}

function copyFiletypeFactory (resourceName, sourceFolder, sourceFileExtension, targetFolder) {
  return function () {
    return gulp
      .src(sourceFolder + '/**/*.' + sourceFileExtension, { base: sourceFolder })
      .pipe(gulp.dest(targetFolder))
      .on('end', function () {
        console.log('📂  Copied ' + resourceName)
      })
  }
}

gulp.task(
  'copy:dm_toolkit_assets:stylesheets',
  copyFactory(
    'stylesheets from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/scss',
    'app/assets/scss/toolkit'
  )
)

gulp.task(
  'copy:dm_toolkit_assets:images',
  copyFactory(
    'images from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:govuk_toolkit_assets:images',
  copyFactory(
    'images from the GOVUK frontend toolkit',
    govukToolkitRoot + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:dm_toolkit_assets:templates',
  copyFactory(
    'templates from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/templates',
    'app/templates/toolkit'
  )
)

gulp.task(
  'copy:images',
  copyFactory(
    'image assets from app to static folder',
    assetsFolder + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:frameworks',
  copyFactory(
    'frameworks YAML into app folder',
    sspContentRoot + '/frameworks', 'app/content/frameworks'
  )
)

gulp.task(
  'copy:country_picker:jsons',
  copyFiletypeFactory(
    'country picker jsons to static folder',
    govukCountryPickerDist,
    'json',
    staticFolder
  )
)

gulp.task(
  'copy:country_picker:stylesheets',
  copyFiletypeFactory(
    'country picker stylesheets to static folder',
    govukCountryPickerDist,
    'css',
    cssDistributionFolder
  )
)

gulp.task(
  'copy:country_picker_package:javascripts',
  copyFiletypeFactory(
    'country picker package javascripts to static folder',
    govukCountryPickerDist,
    '{js,js.map}',
    jsDistributionFolder
  )
)

gulp.task(
  'copy:page_specific:javascripts',
  copyFactory(
    'page specific javascript to static folder',
    jsPageSpecific,
    jsDistributionFolder
  )
)

gulp.task(
  'copy:govuk_frontend_assets:fonts',
  copyFactory(
    'fonts from the GOVUK frontend assets',
    govukFrontendFontsFolder,
    staticFolder + '/fonts'
  )
)

gulp.task(
  'copy:govuk_frontend_assets:images',
  copyFactory(
    'images from the GOVUK frontend',
    govukFrontendImageFolder,
    path.join(staticFolder, 'images')
  )
)

gulp.task(
  'copy:govuk_frontend_assets:stylesheets',
  copyFiletypeFactory(
    'stylesheets from GOV.UK Frontend',
    govukFrontendRoot,
    'scss',
    path.join('app', 'assets', 'scss', 'govuk'),
  )
)

gulp.task('set_environment_to_development', function (cb) {
  environment = 'development'
  cb()
})

gulp.task('set_environment_to_production', function (cb) {
  environment = 'production'
  cb()
})

gulp.task(
  'copy',
  gulp.parallel(
    'copy:frameworks',
    'copy:govuk_toolkit_assets:images',
    'copy:dm_toolkit_assets:stylesheets',
    'copy:dm_toolkit_assets:images',
    'copy:dm_toolkit_assets:templates',
    'copy:images',
    'copy:govuk_frontend_assets:fonts',
    'copy:govuk_frontend_assets:images',
    'copy:govuk_frontend_assets:stylesheets',
    'copy:country_picker:jsons',
    'copy:country_picker:stylesheets',
    'copy:country_picker_package:javascripts',
    'copy:page_specific:javascripts'
  )
)

gulp.task('compile', gulp.series('copy', gulp.parallel('sass', 'js')))

gulp.task('build:development', gulp.series(gulp.parallel('set_environment_to_development', 'clean'), 'compile'))

gulp.task('build:production', gulp.series(gulp.parallel('set_environment_to_production', 'clean'), 'compile'))

gulp.task('watch', gulp.series('build:development', function () {
  const jsWatcher = gulp.watch([assetsFolder + '/**/*.js'], gulp.series('js'))
  const cssWatcher = gulp.watch([assetsFolder + '/**/*.scss'], gulp.series('sass'))
  const dmWatcher = gulp.watch([npmRoot + '/digitalmarketplace-frameworks/**'], gulp.series('copy:frameworks'))
  const notice = function (event) {
    console.log('File ' + event.path + ' was ' + event.type + ' running tasks...')
  }

  cssWatcher.on('change', notice)
  jsWatcher.on('change', notice)
  dmWatcher.on('change', notice)
}))
<commit_msg>Fix linter warning<commit_after>const gulp = require('gulp')
const uglify = require('gulp-uglify')
const del = require('del')
const sass = require('gulp-sass')
const filelog = require('gulp-filelog')
const include = require('gulp-include')
const colours = require('colors/safe')
const path = require('path')

// Paths
let environment
const repoRoot = path.join(__dirname)
const npmRoot = path.join(repoRoot, 'node_modules')
const govukCountryPickerDist = path.join(npmRoot, 'govuk-country-and-territory-autocomplete', 'dist')
const govukToolkitRoot = path.join(npmRoot, 'govuk_frontend_toolkit')
const govukElementsRoot = path.join(npmRoot, 'govuk-elements-sass')
const govukFrontendRoot = path.join(npmRoot, 'govuk-frontend')
const dmToolkitRoot = path.join(npmRoot, 'digitalmarketplace-frontend-toolkit', 'toolkit')
const sspContentRoot = path.join(npmRoot, 'digitalmarketplace-frameworks')
const assetsFolder = path.join(repoRoot, 'app', 'assets')
const staticFolder = path.join(repoRoot, 'app', 'static')
const govukFrontendFontsFolder = path.join(govukFrontendRoot, 'assets', 'fonts')
const govukFrontendImageFolder = path.join(govukFrontendRoot, 'assets', 'images')

// JavaScript paths
const jsSourceFile = path.join(assetsFolder, 'javascripts', 'application.js')
const jsPageSpecific = path.join(assetsFolder, 'javascripts', 'page_specific')
const jsDistributionFolder = path.join(staticFolder, 'javascripts')
const jsDistributionFile = 'application.js'

// CSS paths
const cssSourceGlob = path.join(assetsFolder, 'scss', 'application*.scss')
const cssDistributionFolder = path.join(staticFolder, 'stylesheets')

// Configuration
const sassOptions = {
  development: {
    outputStyle: 'expanded',
    lineNumbers: true,
    includePaths: [
      path.join(assetsFolder, 'scss'),
      path.join(dmToolkitRoot, 'scss'),
      path.join(govukToolkitRoot, 'stylesheets'),
      path.join(govukElementsRoot, 'public', 'sass')
    ],
    sourceComments: true,
    errLogToConsole: true
  },
  production: {
    outputStyle: 'compressed',
    lineNumbers: true,
    includePaths: [
      path.join(assetsFolder, 'scss'),
      path.join(dmToolkitRoot, 'scss'),
      path.join(govukToolkitRoot, 'stylesheets'),
      path.join(govukElementsRoot, 'public', 'sass')
    ]
  }
}

const uglifyOptions = {
  development: {
    mangle: false,
    output: {
      beautify: true,
      semicolons: true,
      comments: true,
      indent_level: 2
    },
    compress: false
  },
  production: {
    mangle: true
  }
}

const logErrorAndExit = function logErrorAndExit (err) {
  const printError = function (type, message) {
    console.log('gulp ' + colours.red('ERR! ') + type + ': ' + message)
  }

  printError('message', err.message)
  printError('file name', err.fileName)
  printError('line number', err.lineNumber)
  process.exit(1)
}

gulp.task('clean:js', function () {
  return del(jsDistributionFolder + '/**/*').then(function (paths) {
    console.log('💥  Deleted the following JavaScript files:\n', paths.join('\n'))
  })
})

gulp.task('clean:css', function () {
  return del(cssDistributionFolder + '/**/*').then(function (paths) {
    console.log('💥  Deleted the following CSS files:\n', paths.join('\n'))
  })
})

gulp.task('clean', gulp.parallel('clean:js', 'clean:css'))

gulp.task('sass', function () {
  const stream = gulp.src(cssSourceGlob)
    .pipe(filelog('Compressing SCSS files'))
    .pipe(
      sass(sassOptions[environment]))
    .on('error', logErrorAndExit)
    .pipe(gulp.dest(cssDistributionFolder))

  stream.on('end', function () {
    console.log('💾  Compressed CSS saved as .css files in ' + cssDistributionFolder)
  })

  return stream
})

gulp.task('js', function () {
  const stream = gulp.src(jsSourceFile)
    .pipe(filelog('Compressing JavaScript files'))
    .pipe(include({ hardFail: true }))
    .pipe(uglify(
      uglifyOptions[environment]
    ))
    .pipe(gulp.dest(jsDistributionFolder))

  stream.on('end', function () {
    console.log('💾 Compressed JavaScript saved as ' + jsDistributionFolder + '/' + jsDistributionFile)
  })

  return stream
})

function copyFactory (resourceName, sourceFolder, targetFolder) {
  return function () {
    return gulp
      .src(sourceFolder + '/**/*', { base: sourceFolder })
      .pipe(gulp.dest(targetFolder))
      .on('end', function () {
        console.log('📂  Copied ' + resourceName)
      })
  }
}

function copyFiletypeFactory (resourceName, sourceFolder, sourceFileExtension, targetFolder) {
  return function () {
    return gulp
      .src(sourceFolder + '/**/*.' + sourceFileExtension, { base: sourceFolder })
      .pipe(gulp.dest(targetFolder))
      .on('end', function () {
        console.log('📂  Copied ' + resourceName)
      })
  }
}

gulp.task(
  'copy:dm_toolkit_assets:stylesheets',
  copyFactory(
    'stylesheets from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/scss',
    'app/assets/scss/toolkit'
  )
)

gulp.task(
  'copy:dm_toolkit_assets:images',
  copyFactory(
    'images from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:govuk_toolkit_assets:images',
  copyFactory(
    'images from the GOVUK frontend toolkit',
    govukToolkitRoot + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:dm_toolkit_assets:templates',
  copyFactory(
    'templates from the Digital Marketplace frontend toolkit',
    dmToolkitRoot + '/templates',
    'app/templates/toolkit'
  )
)

gulp.task(
  'copy:images',
  copyFactory(
    'image assets from app to static folder',
    assetsFolder + '/images',
    staticFolder + '/images'
  )
)

gulp.task(
  'copy:frameworks',
  copyFactory(
    'frameworks YAML into app folder',
    sspContentRoot + '/frameworks', 'app/content/frameworks'
  )
)

gulp.task(
  'copy:country_picker:jsons',
  copyFiletypeFactory(
    'country picker jsons to static folder',
    govukCountryPickerDist,
    'json',
    staticFolder
  )
)

gulp.task(
  'copy:country_picker:stylesheets',
  copyFiletypeFactory(
    'country picker stylesheets to static folder',
    govukCountryPickerDist,
    'css',
    cssDistributionFolder
  )
)

gulp.task(
  'copy:country_picker_package:javascripts',
  copyFiletypeFactory(
    'country picker package javascripts to static folder',
    govukCountryPickerDist,
    '{js,js.map}',
    jsDistributionFolder
  )
)

gulp.task(
  'copy:page_specific:javascripts',
  copyFactory(
    'page specific javascript to static folder',
    jsPageSpecific,
    jsDistributionFolder
  )
)

gulp.task(
  'copy:govuk_frontend_assets:fonts',
  copyFactory(
    'fonts from the GOVUK frontend assets',
    govukFrontendFontsFolder,
    staticFolder + '/fonts'
  )
)

gulp.task(
  'copy:govuk_frontend_assets:images',
  copyFactory(
    'images from the GOVUK frontend',
    govukFrontendImageFolder,
    path.join(staticFolder, 'images')
  )
)

gulp.task(
  'copy:govuk_frontend_assets:stylesheets',
  copyFiletypeFactory(
    'stylesheets from GOV.UK Frontend',
    govukFrontendRoot,
    'scss',
    path.join('app', 'assets', 'scss', 'govuk')
  )
)

gulp.task('set_environment_to_development', function (cb) {
  environment = 'development'
  cb()
})

gulp.task('set_environment_to_production', function (cb) {
  environment = 'production'
  cb()
})

gulp.task(
  'copy',
  gulp.parallel(
    'copy:frameworks',
    'copy:govuk_toolkit_assets:images',
    'copy:dm_toolkit_assets:stylesheets',
    'copy:dm_toolkit_assets:images',
    'copy:dm_toolkit_assets:templates',
    'copy:images',
    'copy:govuk_frontend_assets:fonts',
    'copy:govuk_frontend_assets:images',
    'copy:govuk_frontend_assets:stylesheets',
    'copy:country_picker:jsons',
    'copy:country_picker:stylesheets',
    'copy:country_picker_package:javascripts',
    'copy:page_specific:javascripts'
  )
)

gulp.task('compile', gulp.series('copy', gulp.parallel('sass', 'js')))

gulp.task('build:development', gulp.series(gulp.parallel('set_environment_to_development', 'clean'), 'compile'))

gulp.task('build:production', gulp.series(gulp.parallel('set_environment_to_production', 'clean'), 'compile'))

gulp.task('watch', gulp.series('build:development', function () {
  const jsWatcher = gulp.watch([assetsFolder + '/**/*.js'], gulp.series('js'))
  const cssWatcher = gulp.watch([assetsFolder + '/**/*.scss'], gulp.series('sass'))
  const dmWatcher = gulp.watch([npmRoot + '/digitalmarketplace-frameworks/**'], gulp.series('copy:frameworks'))
  const notice = function (event) {
    console.log('File ' + event.path + ' was ' + event.type + ' running tasks...')
  }

  cssWatcher.on('change', notice)
  jsWatcher.on('change', notice)
  dmWatcher.on('change', notice)
}))
<|endoftext|>


<commit_before>var gulp     = require('gulp'),
	chmod    = require('gulp-chmod'),
	util     = require('gulp-util'),
	plugins  = require('gulp-load-plugins')(),
	sequence = require('run-sequence'),
	del      = require('del'),
	files    = {},
	config   = {},
	jshintConfig, package, config, patterns = [], key;

module.exports = gulp;

/**************************************************
 * helper
 **************************************************/
	function handleError (error) {
		util.log(error);
	}

	function loadPackageFile() {
		delete require.cache[require.resolve('./package.json')];

		package      = require('./package.json');
		jshintConfig = package.jshintConfig;
	}

	function loadConfigFile() {
		delete require.cache[require.resolve('./gulp/config.json')];

		config = replacePatterns(require('./gulp/config.json'));
	}

	function preparePatterns(node, prefix) {
		var key, id, item;

		node = node || package;

		for(key in node) {
			id   = (prefix) ? prefix + '.' + key : 'package.' + key;
			item = node[key];

			if(typeof item === 'string') {
				patterns.push({ pattern: new RegExp('{{gulp:' + id + '}}', 'g'), replacement: item });
			} else if(Object.prototype.toString.call(item) === '[object Object]') {
				preparePatterns(item, id);
			}
		}
	}

	function replacePatterns(value) {
		var i = 0, entry;

		value = JSON.stringify(value);

		for(; (entry = patterns[i]) !== undefined; i++) {
			value = value.replace(entry.pattern, entry.replacement);
		}

		return JSON.parse(value);
	}

	function getDatePatterns() {
		var date  = new Date(),
			month = ''.concat('0', (date.getMonth() + 1).toString()).slice(-2),
			day   = ''.concat('0', date.getDate().toString()).slice(-2),
			time  = ''.concat('0', date.getHours().toString()).slice(-2) + ':' + ''.concat('0', date.getMinutes().toString()).slice(-2) + ':' + ''.concat('0', date.getSeconds().toString()).slice(-2);

		return [
			{ pattern: new RegExp('{{gulp:date.year}}', 'g'), replacement: date.getFullYear() },
			{ pattern: new RegExp('{{gulp:date.month}}', 'g'), replacement: month },
			{ pattern: new RegExp('{{gulp:date.day}}', 'g'), replacement: day },
			{ pattern: new RegExp('{{gulp:date.time}}', 'g'), replacement: time }
		];
	}

/**************************************************
 * initialization
 **************************************************/
	loadPackageFile();
	preparePatterns();
	loadConfigFile();

/**************************************************
 * tasks (private)
 **************************************************/
	gulp.task('bump', function(callback) {
		var tasks = [ 'dist' ];

		loadPackageFile();
		preparePatterns();
		loadConfigFile();

		tasks.push(callback);

		return sequence.apply(null, tasks);
	});

	gulp.task('dist:lint', function() {
		return gulp.src(config.tasks.dist.lint || config.tasks.dist.watch)
			.pipe(plugins.jshint(jshintConfig))
			.pipe(plugins.jshint.reporter('jshint-stylish'));
	});

	gulp.task('dist:clean', function(callback) {
		return del(config.tasks.dist.clean || [ config.tasks.dist.destination + '**/*' ], callback);
	});

	gulp.task('dist:build', function() {
		return gulp.src(config.tasks.dist.build || config.tasks.dist.watch)
			.pipe(plugins.plumber({ errorHandler: handleError}))
			// max
			.pipe(plugins.uglify({ compress: false, mangle: false, preserveComments: 'none', output: { beautify: true } }))
			.pipe(plugins.header(config.strings.banner.max.join('\n')))
			.pipe(plugins.frep(patterns))
			.pipe(plugins.frep(getDatePatterns()))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/' + package.version + '/max/'))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/latest/max/'))
			// min
			.pipe(plugins.uglify({ preserveComments: 'none' }))
			.pipe(plugins.header(config.strings.banner.min.join('\n')))
			.pipe(plugins.frep(patterns))
			.pipe(plugins.frep(getDatePatterns()))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/' + package.version + '/min/'))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/latest/min/'));
	});

	gulp.task('dist', function(callback) {
		return sequence('dist:lint', 'dist:clean', 'dist:build', callback);
	});

/**************************************************
 * tasks (public)
 **************************************************/
	gulp.task('bump:patch', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'patch' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('bump:minor', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'minor' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('bump:major', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'major' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('all', [ 'bump' ]);

	gulp.task('watch', function() {
		gulp.watch(config.tasks.bump.watch, [ 'bump' ]);
		gulp.watch(config.tasks.dist.watch, [ 'dist' ]);
	});

	gulp.task('default', [ 'watch' ]);
<commit_msg>[UPDATE] gulpfile.js<commit_after>var gulp     = require('gulp'),
	chmod    = require('gulp-chmod'),
	util     = require('gulp-util'),
	plugins  = require('gulp-load-plugins')(),
	sequence = require('run-sequence'),
	del      = require('del'),
	config   = {},
	jshintConfig, package, config, patterns = [], key;

module.exports = gulp;

/**************************************************
 * helper
 **************************************************/
	function handleError (error) {
		util.log(error);
	}

	function loadPackageFile() {
		delete require.cache[require.resolve('./package.json')];

		package      = require('./package.json');
		jshintConfig = package.jshintConfig;
	}

	function loadConfigFile() {
		delete require.cache[require.resolve('./gulp/config.json')];

		config = replacePatterns(require('./gulp/config.json'));
	}

	function preparePatterns(node, prefix) {
		var key, id, item;

		node = node || package;

		for(key in node) {
			id   = (prefix) ? prefix + '.' + key : 'package.' + key;
			item = node[key];

			if(typeof item === 'string') {
				patterns.push({ pattern: new RegExp('{{gulp:' + id + '}}', 'g'), replacement: item });
			} else if(Object.prototype.toString.call(item) === '[object Object]') {
				preparePatterns(item, id);
			}
		}
	}

	function replacePatterns(value) {
		var i = 0, entry;

		value = JSON.stringify(value);

		for(; (entry = patterns[i]) !== undefined; i++) {
			value = value.replace(entry.pattern, entry.replacement);
		}

		return JSON.parse(value);
	}

	function getDatePatterns() {
		var date  = new Date(),
			month = ''.concat('0', (date.getMonth() + 1).toString()).slice(-2),
			day   = ''.concat('0', date.getDate().toString()).slice(-2),
			time  = ''.concat('0', date.getHours().toString()).slice(-2) + ':' + ''.concat('0', date.getMinutes().toString()).slice(-2) + ':' + ''.concat('0', date.getSeconds().toString()).slice(-2);

		return [
			{ pattern: new RegExp('{{gulp:date.year}}', 'g'), replacement: date.getFullYear() },
			{ pattern: new RegExp('{{gulp:date.month}}', 'g'), replacement: month },
			{ pattern: new RegExp('{{gulp:date.day}}', 'g'), replacement: day },
			{ pattern: new RegExp('{{gulp:date.time}}', 'g'), replacement: time }
		];
	}

/**************************************************
 * initialization
 **************************************************/
	loadPackageFile();
	preparePatterns();
	loadConfigFile();

/**************************************************
 * tasks (private)
 **************************************************/
	gulp.task('bump', function(callback) {
		var tasks = [ 'dist' ];

		loadPackageFile();
		preparePatterns();
		loadConfigFile();

		tasks.push(callback);

		return sequence.apply(null, tasks);
	});

	gulp.task('dist:lint', function() {
		return gulp.src(config.tasks.dist.lint || config.tasks.dist.watch)
			.pipe(plugins.jshint(jshintConfig))
			.pipe(plugins.jshint.reporter('jshint-stylish'));
	});

	gulp.task('dist:clean', function(callback) {
		return del(config.tasks.dist.clean || [ config.tasks.dist.destination + '**/*' ], callback);
	});

	gulp.task('dist:build', function() {
		return gulp.src(config.tasks.dist.build || config.tasks.dist.watch)
			.pipe(plugins.plumber({ errorHandler: handleError}))
			// max
			.pipe(plugins.uglify({ compress: false, mangle: false, preserveComments: 'none', output: { beautify: true } }))
			.pipe(plugins.header(config.strings.banner.max.join('\n')))
			.pipe(plugins.frep(patterns))
			.pipe(plugins.frep(getDatePatterns()))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/' + package.version + '/max/'))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/latest/max/'))
			// min
			.pipe(plugins.uglify({ preserveComments: 'none' }))
			.pipe(plugins.header(config.strings.banner.min.join('\n')))
			.pipe(plugins.frep(patterns))
			.pipe(plugins.frep(getDatePatterns()))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/' + package.version + '/min/'))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.dist.destination + '/latest/min/'));
	});

	gulp.task('dist', function(callback) {
		return sequence('dist:lint', 'dist:clean', 'dist:build', callback);
	});

/**************************************************
 * tasks (public)
 **************************************************/
	gulp.task('bump:patch', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'patch' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('bump:minor', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'minor' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('bump:major', function() {
		return gulp.src(config.tasks.bump.watch)
			.pipe(plugins.bump({ type: 'major' }))
			.pipe(chmod(644))
			.pipe(gulp.dest(config.tasks.bump.destination));
	});

	gulp.task('all', [ 'bump' ]);

	gulp.task('watch', function() {
		gulp.watch(config.tasks.bump.watch, [ 'bump' ]);
		gulp.watch(config.tasks.dist.watch, [ 'dist' ]);
	});

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


<commit_before>var gulp = require('gulp');
var clean = require('gulp-clean');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var cssBase64 = require('gulp-css-base64');
var es = require('event-stream');
var rseq = require('gulp-run-sequence');
var zip = require('gulp-zip');
var rename = require('gulp-rename');
var shell = require('gulp-shell');
var jeditor = require("gulp-json-editor");
var peditor = require('gulp-plist');
var app = require('./package');

function pipe(src, transforms, dest) {
  if (typeof transforms === 'string') {
    dest = transforms;
    transforms = null;
  }

  var stream = gulp.src(src);
  transforms && transforms.forEach(function (transform) {
    stream = stream.pipe(transform);
  });

  if (dest) {
    stream = stream.pipe(gulp.dest(dest));
  }

  return stream;
}

gulp.task('styles', function () {
  return gulp.src('./src/less/style.less')
      .pipe(less())
      .pipe(cssBase64())
      .pipe(minifyCSS())
      .pipe(gulp.dest('./src/css'));
});

gulp.task('options', function () {
  return gulp.src('./src/less/options.less')
      .pipe(less())
      .pipe(cssBase64())
      .pipe(minifyCSS())
      .pipe(gulp.dest('./src/css'));
});

gulp.task('clean', function () {
  return pipe('./build', [clean()]);
});

gulp.task('chrome', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/chrome/js'),
      pipe('./src/css/**/*', './build/chrome/css'),
      pipe('./src/icons/**/*', './build/chrome/icons'),
      pipe('./vendor/chrome/data/**/*', './build/chrome'),
      pipe('./vendor/chrome/manifest.json', [
        jeditor({
          'name': app.title,
          'version': app.version,
          'description': app.description,
          'homepage_url': app.homepage
        })
      ], './build/chrome/')
  );
});

gulp.task('opera', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/opera/js'),
      pipe('./src/css/**/*', './build/opera/css'),
      pipe('./src/icons/**/*', './build/opera/icons'),
      pipe('./vendor/opera/data/**/*', './build/opera'),
      pipe('./vendor/opera/manifest.json', [
        jeditor({
          'name': app.title,
          'version': app.version,
          'description': app.description,
          'homepage_url': app.homepage
        })
      ], './build/opera/')
  );
});

gulp.task('firefox', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/firefox/data/js'),
      pipe(['./src/css/**/*', '!./src/css/options.css'], './build/firefox/data/css'),
      pipe('./src/icons/**/*', './build/firefox/data/icons'),
      pipe('./vendor/firefox/data/**/*', './build/firefox/data'),
      pipe('./vendor/firefox/package.json', [
        jeditor({
          'title': app.title,
          'version': app.version,
          'description': app.description,
          'homepage': app.homepage
        })
      ], './build/firefox/')
  );
});

gulp.task('safari', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/safari/handsometrello.safariextension/js'),
      pipe(['./src/css/**/*', '!./src/css/options.css'], './build/safari/handsometrello.safariextension/css'),
      pipe('./src/icons/**/*', './build/safari/handsometrello.safariextension/icons'),
      pipe('./vendor/safari/data/**/*', './build/safari/handsometrello.safariextension'),
      pipe('./vendor/safari/Info.plist', [
        peditor({
          CFBundleDisplayName: app.title,
          CFBundleShortVersionString: app.version,
          Description: app.description,
          Website: app.homepage
        })
      ], './build/safari/handsometrello.safariextension')
  );
});

gulp.task('chrome-dist', function () {
  gulp.src('./build/chrome/**/*')
      .pipe(zip('handsome-trello-chrome-extension-' + app.version + '.zip'))
      .pipe(gulp.dest('./dist/chrome'))
      .pipe(rename('handsome-trello-chrome-extension-latest.zip'))
      .pipe(gulp.dest('./dist/chrome'));
});

gulp.task('opera-dist', function () {
  gulp.src('./build/opera/**/*')
      .pipe(zip('handsome-trello-opera-extension-' + app.version + '.zip'))
      .pipe(gulp.dest('./dist/opera'))
      .pipe(rename('handsome-trello-opera-extension-latest.zip'))
      .pipe(gulp.dest('./dist/opera'));
});

gulp.task('firefox-dist', shell.task([
  'mkdir -p dist/firefox',
  'cd ./build/firefox && ../../node_modules/.bin/jpm xpi > /dev/null',
  'mv ./build/firefox/*-' + app.version + '.xpi ./dist/firefox/handsome-trello-firefox-extension-' + app.version + '.xpi',
  'cp ./dist/firefox/handsome-trello-firefox-extension-' + app.version + '.xpi ./dist/firefox/handsome-trello-firefox-extension-latest.xpi'
]));

gulp.task('safari-dist', shell.task([
  'mkdir -p dist/safari',
  'cd ./build/safari && ../../node_modules/.bin/xarjs create extension.safariextz --cert ../../vendor/safari/certs/cert.pem --cert ../../vendor/safari/certs/apple-intermediate.pem --cert ../../vendor/safari/certs/apple-root.pem --private-key ../../vendor/safari/certs/privatekey.pem handsometrello.safariextension',
  'mv ./build/safari/extension.safariextz ./dist/safari/handsome-trello-safari-extension-' + app.version + '.safariextz',
  'cp ./dist/safari/handsome-trello-safari-extension-' + app.version + '.safariextz ./dist/safari/handsome-trello-safari-extension-latest.safariextz'
]));

gulp.task('firefox-run', shell.task([
  'cd ./build/firefox && ../../node_modules/.bin/jpm run'
]));

gulp.task('dist', function (cb) {
  return rseq('clean', ['chrome', 'opera', 'firefox', 'safari'], ['chrome-dist', 'opera-dist', 'firefox-dist', 'safari-dist'], cb);
});

gulp.task('watch', function () {
  rseq('default');

  gulp.watch([
    './src/less/**/*',
    './src/fonts/**/*'
  ], ['styles', 'options']);

  gulp.watch([
    './src/js/**/*',
    './src/css/**/*',
    './vendor/**/*',
    './package.json'
  ], ['default']);
});

gulp.task('run', function (cb) {
  return rseq('clean', 'firefox', 'firefox-run', cb);
});

gulp.task('addons', shell.task([
  'cp -R ./dist ../addons'
]));

gulp.task('default', function (cb) {
  return rseq('clean', ['chrome', 'opera', 'firefox', 'safari'], cb);
});
<commit_msg>Fixes and optimizations for gulp<commit_after>var gulp = require('gulp');
var clean = require('gulp-clean');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var cssBase64 = require('gulp-css-base64');
var es = require('event-stream');
var rseq = require('gulp-run-sequence');
var zip = require('gulp-zip');
var rename = require('gulp-rename');
var shell = require('gulp-shell');
var jeditor = require("gulp-json-editor");
var peditor = require('gulp-plist');
var app = require('./package');

function pipe(src, transforms, dest) {
  if (typeof transforms === 'string') {
    dest = transforms;
    transforms = null;
  }

  var stream = gulp.src(src);
  transforms && transforms.forEach(function (transform) {
    stream = stream.pipe(transform);
  });

  if (dest) {
    stream = stream.pipe(gulp.dest(dest));
  }

  return stream;
}

gulp.task('styles', function () {
  return gulp.src('./src/less/style.less')
      .pipe(less())
      .pipe(cssBase64())
      .pipe(minifyCSS())
      .pipe(gulp.dest('./src/css'));
});

gulp.task('options', function () {
  return gulp.src('./src/less/options.less')
      .pipe(less())
      .pipe(cssBase64())
      .pipe(minifyCSS())
      .pipe(gulp.dest('./src/css'));
});

gulp.task('clean', function () {
  return pipe('./build', [clean()]);
});

gulp.task('chrome', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/chrome/js'),
      pipe('./src/css/**/*', './build/chrome/css'),
      pipe('./src/icons/**/*', './build/chrome/icons'),
      pipe('./vendor/chrome/data/**/*', './build/chrome'),
      pipe('./vendor/chrome/manifest.json', [
        jeditor({
          'name': app.title,
          'version': app.version,
          'description': app.description,
          'homepage_url': app.homepage
        })
      ], './build/chrome/')
  );
});

gulp.task('opera', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/opera/js'),
      pipe('./src/css/**/*', './build/opera/css'),
      pipe('./src/icons/**/*', './build/opera/icons'),
      pipe('./vendor/opera/data/**/*', './build/opera'),
      pipe('./vendor/opera/manifest.json', [
        jeditor({
          'name': app.title,
          'version': app.version,
          'description': app.description,
          'homepage_url': app.homepage
        })
      ], './build/opera/')
  );
});

gulp.task('firefox', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/firefox/data/js'),
      pipe(['./src/css/**/*', '!./src/css/options.css'], './build/firefox/data/css'),
      pipe('./src/icons/**/*', './build/firefox/data/icons'),
      pipe('./vendor/firefox/data/**/*', './build/firefox/data'),
      pipe('./vendor/firefox/package.json', [
        jeditor({
          'title': app.title,
          'version': app.version,
          'description': app.description,
          'homepage': app.homepage
        })
      ], './build/firefox/')
  );
});

gulp.task('safari', function () {
  return es.merge(
      pipe('./src/js/**/*', './build/safari/handsometrello.safariextension/js'),
      pipe(['./src/css/**/*', '!./src/css/options.css'], './build/safari/handsometrello.safariextension/css'),
      pipe('./src/icons/**/*', './build/safari/handsometrello.safariextension/icons'),
      pipe('./vendor/safari/data/**/*', './build/safari/handsometrello.safariextension'),
      pipe('./vendor/safari/Info.plist', [
        peditor({
          CFBundleDisplayName: app.title,
          CFBundleShortVersionString: app.version,
          Description: app.description,
          Website: app.homepage
        })
      ], './build/safari/handsometrello.safariextension')
  );
});

gulp.task('chrome-dist', function () {
  gulp.src('./build/chrome/**/*')
      .pipe(zip('handsome-trello-chrome-extension-' + app.version + '.zip'))
      .pipe(gulp.dest('./dist/chrome'))
      .pipe(rename('handsome-trello-chrome-extension-latest.zip'))
      .pipe(gulp.dest('./dist/chrome'));
});

gulp.task('opera-dist', function () {
  gulp.src('./build/opera/**/*')
      .pipe(zip('handsome-trello-opera-extension-' + app.version + '.zip'))
      .pipe(gulp.dest('./dist/opera'))
      .pipe(rename('handsome-trello-opera-extension-latest.zip'))
      .pipe(gulp.dest('./dist/opera'));
});

gulp.task('firefox-dist', shell.task([
  'mkdir -p dist/firefox',
  'cd ./build/firefox && ../../node_modules/.bin/jpm xpi > /dev/null',
  'mv ./build/firefox/*-' + app.version + '.xpi ./dist/firefox/handsome-trello-firefox-extension-' + app.version + '.xpi',
  'cp ./dist/firefox/handsome-trello-firefox-extension-' + app.version + '.xpi ./dist/firefox/handsome-trello-firefox-extension-latest.xpi'
]));

gulp.task('safari-dist', shell.task([
  'mkdir -p dist/safari',
  'cd ./build/safari && ../../node_modules/.bin/xarjs create ../../dist/safari/handsome-trello-safari-extension-' + app.version + '.safariextz --cert ../../vendor/safari/certs/cert.pem --cert ../../vendor/safari/certs/apple-intermediate.pem --cert ../../vendor/safari/certs/apple-root.pem --private-key ../../vendor/safari/certs/privatekey.pem handsometrello.safariextension',
  'cp ./dist/safari/handsome-trello-safari-extension-' + app.version + '.safariextz ./dist/safari/handsome-trello-safari-extension-latest.safariextz'
]));

gulp.task('firefox-run', shell.task([
  'cd ./build/firefox && ../../node_modules/.bin/jpm run'
]));

gulp.task('dist', function (cb) {
  return rseq('clean', ['styles', 'options'], ['chrome', 'opera', 'firefox', 'safari'], ['chrome-dist', 'opera-dist', 'firefox-dist', 'safari-dist'], cb);
});

gulp.task('watch', function () {
  rseq('default');

  gulp.watch([
    './src/less/**/*',
    './src/fonts/**/*'
  ], ['styles', 'options'], ['chrome', 'opera', 'firefox', 'safari']);

  gulp.watch([
    './src/js/**/*',
    './src/css/**/*',
    './vendor/**/*',
    './package.json'
  ], ['default']);
});

gulp.task('run', function (cb) {
  return rseq('clean', ['styles', 'options'], 'firefox', 'firefox-run', cb);
});

gulp.task('addons', shell.task([
  'cp -R ./dist ../addons'
]));

gulp.task('default', function (cb) {
  return rseq('clean', ['styles', 'options'], ['chrome', 'opera', 'firefox', 'safari'], cb);
});
<|endoftext|>


<commit_before>/*
 * biojs-vis-context-data-unique-list
 * https://github.com/BioCIDER/biojs-vis-context-data-unique-list
 *
 * Copyright (c) 2015 Carlos Horro
 * Licensed under the MIT license.
 */

// browserify build config
var buildDir = "build";
var outputFile = "biojsviscontextdatauniquelist";

var imagesDir = "img";

// packages
var gulp   = require('gulp');

// browser builds
var browserify = require('browserify');
var watchify = require('watchify')
var uglify = require('gulp-uglify');

// testing
//var mocha = require('gulp-mocha');

// code style

// gulp helper
var source = require('vinyl-source-stream'); // converts node streams into vinyl streams
var gzip = require('gulp-gzip');
var rename = require('gulp-rename');
var chmod = require('gulp-chmod');
var streamify = require('gulp-streamify'); // converts streams into buffers (legacy support for old plugins)
var watch = require('gulp-watch');

// path tools
var fs = require('fs');
var path = require('path');
var join = path.join;
var mkdirp = require('mkdirp');
var del = require('del');

// auto config
var outputFileMin = join(buildDir,outputFile + ".min.js");
var packageConfig = require('./package.json');

// a failing test breaks the whole build chain
gulp.task('build', ['build-browser', 'build-browser-gzip','copy-images']);
gulp.task('default', [  'build']);

// will remove everything in build
gulp.task('clean', function(cb) {
  del([buildDir+'/img']);
  del([buildDir+'/css']);
  del([buildDir+'/**/*'], cb);
});

// just makes sure that the build dir exists
gulp.task('init', ['clean'], function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

//gulp.task('test', function () {
//  return gulp.src('./test/**/*.js', {read: false})
//    .pipe(mocha({reporter: 'spec',
//                 useColors: false}));
//});

// copy images from source locations to build location
gulp.task('copy-images', function(cb) {
  gulp.src([
    imagesDir+'/**'
])
.pipe(gulp.dest(buildDir+'/'+imagesDir));
});

// browserify debug
gulp.task('build-browser',['init'], function() {
  var b = browserify({debug: true,hasExports: true});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
});

// browserify min
gulp.task('build-browser-min',['init'], function() {
  var b = browserify({hasExports: true, standalone: "biojs-vis-context-data-unique-list"});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".min.js"))
    .pipe(chmod(644))
    .pipe(streamify(uglify()))
    .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-gzip', ['build-browser-min'], function() {
  return gulp.src(outputFileMin)
    .pipe(gzip({append: false, gzipOptions: { level: 9 }}))
    .pipe(rename(outputFile + ".min.gz.js"))
    .pipe(gulp.dest(buildDir));
});

// exposes the main package
// + checks the config whether it should expose other packages
function exposeBundles(b){
  b.add("./" + packageConfig.main, {expose: packageConfig.name });
  if(packageConfig.sniper !== undefined && packageConfig.sniper.exposed !== undefined){
    for(var i=0; i<packageConfig.sniper.exposed.length; i++){
      b.require(packageConfig.sniper.exposed[i]);
    }
  }
}

// watch task for browserify
// watchify has an internal cache -> subsequent builds are faster
gulp.task('watch', function() {
  var util = require('gulp-util')

  var b = browserify({debug: true,hasExports: true, cache: {}, packageCache: {} });
  b.add("./" + packageConfig.main, {expose: packageConfig.name});
  // expose other bundles
  exposeBundles(b);

  function rebundle(ids){
    b.bundle()
    .on("error", function(error) {
      util.log(util.colors.red("Error: "), error);
     })
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
  }

  var watcher = watchify(b);
  watcher.on("update", rebundle)
   .on("log", function(message) {
      util.log("Refreshed:", message);
  });
  return rebundle();
});
<commit_msg>changed bundle name to biocider<commit_after>/*
 * biojs-vis-context-data-unique-list
 * https://github.com/BioCIDER/biojs-vis-context-data-unique-list
 *
 * Copyright (c) 2015 Carlos Horro
 * Licensed under the MIT license.
 */

// browserify build config
var buildDir = "build";
var outputFile = "biocider";

var imagesDir = "img";

// packages
var gulp   = require('gulp');

// browser builds
var browserify = require('browserify');
var watchify = require('watchify')
var uglify = require('gulp-uglify');

// testing
//var mocha = require('gulp-mocha');

// code style

// gulp helper
var source = require('vinyl-source-stream'); // converts node streams into vinyl streams
var gzip = require('gulp-gzip');
var rename = require('gulp-rename');
var chmod = require('gulp-chmod');
var streamify = require('gulp-streamify'); // converts streams into buffers (legacy support for old plugins)
var watch = require('gulp-watch');

// path tools
var fs = require('fs');
var path = require('path');
var join = path.join;
var mkdirp = require('mkdirp');
var del = require('del');

// auto config
var outputFileMin = join(buildDir,outputFile + ".min.js");
var packageConfig = require('./package.json');

// a failing test breaks the whole build chain
gulp.task('build', ['build-browser', 'build-browser-gzip','copy-images']);
gulp.task('default', [  'build']);

// will remove everything in build
gulp.task('clean', function(cb) {
  del([buildDir+'/img']);
  del([buildDir+'/css']);
  del([buildDir+'/**/*'], cb);
});

// just makes sure that the build dir exists
gulp.task('init', ['clean'], function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

//gulp.task('test', function () {
//  return gulp.src('./test/**/*.js', {read: false})
//    .pipe(mocha({reporter: 'spec',
//                 useColors: false}));
//});

// copy images from source locations to build location
gulp.task('copy-images', function(cb) {
  gulp.src([
    imagesDir+'/**'
])
.pipe(gulp.dest(buildDir+'/'+imagesDir));
});

// browserify debug
gulp.task('build-browser',['init'], function() {
  var b = browserify({debug: true,hasExports: true});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
});

// browserify min
gulp.task('build-browser-min',['init'], function() {
  var b = browserify({hasExports: true, standalone: "biojs-vis-context-data-unique-list"});
  exposeBundles(b);
  return b.bundle()
    .pipe(source(outputFile + ".min.js"))
    .pipe(chmod(644))
    .pipe(streamify(uglify()))
    .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-gzip', ['build-browser-min'], function() {
  return gulp.src(outputFileMin)
    .pipe(gzip({append: false, gzipOptions: { level: 9 }}))
    .pipe(rename(outputFile + ".min.gz.js"))
    .pipe(gulp.dest(buildDir));
});

// exposes the main package
// + checks the config whether it should expose other packages
function exposeBundles(b){
  b.add("./" + packageConfig.main, {expose: packageConfig.name });
  if(packageConfig.sniper !== undefined && packageConfig.sniper.exposed !== undefined){
    for(var i=0; i<packageConfig.sniper.exposed.length; i++){
      b.require(packageConfig.sniper.exposed[i]);
    }
  }
}

// watch task for browserify
// watchify has an internal cache -> subsequent builds are faster
gulp.task('watch', function() {
  var util = require('gulp-util')

  var b = browserify({debug: true,hasExports: true, cache: {}, packageCache: {} });
  b.add("./" + packageConfig.main, {expose: packageConfig.name});
  // expose other bundles
  exposeBundles(b);

  function rebundle(ids){
    b.bundle()
    .on("error", function(error) {
      util.log(util.colors.red("Error: "), error);
     })
    .pipe(source(outputFile + ".js"))
    .pipe(chmod(644))
    .pipe(gulp.dest(buildDir));
  }

  var watcher = watchify(b);
  watcher.on("update", rebundle)
   .on("log", function(message) {
      util.log("Refreshed:", message);
  });
  return rebundle();
});
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');

const argv = require('yargs').argv;
const browserify = require('browserify');
const clc = require('cli-color');
const cson = require('cson');
const es = require('event-stream');
const fs = require('fs-extra');
const globby = require('globby');
const path = require('path');
const plugins = require('gulp-load-plugins')();
const vinylSource = require('vinyl-source-stream');
const watchify = require('watchify');

// language config
const lang = {
  css: {
    extName: 'styl',
    compiler: 'stylus',
    source: 'css',
    dest: 'css'
  },
  html: {
    extName: 'jade',
    compiler: 'jade',
    source: 'html',
    dest: '.'
  },
  js: {
    extName: 'js',
    source: 'js',
    dest: 'js'
  }
};

// predefined path
const compilePath = '__compile';
const devPath = '__dev';
const resourcesPath = '_resources';

// console print
function printWithTime(msg) {
  const nowTime = new Date().toLocaleTimeString();

  console.log('[' + clc.blackBright(nowTime) + ']', msg);
}

// language handlers
function compileLang(langName, destDir, options) {
  const thisLang = lang[langName];

  fs.mkdirsSync(path.join(destDir, thisLang.dest));

  return compileLangHandler(
    thisLang,
    getSourcePath(thisLang),
    destDir,
    options
  );
}

function compileJS(destDir, options) {
  const thisLang = lang.js;

  const sourcePath = getSourcePath(thisLang);

  const entries = globby.sync(sourcePath);

  fs.mkdirsSync(path.join(destDir, thisLang.dest));

  const bundledStreamList = entries.map(function(entry) {
    let b = browserify({
      entries: entry,
      debug: true,
      transform: ['babelify']
    });

    const genBundle = function() {
      const bundledStream = b.bundle()
        .pipe(vinylSource(entry));

      if (!options.watch) {
        const uglifyStream = plugins.streamify(plugins.uglify());
        bundledStream.pipe(uglifyStream);
      }

      return bundledStream
        .pipe(gulp.dest(destDir))
        .on('end', function() {
          printWithTime(clc.magenta(entry) + ' is browserified');
        });
    };

    if (options.watch) {
      b = watchify(b).on('update', genBundle);
    }

    return genBundle();
  });

  return es.concat.apply(null, bundledStreamList)
    .on('end', function() {
      printWithTime(clc.magenta(sourcePath) + ' is compiled');
    });
}

function compileLangHandler(thisLang, sourcePath, destDir, options) {
  const compilerPipe = plugins[thisLang.compiler](options);
  const dest = path.join(destDir, thisLang.dest);

  // printWithTime(clc.magenta(sourcePath) + ' is compiled');

  return gulp.src(sourcePath)
    .pipe(compilerPipe)
    .pipe(gulp.dest(dest))
    .on('end', function() {
      printWithTime(clc.magenta(sourcePath) + ' is compiled');
    });
}

function compileManifest(destDir, updateFn) {
  const manifestJSON = cson.load(path.join(resourcesPath, 'manifest.cson'));
  updateFn(manifestJSON);

  const destPath = path.join(destDir, 'manifest.json');
  fs.writeJSONSync(destPath, manifestJSON);
}

function getSourcePath(thisLang) {
  return path.join(thisLang.source, '*.' + thisLang.extName);
}

function watchLang(langName, destDir, options) {
  const thisLang = lang[langName];

  gulp.watch(getSourcePath(thisLang), function(event) {
    compileLangHandler(thisLang, event.path, destDir, options);
  });

  return compileLang(langName, destDir, options);
}

// markdown handler
function getMarkdownData(titleList) {
  const mdSource = path.join(resourcesPath, 'markdown');

  const dataList = [];
  titleList.forEach(function(title) {
    const fileData = fs.readFileSync(
      path.join(mdSource, `${title}.md`), 'utf-8'
    );

    dataList.push(
      `## ${title}` +
      '\n\n' +
      fileData
    );
  });

  return dataList.join('\n\n');
}

// initiate the output folder
function initDir(dirPath) {
  fs.removeSync(dirPath);
  fs.mkdirSync(dirPath);
}

// default when no task
gulp.task('default', ['help']);

// user guideline
gulp.task('help', function() {
  console.log('\n' + getMarkdownData(['Developer guide']) + '\n');
});

// compile and zip PmB
gulp.task('compile-init', function() {
  const version = argv.version;

  const versionCheck = function(x) {
    return (
      x === `${parseInt(x, 10)}` &&
      x >= 0 &&
      x <= 65535
    );
  };

  if (version === undefined ||
      typeof version !== 'string' ||
      version.split('.').length !== 4 ||
      !version.split('.').every(versionCheck)) {
    throw Error('You need to input a version number x.y.z.ddmm, ' +
      'each number between 0 - 65535');
  }

  initDir(compilePath);
});

gulp.task('compile-css', ['compile-init'], function() {
  return compileLang('css', compilePath, {compress: true});
});

gulp.task('compile-html', ['compile-init'], function() {
  return compileLang('html', compilePath);
});

gulp.task('compile-js', ['compile-init'], function() {
  return compileJS(compilePath, {watch: false});
});

gulp.task('compile-others', ['compile-init'], function() {
  const fileList = ['font', '_locales', 'LICENSE'];

  fileList.forEach(function(fileName) {
    fs.copySync(fileName, path.join(compilePath, fileName));
  });
  fs.copySync(path.join(resourcesPath, 'img'), path.join(compilePath, 'img'));

  compileManifest(compilePath, function(manifestJSON) {
    manifestJSON.version = argv.version;
  });
});

gulp.task('compile-zip', [
            'compile-css',
            'compile-html',
            'compile-js',
            'compile-others'
          ], function() {
  return gulp.src(path.join(compilePath, '**'))
    .pipe(plugins.zip(argv.version + '.zip'))
    .pipe(gulp.dest('.'));
});

gulp.task('compile', ['compile-zip'], function() {
  // useless after zipped
  fs.removeSync(compilePath);
});

// create a 'watched' folder for testing
gulp.task('dev', function() {
  initDir(devPath);

  watchLang('css', devPath);
  watchLang('html', devPath, {pretty: true});
  compileJS(devPath, {watch: true});

  const fileList = ['font', '_locales'];

  fileList.forEach(function(fileName) {
    fs.symlinkSync(
      path.join('..', fileName),
      path.join(devPath, fileName),
      'dir'
    );
  });
  fs.symlinkSync(
    path.join('..', resourcesPath, 'img-dev'),
    path.join(devPath, 'img'),
    'dir'
  );

  compileManifest(devPath, function(manifestJSON) {
    manifestJSON.name += '(dev)';
    manifestJSON.version = '0.0.0.0';
  });
});

// Lints
gulp.task('lint-css', function() {
  return gulp.src(path.join(lang.css.source, '*'))
    .pipe(plugins.stylint());
});

gulp.task('lint-js', function() {
  return gulp.src([
    'gulpfile.js',
    path.join(lang.js.source, '**')
  ])
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError());
});

gulp.task('lint', ['lint-css', 'lint-js']);

// generate markdown file
gulp.task('md', function() {
  const fileName = argv.make;

  let fileData;

  switch (fileName) {
    case '__store.md':
      fileData = getMarkdownData([
        'Popup my Bookmarks',
        'Plan to do',
        'What you can help',
        'FAQ'
      ]);

      // remove first three lines
      fileData = fileData.replace(/.+\n\n.+\n/, '');

      // remove style of subheader
      fileData = fileData.replace(/##### /g, '');

      break;

    case 'README.md':
      fileData = getMarkdownData([
        'Popup my Bookmarks',
        'Developer guide',
        'Plan to do',
        'What you can help',
        'FAQ'
      ]);

      // enlarge first header
      fileData = fileData.replace(/^##/, '#');

      break;

    default:
      throw Error(`Unknown markdown file: ${fileName}`);
  }

  fs.writeFile(fileName, fileData);
});
<commit_msg>Use remove instead of removeSync for gulp compile<commit_after>'use strict';

const gulp = require('gulp');

const argv = require('yargs').argv;
const browserify = require('browserify');
const clc = require('cli-color');
const cson = require('cson');
const es = require('event-stream');
const fs = require('fs-extra');
const globby = require('globby');
const path = require('path');
const plugins = require('gulp-load-plugins')();
const vinylSource = require('vinyl-source-stream');
const watchify = require('watchify');

// language config
const lang = {
  css: {
    extName: 'styl',
    compiler: 'stylus',
    source: 'css',
    dest: 'css'
  },
  html: {
    extName: 'jade',
    compiler: 'jade',
    source: 'html',
    dest: '.'
  },
  js: {
    extName: 'js',
    source: 'js',
    dest: 'js'
  }
};

// predefined path
const compilePath = '__compile';
const devPath = '__dev';
const resourcesPath = '_resources';

// console print
function printWithTime(msg) {
  const nowTime = new Date().toLocaleTimeString();

  console.log('[' + clc.blackBright(nowTime) + ']', msg);
}

// language handlers
function compileLang(langName, destDir, options) {
  const thisLang = lang[langName];

  fs.mkdirsSync(path.join(destDir, thisLang.dest));

  return compileLangHandler(
    thisLang,
    getSourcePath(thisLang),
    destDir,
    options
  );
}

function compileJS(destDir, options) {
  const thisLang = lang.js;

  const sourcePath = getSourcePath(thisLang);

  const entries = globby.sync(sourcePath);

  fs.mkdirsSync(path.join(destDir, thisLang.dest));

  const bundledStreamList = entries.map(function(entry) {
    let b = browserify({
      entries: entry,
      debug: true,
      transform: ['babelify']
    });

    const genBundle = function() {
      const bundledStream = b.bundle()
        .pipe(vinylSource(entry));

      if (!options.watch) {
        const uglifyStream = plugins.streamify(plugins.uglify());
        bundledStream.pipe(uglifyStream);
      }

      return bundledStream
        .pipe(gulp.dest(destDir))
        .on('end', function() {
          printWithTime(clc.magenta(entry) + ' is browserified');
        });
    };

    if (options.watch) {
      b = watchify(b).on('update', genBundle);
    }

    return genBundle();
  });

  return es.concat.apply(null, bundledStreamList)
    .on('end', function() {
      printWithTime(clc.magenta(sourcePath) + ' is compiled');
    });
}

function compileLangHandler(thisLang, sourcePath, destDir, options) {
  const compilerPipe = plugins[thisLang.compiler](options);
  const dest = path.join(destDir, thisLang.dest);

  // printWithTime(clc.magenta(sourcePath) + ' is compiled');

  return gulp.src(sourcePath)
    .pipe(compilerPipe)
    .pipe(gulp.dest(dest))
    .on('end', function() {
      printWithTime(clc.magenta(sourcePath) + ' is compiled');
    });
}

function compileManifest(destDir, updateFn) {
  const manifestJSON = cson.load(path.join(resourcesPath, 'manifest.cson'));
  updateFn(manifestJSON);

  const destPath = path.join(destDir, 'manifest.json');
  fs.writeJSONSync(destPath, manifestJSON);
}

function getSourcePath(thisLang) {
  return path.join(thisLang.source, '*.' + thisLang.extName);
}

function watchLang(langName, destDir, options) {
  const thisLang = lang[langName];

  gulp.watch(getSourcePath(thisLang), function(event) {
    compileLangHandler(thisLang, event.path, destDir, options);
  });

  return compileLang(langName, destDir, options);
}

// markdown handler
function getMarkdownData(titleList) {
  const mdSource = path.join(resourcesPath, 'markdown');

  const dataList = [];
  titleList.forEach(function(title) {
    const fileData = fs.readFileSync(
      path.join(mdSource, `${title}.md`), 'utf-8'
    );

    dataList.push(
      `## ${title}` +
      '\n\n' +
      fileData
    );
  });

  return dataList.join('\n\n');
}

// initiate the output folder
function initDir(dirPath) {
  fs.removeSync(dirPath);
  fs.mkdirSync(dirPath);
}

// default when no task
gulp.task('default', ['help']);

// user guideline
gulp.task('help', function() {
  console.log('\n' + getMarkdownData(['Developer guide']) + '\n');
});

// compile and zip PmB
gulp.task('compile-init', function() {
  const version = argv.version;

  const versionCheck = function(x) {
    return (
      x === `${parseInt(x, 10)}` &&
      x >= 0 &&
      x <= 65535
    );
  };

  if (version === undefined ||
      typeof version !== 'string' ||
      version.split('.').length !== 4 ||
      !version.split('.').every(versionCheck)) {
    throw Error('You need to input a version number x.y.z.ddmm, ' +
      'each number between 0 - 65535');
  }

  initDir(compilePath);
});

gulp.task('compile-css', ['compile-init'], function() {
  return compileLang('css', compilePath, {compress: true});
});

gulp.task('compile-html', ['compile-init'], function() {
  return compileLang('html', compilePath);
});

gulp.task('compile-js', ['compile-init'], function() {
  return compileJS(compilePath, {watch: false});
});

gulp.task('compile-others', ['compile-init'], function() {
  const fileList = ['font', '_locales', 'LICENSE'];

  fileList.forEach(function(fileName) {
    fs.copySync(fileName, path.join(compilePath, fileName));
  });
  fs.copySync(path.join(resourcesPath, 'img'), path.join(compilePath, 'img'));

  compileManifest(compilePath, function(manifestJSON) {
    manifestJSON.version = argv.version;
  });
});

gulp.task('compile-zip', [
            'compile-css',
            'compile-html',
            'compile-js',
            'compile-others'
          ], function() {
  return gulp.src(path.join(compilePath, '**'))
    .pipe(plugins.zip(argv.version + '.zip'))
    .pipe(gulp.dest('.'));
});

gulp.task('compile', ['compile-zip'], function() {
  // useless after zipped
  fs.remove(compilePath);
});

// create a 'watched' folder for testing
gulp.task('dev', function() {
  initDir(devPath);

  watchLang('css', devPath);
  watchLang('html', devPath, {pretty: true});
  compileJS(devPath, {watch: true});

  const fileList = ['font', '_locales'];

  fileList.forEach(function(fileName) {
    fs.symlinkSync(
      path.join('..', fileName),
      path.join(devPath, fileName),
      'dir'
    );
  });
  fs.symlinkSync(
    path.join('..', resourcesPath, 'img-dev'),
    path.join(devPath, 'img'),
    'dir'
  );

  compileManifest(devPath, function(manifestJSON) {
    manifestJSON.name += '(dev)';
    manifestJSON.version = '0.0.0.0';
  });
});

// Lints
gulp.task('lint-css', function() {
  return gulp.src(path.join(lang.css.source, '*'))
    .pipe(plugins.stylint());
});

gulp.task('lint-js', function() {
  return gulp.src([
    'gulpfile.js',
    path.join(lang.js.source, '**')
  ])
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError());
});

gulp.task('lint', ['lint-css', 'lint-js']);

// generate markdown file
gulp.task('md', function() {
  const fileName = argv.make;

  let fileData;

  switch (fileName) {
    case '__store.md':
      fileData = getMarkdownData([
        'Popup my Bookmarks',
        'Plan to do',
        'What you can help',
        'FAQ'
      ]);

      // remove first three lines
      fileData = fileData.replace(/.+\n\n.+\n/, '');

      // remove style of subheader
      fileData = fileData.replace(/##### /g, '');

      break;

    case 'README.md':
      fileData = getMarkdownData([
        'Popup my Bookmarks',
        'Developer guide',
        'Plan to do',
        'What you can help',
        'FAQ'
      ]);

      // enlarge first header
      fileData = fileData.replace(/^##/, '#');

      break;

    default:
      throw Error(`Unknown markdown file: ${fileName}`);
  }

  fs.writeFile(fileName, fileData);
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var chef = require('gulp-chef');

var browserSync = require('browser-sync');
var ghpages = require('gulp-gh-pages');

var ingredients = {
	src: 'src/',
	dest: 'dist/',
	clean: {},
	deploy: {
		src: {
			globs: '{{dest.path}}**/*',
			options: {
				join: ''
			}
		},
		config: {
			options: {
				remoteUrl: 'git@github.com:gulp-cookery/gulp-chef.git',
				branch: 'gh-pages'
			}
		},
		task: deploy
	},
	make: {
		script: {
			recipe: 'browserify',
			bundle: {
				entry: 'index.js',
				file: 'scripts.js',
				transform: ['stringify', 'browserify-shim'],
				uglify: true
			}
		},
		style: {
			src: 'styles.css',
			recipe: 'postcss',
			processors: {
				import: {},
				cssnext: {
					features: {
						autoprefixer: {
							browser: 'last 2 versions'
						}
					}
				},
				bem: {},
				lost: {},
				cssnano: {}
			}
		},
		markup: {
			src: 'index.html',
			recipe: 'copy'
		},
		assets: {
			src: {
				globs: [
					'favicon.ico',
					'opensearch.xml',
					'gulp-chef-white-text.svg'
				]
			},
			task: assets
		}
	},
	build: ['clean', 'make'],
	serve: ['build', watch],
	default: 'build'
};

var meals = chef(ingredients);

gulp.registry(meals);

function watch() {
	browserSync.init({
		server: this.config.dest.path
	});

	gulp.watch(ingredients.src + '**/*')
		.on('change', run);

	function run() {
		return gulp.parallel(gulp.task('make'), browserSync.reload)(done);
	}

	function done() {
	}
}

function deploy() {
	var config = this.config;

	return gulp.src(config.src.globs, config.src.options)
		.pipe(ghpages(config.options));
}

function assets() {
	var config = this.config;

	return gulp.src(config.src.globs, config.src.options)
		.pipe(gulp.dest(config.dest.path))
		.pipe(browserSync.stream());
}
<commit_msg>gulp: rewrite watch()<commit_after>'use strict';

var gulp = require('gulp');
var chef = require('gulp-chef');

var browserSync = require('browser-sync');
var ghpages = require('gulp-gh-pages');

var ingredients = {
	src: 'src/',
	dest: 'dist/',
	clean: {},
	deploy: {
		src: {
			globs: '{{dest.path}}**/*',
			options: {
				join: ''
			}
		},
		config: {
			options: {
				remoteUrl: 'git@github.com:gulp-cookery/gulp-chef.git',
				branch: 'gh-pages'
			}
		},
		task: deploy
	},
	make: {
		script: {
			recipe: 'browserify',
			bundle: {
				entry: 'index.js',
				file: 'scripts.js',
				transform: ['stringify', 'browserify-shim'],
				uglify: true
			}
		},
		style: {
			src: 'styles.css',
			recipe: 'postcss',
			processors: {
				import: {},
				cssnext: {
					features: {
						autoprefixer: {
							browser: 'last 2 versions'
						}
					}
				},
				bem: {},
				lost: {},
				cssnano: {}
			}
		},
		markup: {
			src: 'index.html',
			recipe: 'copy'
		},
		assets: {
			src: {
				globs: [
					'favicon.ico',
					'opensearch.xml',
					'gulp-chef-white-text.svg'
				]
			},
			task: assets
		}
	},
	build: ['clean', 'make'],
	serve: ['build', watch],
	default: 'build'
};

var meals = chef(ingredients);

gulp.registry(meals);

function watch() {
	browserSync.init({
		server: this.config.dest.path
	});

	gulp.watch(this.config.src.globs[0] + '**/*', gulp.parallel(gulp.task('make'), browserSync.reload));
}

function deploy() {
	var config = this.config;

	return gulp.src(config.src.globs, config.src.options)
		.pipe(ghpages(config.options));
}

function assets() {
	var config = this.config;

	return gulp.src(config.src.globs, config.src.options)
		.pipe(gulp.dest(config.dest.path))
		.pipe(browserSync.stream());
}
<|endoftext|>


<commit_before>var $      = require('gulp-load-plugins')();
var argv   = require('yargs').argv;
var gulp   = require('gulp');
var rimraf = require('rimraf');
var panini = require('panini');
var sequence = require('run-sequence');

// Check for --production flag
var isProduction = !!(argv.production);

// File paths to various assets are defined here.
var paths = {
  assets: [
    'src/assets/**/*',
    '!src/assets/{!img,js,scss}/**/*'
  ],
  sass: [
    'node_modules/foundation-sites/scss'
  ],
  javascript: [
    'node_modules/jquery/dist/jquery.js',
    'node_modules/foundation-sites/dist/foundation.js',
    'src/assets/js/**/*.js',
    'src/assets/js/app.js'
  ]
};

// Delete the "dist" folder
// This happens every time a build starts
gulp.task('clean', function(done) {
  rimraf('./dist', done);
});

// Copy files out of the assets folder
// This task skips over the "img", "js", and "scss" folders, which are parsed separately
gulp.task('copy', function(done) {
  gulp.src(paths.assets)
    .pipe(gulp.dist('./dist/assets'));
});

// Copy page templates into finished HTML files
gulp.task('pages', function() {
  gulp.src('./src/pages/**/*.html')
    .pipe(panini({
      layouts: './src/layouts/',
      partials: './src/partials/**/*.html',
      data: './src/data/**/*.{json,yml}'
    }))
    .pipe(gulp.dest('./dist'));
});

// Compile Sass into CSS
// In production, the CSS is compressed
gulp.task('sass', function() {
  var uncss = $.if(isProduction, $.uncss({
    html: ['src/**/*.html'],
    ignore: [
      new RegExp('^meta\..*'),
      new RegExp('^\.is-.*')
    ]
  }));

  return gulp.src('./src/assets/scss/app.scss')
    .pipe($.sass({
      includePaths: paths.sass,
      outputStyle: (isProduction ? 'compressed' : 'nested'),
      errLogToConsole: true
    }))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie >= 9']
    }))
    .pipe(uncss)
    .pipe(gulp.dest('./dist/assets/css'));
});

// Combine JavaScript into one file
// In production, the file is minified
gulp.task('javascript', function() {
  var uglify = $.if(isProduction, $.uglify()
    .on('error', function (e) {
      console.log(e);
    }));

  return gulp.src(paths.javascript)
    .pipe($.concat('app.js'))
    .pipe(uglify)
    .pipe(gulp.dest('./dist/assets/js'));
});

// Copy images to the "dist" folder
// In production, the images are compressed
gulp.task('images', function() {
  var imagemin = $.if(isProduction, $.imagemin({
    progressive: true
  }));

  return gulp.src('./src/assets/img/**/*')
    .pipe(imagemin)
    .pipe(gulp.dest('./dist/assets/img'));
});

// Build the "dist" folder by running all of the above tasks
gulp.task('build', function(done) {
  sequence('clean', ['pages', 'sass', 'javascript', 'images'], done);
});

// Start a server with LiveReload to preview the site in
gulp.task('server', ['build'], function() {
  return gulp.src('./dist')
    .pipe($.webserver({
      host: 'localhost',
      port: 8000,
      livereload: true,
      open: true
    }));
});

// Build the site, run the server, and watch for file changes
gulp.task('default', ['build', 'server'], function() {
  gulp.watch(paths.assets, ['copy']);
  gulp.watch(['./src/pages/**/*.html'], ['pages']);
  gulp.watch(['./src/assets/scss/**/*.scss'], ['sass']);
  gulp.watch(['./src/assets/js/**/*.js'], ['javascript']);
  gulp.watch(['./src/assets/img/**/*'], ['images']);
});
<commit_msg>Correct function call<commit_after>var $      = require('gulp-load-plugins')();
var argv   = require('yargs').argv;
var gulp   = require('gulp');
var rimraf = require('rimraf');
var panini = require('panini');
var sequence = require('run-sequence');

// Check for --production flag
var isProduction = !!(argv.production);

// File paths to various assets are defined here.
var paths = {
  assets: [
    'src/assets/**/*',
    '!src/assets/{!img,js,scss}/**/*'
  ],
  sass: [
    'node_modules/foundation-sites/scss'
  ],
  javascript: [
    'node_modules/jquery/dist/jquery.js',
    'node_modules/foundation-sites/dist/foundation.js',
    'src/assets/js/**/*.js',
    'src/assets/js/app.js'
  ]
};

// Delete the "dist" folder
// This happens every time a build starts
gulp.task('clean', function(done) {
  rimraf('./dist', done);
});

// Copy files out of the assets folder
// This task skips over the "img", "js", and "scss" folders, which are parsed separately
gulp.task('copy', function(done) {
  gulp.src(paths.assets)
    .pipe(gulp.dest('./dist/assets'));
});

// Copy page templates into finished HTML files
gulp.task('pages', function() {
  gulp.src('./src/pages/**/*.html')
    .pipe(panini({
      layouts: './src/layouts/',
      partials: './src/partials/**/*.html',
      data: './src/data/**/*.{json,yml}'
    }))
    .pipe(gulp.dest('./dist'));
});

// Compile Sass into CSS
// In production, the CSS is compressed
gulp.task('sass', function() {
  var uncss = $.if(isProduction, $.uncss({
    html: ['src/**/*.html'],
    ignore: [
      new RegExp('^meta\..*'),
      new RegExp('^\.is-.*')
    ]
  }));

  return gulp.src('./src/assets/scss/app.scss')
    .pipe($.sass({
      includePaths: paths.sass,
      outputStyle: (isProduction ? 'compressed' : 'nested'),
      errLogToConsole: true
    }))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie >= 9']
    }))
    .pipe(uncss)
    .pipe(gulp.dest('./dist/assets/css'));
});

// Combine JavaScript into one file
// In production, the file is minified
gulp.task('javascript', function() {
  var uglify = $.if(isProduction, $.uglify()
    .on('error', function (e) {
      console.log(e);
    }));

  return gulp.src(paths.javascript)
    .pipe($.concat('app.js'))
    .pipe(uglify)
    .pipe(gulp.dest('./dist/assets/js'));
});

// Copy images to the "dist" folder
// In production, the images are compressed
gulp.task('images', function() {
  var imagemin = $.if(isProduction, $.imagemin({
    progressive: true
  }));

  return gulp.src('./src/assets/img/**/*')
    .pipe(imagemin)
    .pipe(gulp.dest('./dist/assets/img'));
});

// Build the "dist" folder by running all of the above tasks
gulp.task('build', function(done) {
  sequence('clean', ['pages', 'sass', 'javascript', 'images'], done);
});

// Start a server with LiveReload to preview the site in
gulp.task('server', ['build'], function() {
  return gulp.src('./dist')
    .pipe($.webserver({
      host: 'localhost',
      port: 8000,
      livereload: true,
      open: true
    }));
});

// Build the site, run the server, and watch for file changes
gulp.task('default', ['build', 'server'], function() {
  gulp.watch(paths.assets, ['copy']);
  gulp.watch(['./src/pages/**/*.html'], ['pages']);
  gulp.watch(['./src/assets/scss/**/*.scss'], ['sass']);
  gulp.watch(['./src/assets/js/**/*.js'], ['javascript']);
  gulp.watch(['./src/assets/img/**/*'], ['images']);
});
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const gulp = require('gulp');
const excludeGitignore = require('gulp-exclude-gitignore');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
const nsp = require('gulp-nsp');
const plumber = require('gulp-plumber');
const coveralls = require('gulp-coveralls');
const eslint = require('gulp-eslint');
const babel = require('gulp-babel');
const bump = require('gulp-bump');
const sequence = require('gulp-sequence');
const git = require('gulp-git');

gulp.task('nsp', (cb) => {
    return nsp({package: `${__dirname}/package.json`}, cb);
});

gulp.task('eslint', () => {
    return gulp.src(['**/*.js', '!lib/**/*.js'])
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.formatEach())
        .pipe(eslint.failAfterError());
});

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('pre-test', ['babel'], () => {
    return gulp.src('lib/**/*.js')
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], (cb) => {
    let mochaErr;

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

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

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

gulp.task('watch', () => {
    gulp.watch('**/*.js', ['build']);
});

gulp.task('bump', () => {
    if (process.argv.length < 3) {
        throw new Error(`Please provide an argument with increase type: --patch, --minor or --major`);
    }

    let type = process.argv[process.argv.length - 1].slice(2).toLowerCase();
    if (type !== 'patch' && type !== 'minor' && type !== 'major') {
        throw new Error(`Please provide a valid version increase type: --patch, --minor or --major`);
    }

    return gulp.src('./package.json')
        .pipe(bump({type: type}))
        .pipe(gulp.dest('./'));
});

gulp.task('tag', ['bump'], () => {
    delete require.cache[require.resolve('./package.json')];
    let versionNumber = require('./package.json').version;
    let version = `v${versionNumber}`;

    if (typeof versionNumber !== 'string') {
        throw new Error(`Current package.json version is invalid.`);
    }

    return gulp.src('./package.json')
        .pipe(git.add())
        .pipe(git.commit(`Release ${version}`, {args: '--allow-empty'}))
        .pipe(git.tag(version, `Release ${version}`, {args: '-a'}, (err) => {
            if (!err) git.push('origin', null, {args: '--follow-tags'});
        }));
});

gulp.task('npm', ['tag'], (cb) => {
    require('child_process')
        .spawn('npm', ['publish'], {stdio: 'inherit'})
        .on('close', cb);
});

// Publishes package to npm
gulp.task('publish', (cb) => {
    sequence('build', 'npm', cb);
});

// Does full a build
gulp.task('build', ['nsp', 'eslint', 'coveralls']);
<commit_msg>Using new arg to push commits alongside tags<commit_after>'use strict';

const path = require('path');
const gulp = require('gulp');
const excludeGitignore = require('gulp-exclude-gitignore');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
const nsp = require('gulp-nsp');
const plumber = require('gulp-plumber');
const coveralls = require('gulp-coveralls');
const eslint = require('gulp-eslint');
const babel = require('gulp-babel');
const bump = require('gulp-bump');
const sequence = require('gulp-sequence');
const git = require('gulp-git');

gulp.task('nsp', (cb) => {
    return nsp({package: `${__dirname}/package.json`}, cb);
});

gulp.task('eslint', () => {
    return gulp.src(['**/*.js', '!lib/**/*.js'])
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.formatEach())
        .pipe(eslint.failAfterError());
});

gulp.task('babel', () => {
    return gulp.src('src/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('lib'));
});

gulp.task('pre-test', ['babel'], () => {
    return gulp.src('lib/**/*.js')
        .pipe(istanbul({
            includeUntested: true
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], (cb) => {
    let mochaErr;

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

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

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

gulp.task('watch', () => {
    gulp.watch('**/*.js', ['build']);
});

gulp.task('bump', () => {
    if (process.argv.length < 3) {
        throw new Error(`Please provide an argument with increase type: --patch, --minor or --major`);
    }

    let type = process.argv[process.argv.length - 1].slice(2).toLowerCase();
    if (type !== 'patch' && type !== 'minor' && type !== 'major') {
        throw new Error(`Please provide a valid version increase type: --patch, --minor or --major`);
    }

    return gulp.src('./package.json')
        .pipe(bump({type: type}))
        .pipe(gulp.dest('./'));
});

gulp.task('tag', ['bump'], () => {
    delete require.cache[require.resolve('./package.json')];
    let versionNumber = require('./package.json').version;
    let version = `v${versionNumber}`;

    if (typeof versionNumber !== 'string') {
        throw new Error(`Current package.json version is invalid.`);
    }

    return gulp.src('./package.json')
        .pipe(git.add())
        .pipe(git.commit(`Release ${version}`, {args: '--allow-empty'}))
        .pipe(git.tag(version, `Release ${version}`, {args: '-a'}, (err) => {
            if (!err) git.push('origin', null, {args: '--tags :'});
        }));
});

gulp.task('npm', ['tag'], (cb) => {
    require('child_process')
        .spawn('npm', ['publish'], {stdio: 'inherit'})
        .on('close', cb);
});

// Publishes package to npm
gulp.task('publish', (cb) => {
    sequence('build', 'npm', cb);
});

// Does full a build
gulp.task('build', ['nsp', 'eslint', 'coveralls']);
<|endoftext|>


<commit_before>const GAME_NAME = 'game-01'

const gulp = require('gulp')
const browserify = require('browserify')
const sourcemaps = require('gulp-sourcemaps')
const livereload = require('gulp-livereload')
const nodemon = require('gulp-nodemon')
const source = require('vinyl-source-stream')
const buffer = require('vinyl-buffer')

gulp.task('bundle', () => {
  return browserify({
    basedir: '.',
    debug: true,
    entries: [GAME_NAME + '/index.js'],
    cache: {},
    packageCache: {}
  })
  .transform('babelify', {
    presets: ['es2015']
  })
  .bundle()
  .pipe(source(GAME_NAME + '.min.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({loadMaps: true}))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('public/bundles'))
  .pipe(livereload())
})

function watchServer() {
  nodemon({
    script: 'server.js',
    watch: ['server.js']
  })
}

gulp.task('watch', ['bundle'], () => {
  watchServer()
  livereload.listen()
  gulp.watch(GAME_NAME + '/index.js', ['bundle'])
})
<commit_msg>Adding notes.<commit_after>const GAME_NAME = 'game-01'

const gulp = require('gulp')
const browserify = require('browserify')
const sourcemaps = require('gulp-sourcemaps')
const livereload = require('gulp-livereload')
const nodemon = require('gulp-nodemon')
const source = require('vinyl-source-stream')
const buffer = require('vinyl-buffer')

gulp.task('bundle', () => {
  return browserify({
    basedir: '.',
    debug: true,
    entries: [GAME_NAME + '/index.js'],
    cache: {},
    packageCache: {}
  })
  .transform('babelify', {
    presets: ['es2015']
  })
  .bundle()
  .pipe(source(GAME_NAME + '.min.js'))
  .pipe(buffer())
  .pipe(sourcemaps.init({loadMaps: true}))
  .pipe(sourcemaps.write('./'))
  .pipe(gulp.dest('public/bundles'))
  .pipe(livereload())
})

function watchServer() {
  nodemon({
    script: 'server.js',
    watch: ['server.js']
  })
}

gulp.task('watch', ['bundle'], () => {
  watchServer()
  livereload.listen()
  gulp.watch(GAME_NAME + '/index.js', ['bundle'])
})

// CREATE TASKS:
//  Test game
//  Test sc-/ut-modules
<|endoftext|>