<commit_before>/*
 * # DEPENDENCIES #
 */
var gulp        = require('gulp');
var browserSync = require('browser-sync');
var reload      = browserSync.reload; // reload shorthand
var path        = require('path');
var addsrc      = require('gulp-add-src');
var del         = require('del');
var run         = require('run-sequence');
var merge       = require('merge-stream');
var _           = require('lodash');
// html building
var build       = require('./build.js');
// styles and scripts
var less        = require('gulp-less');
var concat      = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var minify      = require('gulp-minify-css');
var uglify      = require('gulp-uglify');
// archive
var zip         = require('gulp-zip');
var fs          = require('fs');
// pdf generation
var pdf         = require('./pdf.js');
// link-checking
var checkLinks = require('./check-links');
// get configuration variables
var config      = require('./config.js');

// github hooks
var exec = require('child_process').exec;
var githubhook = require('githubhook');

/*
 * # VARIABLES #
 */
var assetRoot = config.assetRoot;
var buildRoot = config.buildRoot;
var lessonRoot = config.lessonRoot;
var sourceFolder = config.sourceFolder;
var ghHost = config.ghHost;
var ghPort = config.ghPort;
var ghPath = config.ghPath;
var ghRepo = config.ghRepo;
var ghPushCommand = config.ghPushCommand;
var ghSecret = config.ghSecret;

/*
 * # TASKS #
 */

/*
 * Create archive files for each subdir of buildRoot
 * Each archive includes all assets.
 */
gulp.task('archive', function() {
  var src_dirs = fs.readdirSync(buildRoot).filter(function(file) {
    return fs.statSync(path.join(buildRoot, file)).isDirectory();
  });
  var streams = _.map(src_dirs, function (dirname){
    if (dirname == 'assets') {
      return;
    }
    return gulp.src([
          buildRoot + '/index.html',
          buildRoot + '/{assets,assets/**}',
          buildRoot + '/{'+dirname+','+dirname+'/**}',
          ])
      .pipe(zip(dirname + '.zip'))
      .pipe(gulp.dest(buildRoot));
  });
  streams = _.compact(streams);
  return merge(streams);
});

/*
 * serve build directory
 */
gulp.task('server', ['build', 'css', 'js', 'assets'], function () {
  browserSync.init({
    server: { baseDir: buildRoot }
  });
});

/*
 * build less files to css, prefix and minify
 */
gulp.task('css', function(cb) {
  return gulp.src('styles/*.less')
    .pipe(less())
    .on('error', cb)
    .pipe(addsrc([
      'node_modules/scratchblocks2/build/scratchblocks2.css',
      'node_modules/metalsmith-code-highlight/node_modules/highlight.js/styles/idea.css'
    ]))
    .pipe(autoprefixer())
    .pipe(minify())
    .pipe(concat('style.min.css'))
    .pipe(gulp.dest(assetRoot));
});

/*
 * copy all assets to build directory
 */
gulp.task('assets', function(){
  return gulp.src([
      'assets/**/*',
      'node_modules/scratchblocks2/build/*/*.png',
      'node_modules/bootstrap/dist/*/glyphicons-halflings-regular.*',
      'node_modules/jquery/dist/jquery.min.map'
    ])
    .pipe(gulp.dest(assetRoot));
});

/*
 * concat and uglify scripts
 */
gulp.task('js', function(){
  return gulp.src([
    'scripts/**/*.js',
    'node_modules/scratchblocks2/build/scratchblocks2.js',
    'node_modules/scratchblocks2/src/translations.js'
  ])
  .pipe(uglify())
  .pipe(addsrc.prepend([
    'node_modules/jquery/dist/jquery.min.js'
  ]))
  .pipe(concat('script.min.js'))
  .pipe(gulp.dest(assetRoot));
});

/*
 * metalsmith building
 */
gulp.task('build', build);
gulp.task('force-build', function(done){
  build(function(err){
    console.log('done called')
    done();
  }, { // build options
    force: true
  });
});
/*
 * dist - build all without serving
 */
gulp.task('dist', function(cb){
  // preferred way to this will change in gulp 4
  // see https://github.com/gulpjs/gulp/issues/96
  run('clean',
      ['assets', 'build', 'css', 'js'],
      'archive',
      'pdf', // do not include pdf in zip files
      cb);
});

/*
 * clean - remove files in build directory
 */
gulp.task('clean', function(cb){
  del([path.join(lessonRoot, 'build')], {force: true}, cb);
});

/*
 * pdf - generate pdfs of all htmls
 */
gulp.task('pdf', pdf);

/*
 * links - check for broken links
 */
gulp.task('links', checkLinks('http://localhost:3000/'));
gulp.task('prodlinks', checkLinks(config.productionCrawlStart));

/*
 * github webhook for automatic building
 */
gulp.task('github', function(cb){
  var github = githubhook({
    host: ghHost,
    port: ghPort,
    path: ghPath,
    secret: ghSecret
  });
  github.on('push:'+ghRepo, function(repo, ref, data) {
    deployProc = exec(ghPushCommand, function(err, stdout, stderr) {
      if(err!==null) {
        console.log(stderr);
      }
    });
  });
  github.listen();
});

/*
 * # DEFAULT TASK #
 * do metalsmith build
 * build, concat and minify styles
 * concat and uglify scripts
 * copy assets
 * serve build directory with livereload
 * watch files -> build and reload upon changes
 */
gulp.task('default', ['server'], function(){
  /*
   * ## WATCHES ##
   */
  // files which are built with metalsmith
  gulp.watch(path.join(lessonRoot, sourceFolder, '**'), ['build', reload]);
  gulp.watch(path.join(__dirname, 'templates', '**'), ['force-build', reload]);

  // styles
  gulp.watch(path.join(__dirname, 'styles', '**', '*'), ['css', reload]);

  // scripts
  gulp.watch(path.join(__dirname, 'scripts', '**'), ['js', reload]);

  // assets
  gulp.watch(path.join(__dirname, 'assets', '**'), ['assets', reload]);
});
<commit_msg>compile only main.less, include tooltip.js<commit_after>/*
 * # DEPENDENCIES #
 */
var gulp        = require('gulp');
var browserSync = require('browser-sync');
var reload      = browserSync.reload; // reload shorthand
var path        = require('path');
var addsrc      = require('gulp-add-src');
var del         = require('del');
var run         = require('run-sequence');
var merge       = require('merge-stream');
var _           = require('lodash');
// html building
var build       = require('./build.js');
// styles and scripts
var less        = require('gulp-less');
var concat      = require('gulp-concat');
var autoprefixer = require('gulp-autoprefixer');
var minify      = require('gulp-minify-css');
var uglify      = require('gulp-uglify');
// archive
var zip         = require('gulp-zip');
var fs          = require('fs');
// pdf generation
var pdf         = require('./pdf.js');
// link-checking
var checkLinks = require('./check-links');
// get configuration variables
var config      = require('./config.js');

// github hooks
var exec = require('child_process').exec;
var githubhook = require('githubhook');

/*
 * # VARIABLES #
 */
var assetRoot = config.assetRoot;
var buildRoot = config.buildRoot;
var lessonRoot = config.lessonRoot;
var sourceFolder = config.sourceFolder;
var ghHost = config.ghHost;
var ghPort = config.ghPort;
var ghPath = config.ghPath;
var ghRepo = config.ghRepo;
var ghPushCommand = config.ghPushCommand;
var ghSecret = config.ghSecret;

/*
 * # TASKS #
 */

/*
 * Create archive files for each subdir of buildRoot
 * Each archive includes all assets.
 */
gulp.task('archive', function() {
  var src_dirs = fs.readdirSync(buildRoot).filter(function(file) {
    return fs.statSync(path.join(buildRoot, file)).isDirectory();
  });
  var streams = _.map(src_dirs, function (dirname){
    if (dirname == 'assets') {
      return;
    }
    return gulp.src([
          buildRoot + '/index.html',
          buildRoot + '/{assets,assets/**}',
          buildRoot + '/{'+dirname+','+dirname+'/**}',
          ])
      .pipe(zip(dirname + '.zip'))
      .pipe(gulp.dest(buildRoot));
  });
  streams = _.compact(streams);
  return merge(streams);
});

/*
 * serve build directory
 */
gulp.task('server', ['build', 'css', 'js', 'assets'], function () {
  browserSync.init({
    server: { baseDir: buildRoot }
  });
});

/*
 * build less files to css, prefix and minify
 */
gulp.task('css', function(cb) {
  return gulp.src('styles/main.less')
    .pipe(less())
    .on('error', cb)
    .pipe(addsrc([
      'node_modules/scratchblocks2/build/scratchblocks2.css',
      'node_modules/metalsmith-code-highlight/node_modules/highlight.js/styles/idea.css'
    ]))
    .pipe(autoprefixer())
    .pipe(minify())
    .pipe(concat('style.min.css'))
    .pipe(gulp.dest(assetRoot));
});

/*
 * copy all assets to build directory
 */
gulp.task('assets', function(){
  return gulp.src([
      'assets/**/*',
      'node_modules/scratchblocks2/build/*/*.png',
      'node_modules/bootstrap/dist/*/glyphicons-halflings-regular.*',
      'node_modules/jquery/dist/jquery.min.map'
    ])
    .pipe(gulp.dest(assetRoot));
});

/*
 * concat and uglify scripts
 */
gulp.task('js', function(){
  return gulp.src([
    'scripts/**/*.js',
    'node_modules/scratchblocks2/build/scratchblocks2.js',
    'node_modules/scratchblocks2/src/translations.js',
    'node_modules/bootstrap/js/tooltip.js'
  ])
  .pipe(uglify())
  .pipe(addsrc.prepend([
    'node_modules/jquery/dist/jquery.min.js'
  ]))
  .pipe(concat('script.min.js'))
  .pipe(gulp.dest(assetRoot));
});

/*
 * metalsmith building
 */
gulp.task('build', build);
gulp.task('force-build', function(done){
  build(function(err){
    console.log('done called')
    done();
  }, { // build options
    force: true
  });
});
/*
 * dist - build all without serving
 */
gulp.task('dist', function(cb){
  // preferred way to this will change in gulp 4
  // see https://github.com/gulpjs/gulp/issues/96
  run('clean',
      ['assets', 'build', 'css', 'js'],
      'archive',
      'pdf', // do not include pdf in zip files
      cb);
});

/*
 * clean - remove files in build directory
 */
gulp.task('clean', function(cb){
  del([path.join(lessonRoot, 'build')], {force: true}, cb);
});

/*
 * pdf - generate pdfs of all htmls
 */
gulp.task('pdf', pdf);

/*
 * links - check for broken links
 */
gulp.task('links', checkLinks('http://localhost:3000/'));
gulp.task('prodlinks', checkLinks(config.productionCrawlStart));

/*
 * github webhook for automatic building
 */
gulp.task('github', function(cb){
  var github = githubhook({
    host: ghHost,
    port: ghPort,
    path: ghPath,
    secret: ghSecret
  });
  github.on('push:'+ghRepo, function(repo, ref, data) {
    deployProc = exec(ghPushCommand, function(err, stdout, stderr) {
      if(err!==null) {
        console.log(stderr);
      }
    });
  });
  github.listen();
});

/*
 * # DEFAULT TASK #
 * do metalsmith build
 * build, concat and minify styles
 * concat and uglify scripts
 * copy assets
 * serve build directory with livereload
 * watch files -> build and reload upon changes
 */
gulp.task('default', ['server'], function(){
  /*
   * ## WATCHES ##
   */
  // files which are built with metalsmith
  gulp.watch(path.join(lessonRoot, sourceFolder, '**'), ['build', reload]);
  gulp.watch(path.join(__dirname, 'templates', '**'), ['force-build', reload]);

  // styles
  gulp.watch(path.join(__dirname, 'styles', '**', '*'), ['css', reload]);

  // scripts
  gulp.watch(path.join(__dirname, 'scripts', '**'), ['js', reload]);

  // assets
  gulp.watch(path.join(__dirname, 'assets', '**'), ['assets', reload]);
});
<|endoftext|>


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

var autoprefixer = require("gulp-autoprefixer"),
    browserify = require("browserify"),
    combineMediaQueries = require("gulp-combine-media-queries"),
    imagemin = require("gulp-imagemin"),
    jshint = require("gulp-jshint"),
    less = require("gulp-less"),
    minifyCss = require("gulp-minify-css"),
    minifyHtml = require("gulp-minify-html"),
    pixrem = require("gulp-pixrem"),
    uglify = require("gulp-uglify"),
    vinylBuffer = require("vinyl-buffer"),
    vinylSourceStream = require("vinyl-source-stream");

gulp.task("copy-assets", function() {
    gulp.src("./node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("./src/css"));
});

gulp.task("imagemin", function() {
    gulp.src("./src/img/*")
        .pipe(imagemin())
        .pipe(gulp.dest("./dist/img"));
});

gulp.task("css", function() {
    gulp.src("./src/less/main.less")
        .pipe(less())
        .pipe(autoprefixer())
        .pipe(pixrem())
        .pipe(combineMediaQueries())
        .pipe(minifyCss({ noAdvanced: true }))
        .pipe(gulp.dest("./dist/css"));
});

gulp.task("test", function() {
    gulp.src("./src/js/main.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js", function() {
    return browserify("./src/js/main.js")
        .bundle()
        .pipe(vinylSourceStream("main.js"))
        .pipe(vinylBuffer())
        .pipe(uglify())
        .pipe(gulp.dest("./dist/js"));
});

gulp.task("html", function() {
    gulp.src("./src/**/*.{html,php}")
        .pipe(minifyHtml())
        .pipe(gulp.dest("./dist"));
});

gulp.task("default", ["test", "js", "css", "html"]);<commit_msg>Rolled the JSHint test step into the regular js workflow.<commit_after>var gulp = require("gulp");

var autoprefixer = require("gulp-autoprefixer"),
    browserify = require("browserify"),
    combineMediaQueries = require("gulp-combine-media-queries"),
    imagemin = require("gulp-imagemin"),
    jshint = require("gulp-jshint"),
    less = require("gulp-less"),
    minifyCss = require("gulp-minify-css"),
    minifyHtml = require("gulp-minify-html"),
    pixrem = require("gulp-pixrem"),
    uglify = require("gulp-uglify"),
    vinylBuffer = require("vinyl-buffer"),
    vinylSourceStream = require("vinyl-source-stream");

gulp.task("copy-assets", function() {
    gulp.src("./node_modules/normalize.css/normalize.css")
        .pipe(gulp.dest("./src/css"));
});

gulp.task("imagemin", function() {
    gulp.src("./src/img/*")
        .pipe(imagemin())
        .pipe(gulp.dest("./dist/img"));
});

gulp.task("css", function() {
    gulp.src("./src/less/main.less")
        .pipe(less())
        .pipe(autoprefixer())
        .pipe(pixrem())
        .pipe(combineMediaQueries())
        .pipe(minifyCss({ noAdvanced: true }))
        .pipe(gulp.dest("./dist/css"));
});

gulp.task("js", function() {
    gulp.src("./src/js/main.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));

    return browserify("./src/js/main.js")
        .bundle()
        .pipe(vinylSourceStream("main.js"))
        .pipe(vinylBuffer())
        .pipe(uglify())
        .pipe(gulp.dest("./dist/js"));
});

gulp.task("html", function() {
    gulp.src("./src/**/*.{html,php}")
        .pipe(minifyHtml())
        .pipe(gulp.dest("./dist"));
});

gulp.task("default", ["js", "css", "html"]);<|endoftext|>


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

gulp.task('cases', function () {
    var jsonify = require('./jsonify');
    var postcss = require('postcss');
    var cases   = path.join(__dirname, 'cases');
    var extra   = require('./extra-cases');
    fs.readdirSync(cases).forEach(function (i) {
        if ( path.extname(i) !== '.json' ) return;
        var name = path.basename(i, '.json');
        var css  = extra[name];
        if ( !css ) css = fs.readFileSync(path.join(cases, name + '.css'));
        var root = postcss.parse(css, { from: '/' + name });
        fs.writeFileSync(path.join(cases, i), jsonify(root) + '\n');
    });
});

gulp.task('lint', function () {
    var eslint = require('gulp-eslint');
    return gulp.src(['*.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('integration', function (done) {
    var real = require('./real');
    real(done, [['Browserhacks', 'http://browserhacks.com/']], function (css) {
        return { css: css };
    });
});

gulp.task('test', function () {
    var mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false }).pipe(mocha());
});

gulp.task('default', ['lint', 'integration']);
<commit_msg>Remove integration test, because it run too long in CI<commit_after>var gulp = require('gulp');
var path = require('path');
var fs   = require('fs');

gulp.task('cases', function () {
    var jsonify = require('./jsonify');
    var postcss = require('postcss');
    var cases   = path.join(__dirname, 'cases');
    var extra   = require('./extra-cases');
    fs.readdirSync(cases).forEach(function (i) {
        if ( path.extname(i) !== '.json' ) return;
        var name = path.basename(i, '.json');
        var css  = extra[name];
        if ( !css ) css = fs.readFileSync(path.join(cases, name + '.css'));
        var root = postcss.parse(css, { from: '/' + name });
        fs.writeFileSync(path.join(cases, i), jsonify(root) + '\n');
    });
});

gulp.task('lint', function () {
    var eslint = require('gulp-eslint');
    return gulp.src(['*.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('test', function () {
    var mocha = require('gulp-mocha');
    return gulp.src('test/*.js', { read: false }).pipe(mocha());
});

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


<commit_before>var gulp = require('gulp');
require('web-component-tester').initGulp(gulp);
<commit_msg>Delete gulpfile.js. Closes #34<commit_after><|endoftext|>


<commit_before>/* eslint-env node */

"use strict";

const fs_ = require("fs");
const path = require("path");

const gulp = require("gulp");
const log = require("fancy-log");
const gulpNewer = require("gulp-newer");
const jison = require("jison-gho");
const Promise = require("bluebird");
const del = require("del");
const touch = require("touch");
const es = require("event-stream");
const { ArgumentParser } = require("argparse");
const eslint = require("gulp-eslint");
const versync = require("versync");
const { spawn, execFile } = require("child-process-promise");
const { execFileAndReport, newer } = require("./gulptasks/util");

const fs = Promise.promisifyAll(fs_);

//
// This script accepts configuration options from 3 places, in
// decreasing order of precedence:
//
// 1. command line,
// 2. configuration file,
// 3. internal default.
//

// Try to load local configuration options.
let localConfig = {};
try {
  // eslint-disable-next-line global-require, import/no-unresolved
  localConfig = require("./gulp.local");
}
catch (e) {
  if (e.code !== "MODULE_NOT_FOUND") {
    throw e;
  }
}

const parser = new ArgumentParser({ addHelp: true });

// We have this here so that the help message is more useful than
// without. At the same time, this positional argument is not
// *required*.
parser.addArgument(["target"], {
  help: "Target to execute.",
  nargs: "?",
  defaultValue: "default",
});

parser.addArgument(["--doc-private"], {
  help: "document private functions.",
  type: Boolean,
  action: "storeTrue",
  defaultValue: localConfig.doc_private,
});

parser.addArgument(["--no-doc-private"], {
  help: "do not document private functions.",
  type: Boolean,
  action: "storeFalse",
  dest: "doc_private",
  defaultValue: localConfig.doc_private,
});

parser.addArgument(["--mocha-grep"], {
  // We do not have a default for this one.
  help: "A pattern to pass to mocha to select tests.",
});

parser.addArgument(["--browsers"], {
  help: "The list of browsers to use for Karma.",
  nargs: "+",
});

const options = parser.parseArgs(process.argv.slice(2));

function runTsc(tsconfigPath, dest) {
  return execFileAndReport("./node_modules/.bin/tsc", ["-p", tsconfigPath,
                                                       "--outDir", dest]);
}

function runTslint(tsconfig, tslintConfig) {
  return execFileAndReport(
    "./node_modules/.bin/tslint",
    ["--format", "verbose", "--project", tsconfig, "-c", tslintConfig],
    { capture: ["stdout", "stderr"] });
}

function tsc() {
  return runTsc("tsconfig.json", "build/dist/lib");
}

function runEslint() {
  return gulp.src([
    "*.js",
    "bin/**/*.js",
    "lib/**/*.js",
    "gulptasks/**/*.js",
    "test/**/*.js",
    "!test/salve-convert/**/*.js",
    "misc/**/*.js",
    "!test/**/simplified-rng*.js",
  ])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

function tslint() {
  return runTslint("tsconfig.json", "tslint.json");
}

function copySrc() {
  const dest = "build/dist/";
  return gulp.src([
    "package.json",
    "README.md",
    "bin/*",
    "lib/**/*.d.ts",
    "lib/**/*.xsl",
  ], { base: "." })
    .pipe(gulpNewer(dest))
    .pipe(gulp.dest(dest));
}

function webpack(config) {
  const args = ["--mode", "production", "--progress", "--color"];
  if (config) {
    args.push("--config", config);
  }

  return spawn("./node_modules/.bin/webpack", args, { stdio: "inherit" });
}

function runKarma(localOptions) {
  // We cannot let it be set to ``null`` or ``undefined``.
  if (options.browsers) {
    localOptions = localOptions.concat("--browsers", options.browsers);
  }
  return spawn("./node_modules/.bin/karma", localOptions, { stdio: "inherit" });
}

function karma() {
  return runKarma(["start", "--single-run"]);
}

function mocha() {
  return spawn(
    "./node_modules/.bin/mocha",
    options.mocha_grep ? ["--grep", options.mocha_grep] :
      [],
    { stdio: "inherit" });
}

// === gulp tasks ===

gulp.task("lint", gulp.parallel(tslint, runEslint));

gulp.task("jison", () => {
  const dest = "build/dist/lib/salve/datatypes";
  return gulp.src("lib/salve/datatypes/regexp.jison")
    .pipe(gulpNewer(`${dest}/regexp.js`))
  // eslint-disable-next-line array-callback-return
    .pipe(es.map((data, callback) => {
      const generated = new jison.Generator(data.contents.toString(), {
        moduleType: "commonjs",
        // Override the default main created by Jison. This module cannot ever
        // be used as a main script. And the default that Jison uses does
        // `require("fs")` which causes problems.
        moduleMain: function main() {
          throw new Error("this module cannot be used as main");
        },
      }).generate();
      data.contents = Buffer.from(generated);
      data.path = data.path.replace(/.jison$/, ".js");
      callback(null, data);
    }))
    .pipe(gulp.dest(dest));
});

gulp.task("copy", gulp.series(copySrc,
                              () => fs.writeFileAsync("build/dist/.npmignore",
                                                      "bin/parse.js")));
gulp.task("convert-schema",
          // We have to create the directory before converting.
          () => execFileAndReport("mkdir", ["-p",
                                            "build/dist/lib/salve/schemas/"])
          // We have to write an empty file so that salve-convert will at least
          // not crash due to the file being missing.
          .then(() => fs.writeFileAsync(
            "build/dist/lib/salve/schemas/relaxng.json", "{}"))
          // We use the previous version of salve to convert the
          // validation schema.
          .then(() => execFileAndReport(
            "./build/dist/bin/salve-convert",
            ["--validator=none", "lib/salve/schemas/relaxng.rng",
             "build/dist/lib/salve/schemas/relaxng.json"])));

gulp.task("default", gulp.series(gulp.parallel(tsc, "copy", "jison"),
                                 "convert-schema",
                                 () => webpack()));

gulp.task("karma", gulp.series("default", karma));

let packname;

gulp.task("pack", gulp.series(
  "default",
  () => execFile("npm", ["pack"], { cwd: "build/dist" })
    .then((result) => {
      const { stdout } = result;
      packname = stdout.trim();
      return fs.renameAsync(`build/dist/${packname}`, `build/${packname}`);
    })));

gulp.task("install_test", gulp.series(
  "pack",
  Promise.coroutine(function *install() {
    const testDir = "build/install_dir";
    yield del(testDir);
    yield fs.mkdirAsync(testDir);
    yield fs.mkdirAsync(path.join(testDir, "node_modules"));
    yield execFile("npm", ["install", `../${packname}`, "sax", "@types/sax"],
          { cwd: testDir });
    let module = yield fs.readFileAsync("lib/salve/parse.ts");
    module = module.toString();
    module = module.replace("./validate", "salve");
    yield fs.writeFileAsync(path.join(testDir, "parse.ts"), module);
    yield execFileAndReport("../../node_modules/.bin/tsc",
                            ["--lib", "es2015,dom", "--esModuleInterop",
                             "parse.ts"],
                            { cwd: testDir });
    yield del(testDir);
  })));

gulp.task("publish", gulp.series("install_test",
                                 () => execFile("npm", ["publish", packname],
                                                { cwd: "build" })));

// This task also needs to check the hash of the latest commit because typedoc
// generates links to source based on the latest commit in effect when it is
// run. So if a commit happened between the time the doc was generated last, and
// now, we need to regenerate the docs.
gulp.task("typedoc",
          gulp.series(
            tslint,
            Promise.coroutine(function *task() {
              const sources = ["lib/**/*.ts"];
              const stamp = "build/api.stamp";
              const hashPath = "./build/typedoc.hash.txt";

              const prelim = yield Promise.all(
                [fs.readFileAsync(hashPath).then(hash => hash.toString())
                 .catch(() => undefined),
                 execFile("git", ["rev-parse", "--short", "HEAD"])
                 .then(result => result.stdout),
                ]);

              const savedHash = prelim[0];
              const currentHash = prelim[1][0];

              if ((currentHash === savedHash) &&
                  !(yield newer(sources, stamp))) {
                log("No change, skipping typedoc.");
                return;
              }

              const { version } = JSON.parse(fs.readFileSync("package.json"));
              const tsoptions = [
                "--out", `./build/api/salve/${version}`,
                "--name", "salve",
                "--tsconfig", "./tsconfig.json",
                "--listInvalidSymbolLinks",
              ];

              if (!options.doc_private) {
                tsoptions.push("--excludePrivate");
              }

              yield spawn("./node_modules/.bin/typedoc", tsoptions,
                          { stdio: "inherit" });

              yield Promise.all([fs.writeFileAsync(hashPath, currentHash),
                                 touch(stamp)]);
            })));

gulp.task("doc", gulp.task("typedoc"));

gulp.task("gh-pages-build", gulp.series("typedoc", () => {
  const dest = "gh-pages-build";
  return gulp.src("**/*", { cwd: "build/api/" })
    .pipe(gulpNewer(dest))
    .pipe(gulp.dest(dest));
}));

gulp.task("versync", () => versync.run({
  onMessage: log,
}));

gulp.task("mocha", gulp.series("default", mocha));

gulp.task("test",
          gulp.series("default",
                      gulp.parallel("versync", mocha, karma, "lint")));

gulp.task("clean", () => del(["build", "gh-pages-build"]));
<commit_msg>build: there are no js files in the lib directory anymore<commit_after>/* eslint-env node */

"use strict";

const fs_ = require("fs");
const path = require("path");

const gulp = require("gulp");
const log = require("fancy-log");
const gulpNewer = require("gulp-newer");
const jison = require("jison-gho");
const Promise = require("bluebird");
const del = require("del");
const touch = require("touch");
const es = require("event-stream");
const { ArgumentParser } = require("argparse");
const eslint = require("gulp-eslint");
const versync = require("versync");
const { spawn, execFile } = require("child-process-promise");
const { execFileAndReport, newer } = require("./gulptasks/util");

const fs = Promise.promisifyAll(fs_);

//
// This script accepts configuration options from 3 places, in
// decreasing order of precedence:
//
// 1. command line,
// 2. configuration file,
// 3. internal default.
//

// Try to load local configuration options.
let localConfig = {};
try {
  // eslint-disable-next-line global-require, import/no-unresolved
  localConfig = require("./gulp.local");
}
catch (e) {
  if (e.code !== "MODULE_NOT_FOUND") {
    throw e;
  }
}

const parser = new ArgumentParser({ addHelp: true });

// We have this here so that the help message is more useful than
// without. At the same time, this positional argument is not
// *required*.
parser.addArgument(["target"], {
  help: "Target to execute.",
  nargs: "?",
  defaultValue: "default",
});

parser.addArgument(["--doc-private"], {
  help: "document private functions.",
  type: Boolean,
  action: "storeTrue",
  defaultValue: localConfig.doc_private,
});

parser.addArgument(["--no-doc-private"], {
  help: "do not document private functions.",
  type: Boolean,
  action: "storeFalse",
  dest: "doc_private",
  defaultValue: localConfig.doc_private,
});

parser.addArgument(["--mocha-grep"], {
  // We do not have a default for this one.
  help: "A pattern to pass to mocha to select tests.",
});

parser.addArgument(["--browsers"], {
  help: "The list of browsers to use for Karma.",
  nargs: "+",
});

const options = parser.parseArgs(process.argv.slice(2));

function runTsc(tsconfigPath, dest) {
  return execFileAndReport("./node_modules/.bin/tsc", ["-p", tsconfigPath,
                                                       "--outDir", dest]);
}

function runTslint(tsconfig, tslintConfig) {
  return execFileAndReport(
    "./node_modules/.bin/tslint",
    ["--format", "verbose", "--project", tsconfig, "-c", tslintConfig],
    { capture: ["stdout", "stderr"] });
}

function tsc() {
  return runTsc("tsconfig.json", "build/dist/lib");
}

function runEslint() {
  return gulp.src([
    "*.js",
    "bin/**/*.js",
    "gulptasks/**/*.js",
    "test/**/*.js",
    "!test/salve-convert/**/*.js",
    "misc/**/*.js",
    "!test/**/simplified-rng*.js",
  ])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

function tslint() {
  return runTslint("tsconfig.json", "tslint.json");
}

function copySrc() {
  const dest = "build/dist/";
  return gulp.src([
    "package.json",
    "README.md",
    "bin/*",
    "lib/**/*.d.ts",
    "lib/**/*.xsl",
  ], { base: "." })
    .pipe(gulpNewer(dest))
    .pipe(gulp.dest(dest));
}

function webpack(config) {
  const args = ["--mode", "production", "--progress", "--color"];
  if (config) {
    args.push("--config", config);
  }

  return spawn("./node_modules/.bin/webpack", args, { stdio: "inherit" });
}

function runKarma(localOptions) {
  // We cannot let it be set to ``null`` or ``undefined``.
  if (options.browsers) {
    localOptions = localOptions.concat("--browsers", options.browsers);
  }
  return spawn("./node_modules/.bin/karma", localOptions, { stdio: "inherit" });
}

function karma() {
  return runKarma(["start", "--single-run"]);
}

function mocha() {
  return spawn(
    "./node_modules/.bin/mocha",
    options.mocha_grep ? ["--grep", options.mocha_grep] :
      [],
    { stdio: "inherit" });
}

// === gulp tasks ===

gulp.task("lint", gulp.parallel(tslint, runEslint));

gulp.task("jison", () => {
  const dest = "build/dist/lib/salve/datatypes";
  return gulp.src("lib/salve/datatypes/regexp.jison")
    .pipe(gulpNewer(`${dest}/regexp.js`))
  // eslint-disable-next-line array-callback-return
    .pipe(es.map((data, callback) => {
      const generated = new jison.Generator(data.contents.toString(), {
        moduleType: "commonjs",
        // Override the default main created by Jison. This module cannot ever
        // be used as a main script. And the default that Jison uses does
        // `require("fs")` which causes problems.
        moduleMain: function main() {
          throw new Error("this module cannot be used as main");
        },
      }).generate();
      data.contents = Buffer.from(generated);
      data.path = data.path.replace(/.jison$/, ".js");
      callback(null, data);
    }))
    .pipe(gulp.dest(dest));
});

gulp.task("copy", gulp.series(copySrc,
                              () => fs.writeFileAsync("build/dist/.npmignore",
                                                      "bin/parse.js")));
gulp.task("convert-schema",
          // We have to create the directory before converting.
          () => execFileAndReport("mkdir", ["-p",
                                            "build/dist/lib/salve/schemas/"])
          // We have to write an empty file so that salve-convert will at least
          // not crash due to the file being missing.
          .then(() => fs.writeFileAsync(
            "build/dist/lib/salve/schemas/relaxng.json", "{}"))
          // We use the previous version of salve to convert the
          // validation schema.
          .then(() => execFileAndReport(
            "./build/dist/bin/salve-convert",
            ["--validator=none", "lib/salve/schemas/relaxng.rng",
             "build/dist/lib/salve/schemas/relaxng.json"])));

gulp.task("default", gulp.series(gulp.parallel(tsc, "copy", "jison"),
                                 "convert-schema",
                                 () => webpack()));

gulp.task("karma", gulp.series("default", karma));

let packname;

gulp.task("pack", gulp.series(
  "default",
  () => execFile("npm", ["pack"], { cwd: "build/dist" })
    .then((result) => {
      const { stdout } = result;
      packname = stdout.trim();
      return fs.renameAsync(`build/dist/${packname}`, `build/${packname}`);
    })));

gulp.task("install_test", gulp.series(
  "pack",
  Promise.coroutine(function *install() {
    const testDir = "build/install_dir";
    yield del(testDir);
    yield fs.mkdirAsync(testDir);
    yield fs.mkdirAsync(path.join(testDir, "node_modules"));
    yield execFile("npm", ["install", `../${packname}`, "sax", "@types/sax"],
          { cwd: testDir });
    let module = yield fs.readFileAsync("lib/salve/parse.ts");
    module = module.toString();
    module = module.replace("./validate", "salve");
    yield fs.writeFileAsync(path.join(testDir, "parse.ts"), module);
    yield execFileAndReport("../../node_modules/.bin/tsc",
                            ["--lib", "es2015,dom", "--esModuleInterop",
                             "parse.ts"],
                            { cwd: testDir });
    yield del(testDir);
  })));

gulp.task("publish", gulp.series("install_test",
                                 () => execFile("npm", ["publish", packname],
                                                { cwd: "build" })));

// This task also needs to check the hash of the latest commit because typedoc
// generates links to source based on the latest commit in effect when it is
// run. So if a commit happened between the time the doc was generated last, and
// now, we need to regenerate the docs.
gulp.task("typedoc",
          gulp.series(
            tslint,
            Promise.coroutine(function *task() {
              const sources = ["lib/**/*.ts"];
              const stamp = "build/api.stamp";
              const hashPath = "./build/typedoc.hash.txt";

              const prelim = yield Promise.all(
                [fs.readFileAsync(hashPath).then(hash => hash.toString())
                 .catch(() => undefined),
                 execFile("git", ["rev-parse", "--short", "HEAD"])
                 .then(result => result.stdout),
                ]);

              const savedHash = prelim[0];
              const currentHash = prelim[1][0];

              if ((currentHash === savedHash) &&
                  !(yield newer(sources, stamp))) {
                log("No change, skipping typedoc.");
                return;
              }

              const { version } = JSON.parse(fs.readFileSync("package.json"));
              const tsoptions = [
                "--out", `./build/api/salve/${version}`,
                "--name", "salve",
                "--tsconfig", "./tsconfig.json",
                "--listInvalidSymbolLinks",
              ];

              if (!options.doc_private) {
                tsoptions.push("--excludePrivate");
              }

              yield spawn("./node_modules/.bin/typedoc", tsoptions,
                          { stdio: "inherit" });

              yield Promise.all([fs.writeFileAsync(hashPath, currentHash),
                                 touch(stamp)]);
            })));

gulp.task("doc", gulp.task("typedoc"));

gulp.task("gh-pages-build", gulp.series("typedoc", () => {
  const dest = "gh-pages-build";
  return gulp.src("**/*", { cwd: "build/api/" })
    .pipe(gulpNewer(dest))
    .pipe(gulp.dest(dest));
}));

gulp.task("versync", () => versync.run({
  onMessage: log,
}));

gulp.task("mocha", gulp.series("default", mocha));

gulp.task("test",
          gulp.series("default",
                      gulp.parallel("versync", mocha, karma, "lint")));

gulp.task("clean", () => del(["build", "gh-pages-build"]));
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var watchify = require('watchify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');

// add custom browserify options here
var customOpts = {
  entries: ['./js/maze.js'],
  debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  return b.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
    // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
       // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist'));
}

// watch files for changes and reload
gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: '.'
    }
  });

  gulp.watch(['*.html', 'css/**/*.css', 'js/**/*.js'], {cwd: '.'}, browserSync.reload);
});

gulp.task('default', ['js', 'serve']);
<commit_msg>코드 포매팅 (공백 조정)<commit_after>'use strict';

var gulp = require('gulp');
var watchify = require('watchify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');

// add custom browserify options here
var customOpts = {
  entries: ['./js/maze.js'],
  debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle);  // on any dep update, runs the bundler
b.on('log', gutil.log);  // output build logs to terminal

function bundle() {
  return b.bundle()
  // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
  // optional, remove if you don't need to buffer file contents
    .pipe(buffer())
  // optional, remove if you dont want sourcemaps
    .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
  // Add transformation tasks to the pipeline here.
    .pipe(sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./dist'));
}

// watch files for changes and reload
gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: '.'
    }
  });

  gulp.watch(['*.html', 'css/**/*.css', 'js/**/*.js'], {cwd: '.'}, browserSync.reload);
});

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


<commit_before>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
require('babel-core/register');
// testing
var mocha = require('gulp-mocha');

/**
 *
 * @param outFolder string
 * @param outFileBase string
 * @return {*}
 */
function runBabelOnFolder(outFolder, outFileBase) {
    if(outFolder !== '' && outFolder.slice(-1) !== '/'){
        outFolder += '/';
    }
    return gulp.src('app/Resources/client/jsx/'+outFolder+outFileBase+'/*.js?(x)')
        .pipe(babel({
            presets: ['es2015', 'react']
        }))
        .pipe(concat(outFileBase+'.js'))
        .pipe(gulp.dest('web/assets/js/'+outFolder));
}

gulp.task('babel-helpers', function() {
    return runBabelOnFolder('', 'helpers');
});

gulp.task('babel-base', function() {
    return runBabelOnFolder('', 'base');
});

gulp.task('babel-project-details', function() {
    return runBabelOnFolder('project', 'details');
});

gulp.task('babel-project-trait-details', function() {
    return runBabelOnFolder('project', 'traitDetails');
});

gulp.task('babel-trait-browse', function() {
    return runBabelOnFolder('trait', 'browse');
});

gulp.task('babel-organism-details', function() {
    return runBabelOnFolder('organism', 'details');
});

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

gulp.task('sass', function () {
  return gulp.src('app/Resources/client/scss/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('style.css'))
    .pipe(sourcemaps.write('.', {includeContent: false}))
    .pipe(gulp.dest('web/assets/css'));
});

gulp.task('sassLint', function() {
  gulp.src('web/assets/scss/*.s+(a|c)ss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
});

gulp.task('babel', [
    'babel-helpers',
    'babel-base',
    'babel-project-details',
    'babel-project-trait-details',
    'babel-trait-browse',
    'babel-organism-details'
], function () {
});

gulp.task('css', ['sassLint','sass'], function () {
});

gulp.task('default', ['css','babel','test'], function() {
  // place code for your default task here
});

<commit_msg>Update gulp tasks<commit_after>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var sassLint = require('gulp-sass-lint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
require('babel-core/register');
// testing
var mocha = require('gulp-mocha');

/**
 *
 * @param outFolder string
 * @param outFileBase string
 * @return {*}
 */
function runBabelOnFolder(outFolder, outFileBase) {
    if(outFolder !== '' && outFolder.slice(-1) !== '/'){
        outFolder += '/';
    }
    return gulp.src('app/Resources/client/jsx/'+outFolder+outFileBase+'/*.js?(x)')
        .pipe(babel({
            presets: ['es2015', 'react']
        }))
        .pipe(concat(outFileBase+'.js'))
        .pipe(gulp.dest('web/assets/js/'+outFolder));
}

gulp.task('babel-helpers', function() {
    return runBabelOnFolder('', 'helpers');
});

gulp.task('babel-base', function() {
    return runBabelOnFolder('', 'base');
});

gulp.task('babel-project-details', function() {
    return runBabelOnFolder('project', 'details');
});

gulp.task('babel-project-helpers', function() {
    return runBabelOnFolder('project', 'helpers');
});

gulp.task('babel-project-trait-details', function() {
    return runBabelOnFolder('project', 'traitDetails');
});

gulp.task('babel-trait-browse', function() {
    return runBabelOnFolder('trait', 'browse');
});

gulp.task('babel-organism-details', function() {
    return runBabelOnFolder('organism', 'details');
});

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

gulp.task('sass', function () {
  return gulp.src('app/Resources/client/scss/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('style.css'))
    .pipe(sourcemaps.write('.', {includeContent: false}))
    .pipe(gulp.dest('web/assets/css'));
});

gulp.task('sassLint', function() {
  gulp.src('web/assets/scss/*.s+(a|c)ss')
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
});

gulp.task('babel', [
    'babel-helpers',
    'babel-base',
    'babel-project-details',
    'babel-project-helpers',
    'babel-project-trait-details',
    'babel-trait-browse',
    'babel-organism-details'
], function () {
});

gulp.task('css', ['sassLint','sass'], function () {
});

gulp.task('default', ['css','babel','test'], function() {
  // place code for your default task here
});

<|endoftext|>


<commit_before>'use strict';

// =============================
// ------ Import Plugins -------
// =============================

var gulp    = require('gulp');
var bower   = require('gulp-bower');
var watch   = require('gulp-watch');
var postcss = require('gulp-postcss');
var sass    = require('gulp-sass');
var rigger  = require('gulp-rigger');
var cssmin  = require('gulp-clean-css');
var filter  = require('gulp-filter');
var csscomb = require('gulp-csscomb');
var zip     = require('gulp-zip');
var plumber = require('gulp-plumber');
var util    = require('gulp-util');

var autoprefixer = require('autoprefixer');
var rimraf = require('rimraf');
var browserSync = require("browser-sync").create();
var reload = browserSync.reload;

// =============================
// -------- Functions ----------
// =============================

// Error handler for gulp-plumber
function errorHandler(err) {
    util.log([ (err.name + ' in ' + err.plugin).bold.red, '', err.message, '' ].join('\n'));

    this.emit('end');
}

function correctNumber(number) {
    return number < 10 ? '0' + number : number;
}

// Return timestamp
function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = correctNumber(now.getMonth() + 1);
    var day = correctNumber(now.getDate());
    var hours = correctNumber(now.getHours());
    var minutes = correctNumber(now.getMinutes());
    return year + '-' + month + '-' + day + '-' + hours + minutes;
};

// =============================
// ------- Add var path --------
// =============================

var path = {

    build: {
        html: 'web/',
        js: 'web/js/',
        css: 'web/css/',
        img: 'web/images/',
        fonts: 'web/fonts/',
        libs: 'web/libs/'
    },

    src: {
        html: 'src/*.html',                 // Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js: 'src/js/common.js',             // В скриптах нам понадобятся только common файл
        style: 'src/sass/style.scss',       // В стилях берем два файла style и media
        media: 'src/sass/media.scss',
        img: 'src/images/**/*.*',           // Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts: 'src/fonts/**/*.*',
        libs: './bower_components/'
    },

    watch: {
        html: 'src/**/*.html',
        js: 'src/js/**/*.js',
        style: 'src/sass/**/*.scss',
        img: 'src/images/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },

    clean: './web'
};

// =============================
// ---- Add plugins options ----
// =============================

var option = {

    browserSync: {
        server: './web',
        tunnel: false,
        host: 'localhost',
        port: 9000,
        logPrefix: "lucas"
    },

    plumber: {
        errorHandler: errorHandler
    },

    sass: {
        outputStyle: 'expanded'
    },

    postcss: [
        autoprefixer({
            cascade: true
        }),
    ],

    csscomb: 'csscomb.json',

}

// =============================
// --------- Sub tasks ---------
// =============================

// Удаление скомпилированных файлов
gulp.task('clean', function (cb) {
    return rimraf(path.clean, cb);
});

// Запуск сервера с livereload
gulp.task('serve', function () {
    return browserSync.init(option.browserSync);
});

// Загрузка плагинов из Bower
gulp.task('bower', function() {
    return bower();
});

// =============================
// ------- Build tasks ---------
// =============================

gulp.task('build:html', function () {
    gulp.src(path.src.html)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.html))
        .pipe(reload({stream: true}));
});

gulp.task('build:js', function () {
    gulp.src(path.src.js)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.js))
        .pipe(reload({stream: true}));
});

gulp.task('build:css', function () {
    // style.css
    gulp.src(path.src.style)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));

    // media.css
    gulp.src(path.src.media)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));
});

gulp.task('build:img', function () {
    gulp.src(path.src.img) // Выберем наши картинки
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.img)) // И бросим в build
        .pipe(reload({stream: true}));
});

gulp.task('build:fonts', function() {
    gulp.src(path.src.fonts)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.fonts))
});

gulp.task('build:zip', function() {
    var datetime = '-' + getDateTime();
    var zipName = 'web' + datetime + '.zip';

    gulp.src('web/**/*.*')
        .pipe(zip(zipName))
        .pipe(gulp.dest('dist'));
});

// =============================
// ------- Watch task ----------
// =============================

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        gulp.start('build:html');
    });

    watch([path.watch.style], function(event, cb) {
        gulp.start('build:css');
    });

    watch([path.watch.js], function(event, cb) {
        gulp.start('build:js');
    });

    watch([path.watch.img], function(event, cb) {
        gulp.start('build:img');
    });

    watch([path.watch.fonts], function(event, cb) {
        gulp.start('build:fonts');
    });
});

// =============================
// -------- Main task ----------
// =============================

gulp.task('vendor', [
    'bower',
    'filter'
]);

gulp.task('zip', [
    'build',
    'build:zip'
]);

gulp.task('build', [
    'build:html',
    'build:css',
    'build:js',
    'build:img',
    'build:fonts'
]);

gulp.task('dev', [
    'build',
    'watch',
    'serve'
]);

// Default task
gulp.task('default', ['dev']);

// TODO: Разобрать таск и переписать
// Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
    // Настраиваем фильтры для файлов
    const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
    const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

    // Для нормальных плагинов отработает этот кусок кода
    const stream = gulp.src([
        'bower_components/**/*.min.*',
        'bower_components/**/fonts/*',
        'bower_components/**/*.css',
        '!bower_components/**/*.map'
    ])

    // Фильтруем содержимое на наличие js и css
    .pipe(jsFilter)
    .pipe(cssFilter)
    // run them through a plugin
    .pipe(gulp.dest('dist'));

    // Вываливаем в билд
    jsFilter.restore.pipe(gulp.dest(path.build.libs));

    return stream;
});
<commit_msg>some small fix<commit_after>'use strict';

// =============================
// ------ Import Plugins -------
// =============================

var gulp    = require('gulp');
var bower   = require('gulp-bower');
var watch   = require('gulp-watch');
var postcss = require('gulp-postcss');
var sass    = require('gulp-sass');
var rigger  = require('gulp-rigger');
var cssmin  = require('gulp-clean-css');
var filter  = require('gulp-filter');
var csscomb = require('gulp-csscomb');
var zip     = require('gulp-zip');
var plumber = require('gulp-plumber');
var util    = require('gulp-util');

var autoprefixer = require('autoprefixer');
var browserSync  = require("browser-sync").create();
var rimraf       = require('rimraf');
var reload       = browserSync.reload;

// =============================
// -------- Functions ----------
// =============================

// Error handler for gulp-plumber
function errorHandler(err) {
    util.log([ (err.name + ' in ' + err.plugin).bold.red, '', err.message, '' ].join('\n'));

    this.emit('end');
}

function correctNumber(number) {
    return number < 10 ? '0' + number : number;
}

// Return timestamp
function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = correctNumber(now.getMonth() + 1);
    var day = correctNumber(now.getDate());
    var hours = correctNumber(now.getHours());
    var minutes = correctNumber(now.getMinutes());
    return year + '-' + month + '-' + day + '-' + hours + minutes;
};

// =============================
// ------- Add var path --------
// =============================

var path = {

    build: {
        html: 'web/',
        js: 'web/js/',
        css: 'web/css/',
        img: 'web/images/',
        fonts: 'web/fonts/',
        libs: 'web/libs/'
    },

    src: {
        html: 'src/*.html',                 // Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js: 'src/js/common.js',
        style: 'src/sass/style.scss',
        media: 'src/sass/media.scss',
        img: 'src/images/**/*.*',           // Синтаксис images/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts: 'src/fonts/**/*.*',
        libs: './bower_components/'
    },

    watch: {
        html: 'src/**/*.html',
        js: 'src/js/**/*.js',
        style: 'src/sass/**/*.scss',
        img: 'src/images/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },

    clean: './web'
};

// =============================
// ---- Add plugins options ----
// =============================

var option = {

    browserSync: {
        server: './web',
        tunnel: false,
        host: 'localhost',
        port: 9000,
        logPrefix: "lucas"
    },

    plumber: {
        errorHandler: errorHandler
    },

    sass: {
        outputStyle: 'expanded'
    },

    postcss: [
        autoprefixer({
            cascade: true
        }),
    ],

    csscomb: 'csscomb.json',

}

// =============================
// --------- Sub tasks ---------
// =============================

// Удаление скомпилированных файлов
gulp.task('clean', function (cb) {
    return rimraf(path.clean, cb);
});

// Запуск сервера с livereload
gulp.task('serve', function () {
    return browserSync.init(option.browserSync);
});

// Загрузка плагинов из Bower
gulp.task('bower', function() {
    return bower();
});

// =============================
// ------- Build tasks ---------
// =============================

gulp.task('build:html', function () {
    gulp.src(path.src.html)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.html))
        .pipe(reload({stream: true}));
});

gulp.task('build:js', function () {
    gulp.src(path.src.js)
        .pipe(plumber(option.plumber))
        .pipe(rigger())
        .pipe(gulp.dest(path.build.js))
        .pipe(reload({stream: true}));
});

gulp.task('build:css', function () {
    // style.css
    gulp.src(path.src.style)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));

    // media.css
    gulp.src(path.src.media)
        .pipe(plumber(option.plumber))
        .pipe(sass(option.sass))
        .pipe(postcss(option.postcss))
        .pipe(csscomb(option.csscomb))
        .pipe(gulp.dest(path.build.css))
        .pipe(reload({stream: true}));
});

gulp.task('build:img', function () {
    gulp.src(path.src.img)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.img))
        .pipe(reload({stream: true}));
});

gulp.task('build:fonts', function() {
    gulp.src(path.src.fonts)
        .pipe(plumber(option.plumber))
        .pipe(gulp.dest(path.build.fonts))
});

gulp.task('build:zip', function() {
    var datetime = '-' + getDateTime();
    var zipName = 'web' + datetime + '.zip';

    gulp.src('web/**/*.*')
        .pipe(zip(zipName))
        .pipe(gulp.dest('dist'));
});

// =============================
// ------- Watch task ----------
// =============================

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        gulp.start('build:html');
    });

    watch([path.watch.style], function(event, cb) {
        gulp.start('build:css');
    });

    watch([path.watch.js], function(event, cb) {
        gulp.start('build:js');
    });

    watch([path.watch.img], function(event, cb) {
        gulp.start('build:img');
    });

    watch([path.watch.fonts], function(event, cb) {
        gulp.start('build:fonts');
    });
});

// =============================
// -------- Main task ----------
// =============================

gulp.task('vendor', [
    'bower',
    'filter'
]);

gulp.task('zip', [
    'build',
    'build:zip'
]);

gulp.task('build', [
    'build:html',
    'build:css',
    'build:js',
    'build:img',
    'build:fonts'
]);

gulp.task('dev', [
    'build',
    'watch',
    'serve'
]);

// Default task
gulp.task('default', ['dev']);

// TODO: Разобрать таск и переписать
// Фильтруем библиотеки и вынимаем только нужные файлы
gulp.task('filter', function() {
    // Настраиваем фильтры для файлов
    const jsFilter = filter(['*.js', '!src/vendor'], {restore: true, passthrough: false});
    const cssFilter = filter(['*.css', '!src/vendor'], {restore: true, passthrough: false});

    // Для нормальных плагинов отработает этот кусок кода
    const stream = gulp.src([
        'bower_components/**/*.min.*',
        'bower_components/**/fonts/*',
        'bower_components/**/*.css',
        '!bower_components/**/*.map'
    ])

    // Фильтруем содержимое на наличие js и css
    .pipe(jsFilter)
    .pipe(cssFilter)
    // run them through a plugin
    .pipe(gulp.dest('dist'));

    // Вываливаем в билд
    jsFilter.restore.pipe(gulp.dest(path.build.libs));

    return stream;
});
<|endoftext|>


<commit_before>'use strict';
//node modules
var path = require('path');

// node_modules modules
var _ = require('lodash');
var browserify  = require("browserify");
var browserSync = require("browser-sync");
var bsreload = browserSync.reload;
var del = require('del');
var mergeStream = require('merge-stream');
var q = require('q');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

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

// kickstart modules
var assemble = require('kickstart-assemble');

// user project configuration
var config = require('./config.js');

// error handler
var onError = function (err, cb) {
    plugins.util.beep();
    plugins.util.log(plugins.util.colors.red(err));

    if (typeof this.emit === 'function') this.emit('end');
};

// clean task
gulp.task('clean', function (cb) {
    return del([
        config.dest.base,
        'styleguide'
    ], cb);
});

// styles task
gulp.task('styles', function () {
    return gulp.src(config.src.styles)
        .pipe(plugins.plumber({ errorHandler: onError }))
        .pipe(plugins.sass(config.sass.settings))
        .pipe(plugins.cssUrlAdjuster({
            prepend: config.dest.images
        }))
        .pipe(plugins.if(!config.dev, plugins.combineMediaQueries()))
        .pipe(plugins.autoprefixer(config.sass.autoprefixer))
        .pipe(plugins.if(!config.dev, plugins.csso()))
        .pipe(gulp.dest(config.dest.styles))
        .pipe(plugins.if(config.dev, bsreload({ stream: true })));
});

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

    var browserifyTask = function () {

        var browserifyThis = function (bundleConfig) {
            if (config.dev) {
                _.extend(config.src.scriptBundles, watchify.args, { debug: true });

                bundleConfig = _.omit(bundleConfig, ['external', 'require']);
            }

            var b = browserify(bundleConfig);

            var bundle = function () {

                return b
                    .bundle()
                    .on('error', onError)
                    .pipe(source(bundleConfig.outputName))
                    .pipe(gulp.dest(bundleConfig.dest))
                    .pipe(plugins.if(config.dev, bsreload({ stream: true })));
            };

            if (config.dev) {
                b = watchify(b);
                b.on('update', bundle);
            } else {
                if (bundleConfig.require) b.require(bundleConfig.require);
                if (bundleConfig.external) b.external(bundleConfig.external);
            }

            return bundle();
        };

        return mergeStream.apply(gulp, _.map(config.scriptBundles, browserifyThis));

    }

    return browserifyTask();

});

// images task
gulp.task('images', function () {
    return gulp.src(config.src.images)
        .pipe(plugins.changed(config.dest.images))
        .pipe(plugins.if(!config.dev, plugins.imagemin(config.images)))
        .pipe(gulp.dest(config.dest.images))
        .pipe(plugins.if(config.dev, bsreload({ stream: true })));
});

// fonts task
gulp.task('fonts', function () {
    return gulp.src(config.src.fonts)
        .pipe(gulp.dest(config.dest.fonts));
});

// copy extra files task
gulp.task('copy:extras', function () {
    return gulp.src('./src/public/*.{ico,txt}')
        .pipe(gulp.dest(config.dest.base));
});

gulp.task('copy:samples', function () {
    return gulp.src('./src/public/samples/**/*.wav')
        .pipe(gulp.dest(config.dest.samples));
});

gulp.task('compile:templates', function(done) {
    var options = {
        assets: config.dest.assets,
        data: config.src.data,
        production: false,
        helpers: 'src/templates/helpers/**/*.js',
        layout: 'default-layout',
        layouts: 'src/templates/views/layouts/*.html',
        partials: {
            common: ['src/templates/views/partials/layout/**/*.{hbs,html}'],
            components: ['src/templates/views/partials/components/**/*.{hbs,html}'],
            modules: ['src/templates/views/partials/modules/**/*.{hbs,html}'],
            structures: ['src/templates/views/partials/structures/**/*.{hbs,html}'],
            templates: ['src/templates/views/partials/templates/**/*.{hbs,html}']
        },
        //partials: 'src/templates/views/partials/**/*.html',
        pages: 'src/templates/views/*.html',
        dest: config.dest.base
    };

    assemble.templates(options, done);
});

gulp.task('compile:styleguide', function(done) {
  var options = {
    assetPath: '/public', // relative to site root directory (not styleguide)
    data: config.src.data,
    // patterns: 'src/templates/views/partials/**/*.html',
    patterns: {
        component: 'src/templates/views/partials/components/**/*.{hbs,html}',
        module: 'src/templates/views/partials/modules/**/*.{hbs,html}',
        structure: 'src/templates/views/partials/structures/**/*.{hbs,html}',
        template: 'src/templates/views/partials/templates/**/*.{hbs,html}'
    },
    pages: 'src/templates/views/*.{hbs,html}',
    dest: 'styleguide'
  };

  assemble.styleguide(options, done);
});

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

// watch task
gulp.task('watch', function () {
    plugins.watch([config.src.pages, config.src.includes, config.src.data], function () {
        plugins.sequence('compile:templates', function() {
            bsreload();
        });
    });

    plugins.watch(config.src.styles, function () {
        gulp.start('styles')
    });

    plugins.watch(config.src.images, function () {
        gulp.start('images')
    });
});

// test performance task
gulp.task('test:performance', function () {
    //TODO: write the performance tasks
});

// performance task entry point
gulp.task('perf', ['test:performance']);

// production build task
gulp.task('build:production', ['clean'], function (cb) {
    plugins.sequence(
        ['fonts', 'images', 'styles', 'scripts', 'copy:extras', 'copy:samples'],
        ['compile:templates'],
        done
    );
});

gulp.task('build', ['clean'], function(done) {
    plugins.sequence(
        ['fonts', 'images', 'styles', 'scripts', 'copy:extras', 'copy:samples'],
        ['compile:templates'],
        ['compile:styleguide'],
        ['browserSync', 'watch'],
        done
    );
});

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

<commit_msg> not just wav<commit_after>'use strict';
//node modules
var path = require('path');

// node_modules modules
var _ = require('lodash');
var browserify  = require("browserify");
var browserSync = require("browser-sync");
var bsreload = browserSync.reload;
var del = require('del');
var mergeStream = require('merge-stream');
var q = require('q');
var source = require('vinyl-source-stream');
var watchify = require('watchify');

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

// kickstart modules
var assemble = require('kickstart-assemble');

// user project configuration
var config = require('./config.js');

// error handler
var onError = function (err, cb) {
    plugins.util.beep();
    plugins.util.log(plugins.util.colors.red(err));

    if (typeof this.emit === 'function') this.emit('end');
};

// clean task
gulp.task('clean', function (cb) {
    return del([
        config.dest.base,
        'styleguide'
    ], cb);
});

// styles task
gulp.task('styles', function () {
    return gulp.src(config.src.styles)
        .pipe(plugins.plumber({ errorHandler: onError }))
        .pipe(plugins.sass(config.sass.settings))
        .pipe(plugins.cssUrlAdjuster({
            prepend: config.dest.images
        }))
        .pipe(plugins.if(!config.dev, plugins.combineMediaQueries()))
        .pipe(plugins.autoprefixer(config.sass.autoprefixer))
        .pipe(plugins.if(!config.dev, plugins.csso()))
        .pipe(gulp.dest(config.dest.styles))
        .pipe(plugins.if(config.dev, bsreload({ stream: true })));
});

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

    var browserifyTask = function () {

        var browserifyThis = function (bundleConfig) {
            if (config.dev) {
                _.extend(config.src.scriptBundles, watchify.args, { debug: true });

                bundleConfig = _.omit(bundleConfig, ['external', 'require']);
            }

            var b = browserify(bundleConfig);

            var bundle = function () {

                return b
                    .bundle()
                    .on('error', onError)
                    .pipe(source(bundleConfig.outputName))
                    .pipe(gulp.dest(bundleConfig.dest))
                    .pipe(plugins.if(config.dev, bsreload({ stream: true })));
            };

            if (config.dev) {
                b = watchify(b);
                b.on('update', bundle);
            } else {
                if (bundleConfig.require) b.require(bundleConfig.require);
                if (bundleConfig.external) b.external(bundleConfig.external);
            }

            return bundle();
        };

        return mergeStream.apply(gulp, _.map(config.scriptBundles, browserifyThis));

    }

    return browserifyTask();

});

// images task
gulp.task('images', function () {
    return gulp.src(config.src.images)
        .pipe(plugins.changed(config.dest.images))
        .pipe(plugins.if(!config.dev, plugins.imagemin(config.images)))
        .pipe(gulp.dest(config.dest.images))
        .pipe(plugins.if(config.dev, bsreload({ stream: true })));
});

// fonts task
gulp.task('fonts', function () {
    return gulp.src(config.src.fonts)
        .pipe(gulp.dest(config.dest.fonts));
});

// copy extra files task
gulp.task('copy:extras', function () {
    return gulp.src('./src/public/*.{ico,txt}')
        .pipe(gulp.dest(config.dest.base));
});

gulp.task('copy:samples', function () {
    return gulp.src('./src/public/samples/**/*.*')
        .pipe(gulp.dest(config.dest.samples));
});

gulp.task('compile:templates', function(done) {
    var options = {
        assets: config.dest.assets,
        data: config.src.data,
        production: false,
        helpers: 'src/templates/helpers/**/*.js',
        layout: 'default-layout',
        layouts: 'src/templates/views/layouts/*.html',
        partials: {
            common: ['src/templates/views/partials/layout/**/*.{hbs,html}'],
            components: ['src/templates/views/partials/components/**/*.{hbs,html}'],
            modules: ['src/templates/views/partials/modules/**/*.{hbs,html}'],
            structures: ['src/templates/views/partials/structures/**/*.{hbs,html}'],
            templates: ['src/templates/views/partials/templates/**/*.{hbs,html}']
        },
        //partials: 'src/templates/views/partials/**/*.html',
        pages: 'src/templates/views/*.html',
        dest: config.dest.base
    };

    assemble.templates(options, done);
});

gulp.task('compile:styleguide', function(done) {
  var options = {
    assetPath: '/public', // relative to site root directory (not styleguide)
    data: config.src.data,
    // patterns: 'src/templates/views/partials/**/*.html',
    patterns: {
        component: 'src/templates/views/partials/components/**/*.{hbs,html}',
        module: 'src/templates/views/partials/modules/**/*.{hbs,html}',
        structure: 'src/templates/views/partials/structures/**/*.{hbs,html}',
        template: 'src/templates/views/partials/templates/**/*.{hbs,html}'
    },
    pages: 'src/templates/views/*.{hbs,html}',
    dest: 'styleguide'
  };

  assemble.styleguide(options, done);
});

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

// watch task
gulp.task('watch', function () {
    plugins.watch([config.src.pages, config.src.includes, config.src.data], function () {
        plugins.sequence('compile:templates', function() {
            bsreload();
        });
    });

    plugins.watch(config.src.styles, function () {
        gulp.start('styles')
    });

    plugins.watch(config.src.images, function () {
        gulp.start('images')
    });
});

// test performance task
gulp.task('test:performance', function () {
    //TODO: write the performance tasks
});

// performance task entry point
gulp.task('perf', ['test:performance']);

// production build task
gulp.task('build:production', ['clean'], function (cb) {
    plugins.sequence(
        ['fonts', 'images', 'styles', 'scripts', 'copy:extras', 'copy:samples'],
        ['compile:templates'],
        done
    );
});

gulp.task('build', ['clean'], function(done) {
    plugins.sequence(
        ['fonts', 'images', 'styles', 'scripts', 'copy:extras', 'copy:samples'],
        ['compile:templates'],
        ['compile:styleguide'],
        ['browserSync', 'watch'],
        done
    );
});

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

<|endoftext|>


<commit_before>const gulp = require('gulp');<commit_msg>Delete gulpfile.js (#11)<commit_after><|endoftext|>


<commit_before>'use strict'
let gulp = require('gulp')
let karma = require('gulp-karma')
let mocha = require('gulp-mocha')
let path = require('path')
let fs = require('fs')
let browserify = require('browserify')
let babelify = require('babelify')
let envify = require('envify')
let uglifyify = require('uglifyify')
let glob = require('glob')

// By default, we assume browser-loaded javascript is served from the root
// directory, "/", of the http server. karma, however, assumes files are in the
// "/base/" directory, thus we invented this variable to allow overriding the
// directory. If you wish to put your javascript somewhere other than root,
// specify it by setting this environment variable before building. You can
// also override the name of the bundle and worker files or the minified
// versions by setting the respective environment variables below.
if (!process.env.FULLNODE_JS_BASE_URL) {
  process.env.FULLNODE_JS_BASE_URL = '/'
}

if (!process.env.FULLNODE_JS_BUNDLE_FILE) {
  process.env.FULLNODE_JS_BUNDLE_FILE = 'fullnode.js'
}

if (!process.env.FULLNODE_JS_WORKER_FILE) {
  process.env.FULLNODE_JS_WORKER_FILE = 'fullnode-worker.js'
}

if (!process.env.FULLNODE_JS_BUNDLE_MIN_FILE) {
  process.env.FULLNODE_JS_BUNDLE_MIN_FILE = 'fullnode-min.js'
}

if (!process.env.FULLNODE_JS_WORKER_MIN_FILE) {
  process.env.FULLNODE_JS_WORKER_MIN_FILE = 'fullnode-worker-min.js'
}

gulp.task('build-bundle', function () {
  return new Promise(function (resolve, reject) {
    browserify({debug: false})
      // The babel polyfill is include once in the main bundle, and no where
      // else. You must include the main bundle in any HTML that uses fullnode,
      // since the pollyfill must be required exactly once. If you build things
      // yourself with babel, you will need to be sure to include the polyfill
      // exactly once yourself.
      .add(require.resolve('babelify/polyfill'))
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .add(require.resolve('./index.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_BUNDLE_FILE)))
  })
})

gulp.task('build-worker', ['build-bundle'], function () {
  return new Promise(function (resolve, reject) {
    browserify({debug: false})
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .require(require.resolve('./lib/worker-browser.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_WORKER_FILE)))
  })
})

gulp.task('build-bundle-min', ['build-worker'], function () {
  return new Promise(function (resolve, reject) {
    let backup = process.env.FULLNODE_JS_BUNDLE_FILE
    process.env.FULLNODE_JS_BUNDLE_FILE = process.env.FULLNODE_JS_BUNDLE_MIN_FILE
    browserify({debug: false})
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .transform(uglifyify)
      .require(require.resolve('./index.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {process.env.FULLNODE_JS_BUNDLE_FILE = backup; resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_BUNDLE_FILE)))
  })
})

gulp.task('build-worker-min', ['build-bundle-min'], function () {
  return new Promise(function (resolve, reject) {
    let backup = process.env.FULLNODE_JS_WORKER_FILE
    process.env.FULLNODE_JS_WORKER_FILE = process.env.FULLNODE_JS_WORKER_MIN_FILE
    browserify({debug: false})
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .transform(uglifyify)
      .require(require.resolve('./lib/worker-browser.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {process.env.FULLNODE_JS_WORKER_FILE = backup; resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_WORKER_FILE)))
  })
})

gulp.task('build-tests', ['build-worker'], function () {
  return new Promise(function (resolve, reject) {
    glob('./test/**/*.js', {}, function (err, files) {
      let b = browserify({debug: true})
        .transform(envify)
        .transform(babelify.configure({ignore: /node_modules/}))
      for (let file of files) {
        b.add(file)
      }
      b.bundle()
        .on('error', function (err) {reject(err);})
        .on('end', function () {resolve();})
        .pipe(fs.createWriteStream(path.join(__dirname, 'build', 'tests.js')))
    })
  })
})

gulp.task('test-node', function () {
  return gulp.src(['test/*.js'])
    .pipe(mocha({reporter: 'dot'}))
    .once('error', function (error) {
      process.exit(1)
    })
    .once('end', function () {
      process.exit()
    })
})

gulp.task('build-karma-url', function () {
  // karma serves static files, including js files, from /base/
  process.env.FULLNODE_JS_BASE_URL = '/base/'
})

gulp.task('build-karma', ['build-karma-url', 'build-tests'])

gulp.task('test-karma', ['build-karma'], function () {
  let server = require(path.join(__dirname, 'bin', 'testapp')).server // runs the PeerJS server
  return gulp.src([])
    .pipe(karma({
      configFile: '.karma.conf.js',
      action: 'run'
    }))
    .on('error', function (err) {
      throw err
    })
    .on('end', function () {
      server.close()
      process.exit()
    })
})

gulp.task('test-browser', ['build-karma', 'test-karma'])
gulp.task('test', ['test-node'])
gulp.task('build', ['build-bundle', 'build-worker', 'build-bundle-min', 'build-worker-min', 'build-tests'])
gulp.task('default', ['build'])
<commit_msg>minified bundle should also have polyfill<commit_after>'use strict'
let gulp = require('gulp')
let karma = require('gulp-karma')
let mocha = require('gulp-mocha')
let path = require('path')
let fs = require('fs')
let browserify = require('browserify')
let babelify = require('babelify')
let envify = require('envify')
let uglifyify = require('uglifyify')
let glob = require('glob')

// By default, we assume browser-loaded javascript is served from the root
// directory, "/", of the http server. karma, however, assumes files are in the
// "/base/" directory, thus we invented this variable to allow overriding the
// directory. If you wish to put your javascript somewhere other than root,
// specify it by setting this environment variable before building. You can
// also override the name of the bundle and worker files or the minified
// versions by setting the respective environment variables below.
if (!process.env.FULLNODE_JS_BASE_URL) {
  process.env.FULLNODE_JS_BASE_URL = '/'
}

if (!process.env.FULLNODE_JS_BUNDLE_FILE) {
  process.env.FULLNODE_JS_BUNDLE_FILE = 'fullnode.js'
}

if (!process.env.FULLNODE_JS_WORKER_FILE) {
  process.env.FULLNODE_JS_WORKER_FILE = 'fullnode-worker.js'
}

if (!process.env.FULLNODE_JS_BUNDLE_MIN_FILE) {
  process.env.FULLNODE_JS_BUNDLE_MIN_FILE = 'fullnode-min.js'
}

if (!process.env.FULLNODE_JS_WORKER_MIN_FILE) {
  process.env.FULLNODE_JS_WORKER_MIN_FILE = 'fullnode-worker-min.js'
}

gulp.task('build-bundle', function () {
  return new Promise(function (resolve, reject) {
    browserify({debug: false})
      // The babel polyfill is include once in the main bundle, and no where
      // else. You must include the main bundle in any HTML that uses fullnode,
      // since the pollyfill must be required exactly once. If you build things
      // yourself with babel, you will need to be sure to include the polyfill
      // exactly once yourself.
      .add(require.resolve('babelify/polyfill'))
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .add(require.resolve('./index.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_BUNDLE_FILE)))
  })
})

gulp.task('build-worker', ['build-bundle'], function () {
  return new Promise(function (resolve, reject) {
    browserify({debug: false})
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .require(require.resolve('./lib/worker-browser.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_WORKER_FILE)))
  })
})

gulp.task('build-bundle-min', ['build-worker'], function () {
  return new Promise(function (resolve, reject) {
    let backup = process.env.FULLNODE_JS_BUNDLE_FILE
    process.env.FULLNODE_JS_BUNDLE_FILE = process.env.FULLNODE_JS_BUNDLE_MIN_FILE
    browserify({debug: false})
      .add(require.resolve('babelify/polyfill'))
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .transform(uglifyify)
      .require(require.resolve('./index.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {process.env.FULLNODE_JS_BUNDLE_FILE = backup; resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_BUNDLE_FILE)))
  })
})

gulp.task('build-worker-min', ['build-bundle-min'], function () {
  return new Promise(function (resolve, reject) {
    let backup = process.env.FULLNODE_JS_WORKER_FILE
    process.env.FULLNODE_JS_WORKER_FILE = process.env.FULLNODE_JS_WORKER_MIN_FILE
    browserify({debug: false})
      .transform(envify)
      .transform(babelify.configure({ignore: /node_modules/}))
      .transform(uglifyify)
      .require(require.resolve('./lib/worker-browser.js'), {entry: true})
      .bundle()
      .on('error', function (err) {reject(err);})
      .on('end', function () {process.env.FULLNODE_JS_WORKER_FILE = backup; resolve();})
      .pipe(fs.createWriteStream(path.join(__dirname, 'build', process.env.FULLNODE_JS_WORKER_FILE)))
  })
})

gulp.task('build-tests', ['build-worker'], function () {
  return new Promise(function (resolve, reject) {
    glob('./test/**/*.js', {}, function (err, files) {
      let b = browserify({debug: true})
        .transform(envify)
        .transform(babelify.configure({ignore: /node_modules/}))
      for (let file of files) {
        b.add(file)
      }
      b.bundle()
        .on('error', function (err) {reject(err);})
        .on('end', function () {resolve();})
        .pipe(fs.createWriteStream(path.join(__dirname, 'build', 'tests.js')))
    })
  })
})

gulp.task('test-node', function () {
  return gulp.src(['test/*.js'])
    .pipe(mocha({reporter: 'dot'}))
    .once('error', function (error) {
      process.exit(1)
    })
    .once('end', function () {
      process.exit()
    })
})

gulp.task('build-karma-url', function () {
  // karma serves static files, including js files, from /base/
  process.env.FULLNODE_JS_BASE_URL = '/base/'
})

gulp.task('build-karma', ['build-karma-url', 'build-tests'])

gulp.task('test-karma', ['build-karma'], function () {
  let server = require(path.join(__dirname, 'bin', 'testapp')).server // runs the PeerJS server
  return gulp.src([])
    .pipe(karma({
      configFile: '.karma.conf.js',
      action: 'run'
    }))
    .on('error', function (err) {
      throw err
    })
    .on('end', function () {
      server.close()
      process.exit()
    })
})

gulp.task('test-browser', ['build-karma', 'test-karma'])
gulp.task('test', ['test-node'])
gulp.task('build', ['build-bundle', 'build-worker', 'build-bundle-min', 'build-worker-min', 'build-tests'])
gulp.task('default', ['build'])
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    cmq = require('gulp-combine-media-queries'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    cache = require('gulp-cache'),
    express = require('express'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    uncss = require('gulp-uncss'),
    glob = require('glob'),
    lrserver = lr(),
    server = express(),
    livereloadport = 35729,
    serverport = 5000;

server.use(livereload({
    port: livereloadport
}));
server.use(express.static(__dirname + '/dist/'));

gulp.task('styles', function() {
  return gulp.src('src/sass/main.scss')
    .pipe(sass({ style: 'expanded' }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(uncss({
      html: glob.sync('dist/**/*.html'),
      ignore: [/is-/, /not-/]
    }))
    .pipe(cmq({
      log: true
    }))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(livereload(lrserver));
});

gulp.task('scripts', function() {
  return gulp.src('src/js/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(livereload(lrserver));
});

gulp.task('clean', function() {
  return gulp.src(['dist/assets/css', 'dist/assets/js'], {read: false})
    .pipe(clean());
});

gulp.task('serve', function() {
  server.listen(serverport);

  lrserver.listen(livereloadport);
});

gulp.task('default', ['clean'], function() {
    gulp.start('styles', 'scripts');
});

gulp.task('watch', function() {

    gulp.start('serve');

    // Watch .scss files
    gulp.watch('src/sass/**/*.scss', ['styles']);

    // Watch .js files
    gulp.watch('src/js/**/*.js', ['scripts']);

});<commit_msg>Do not process @import<commit_after>var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    cmq = require('gulp-combine-media-queries'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    cache = require('gulp-cache'),
    express = require('express'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    uncss = require('gulp-uncss'),
    glob = require('glob'),
    lrserver = lr(),
    server = express(),
    livereloadport = 35729,
    serverport = 5000;

server.use(livereload({
    port: livereloadport
}));
server.use(express.static(__dirname + '/dist/'));

gulp.task('styles', function() {
  return gulp.src('src/sass/main.scss')
    .pipe(sass({ style: 'expanded' }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(uncss({
      html: glob.sync('dist/**/*.html'),
      ignore: [/is-/, /not-/]
    }))
    .pipe(cmq({
      log: true
    }))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss({processImport:false}))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(livereload(lrserver));
});

gulp.task('scripts', function() {
  return gulp.src('src/js/**/*.js')
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/js'))
    .pipe(livereload(lrserver));
});

gulp.task('clean', function() {
  return gulp.src(['dist/assets/css', 'dist/assets/js'], {read: false})
    .pipe(clean());
});

gulp.task('serve', function() {
  server.listen(serverport);

  lrserver.listen(livereloadport);
});

gulp.task('default', ['clean'], function() {
    gulp.start('styles', 'scripts');
});

gulp.task('watch', function() {

    gulp.start('serve');

    // Watch .scss files
    gulp.watch('src/sass/**/*.scss', ['styles']);

    // Watch .js files
    gulp.watch('src/js/**/*.js', ['scripts']);

});<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    iif = require('gulp-if'),
    sass = require('gulp-sass'),
    cssbeautify = require('gulp-cssbeautify'),
    del = require('del');

gulp.task('build', ['clean'], function() {
  return gulp.src('apps/**')
    .pipe(iif('*.scss', sass()))
    .pipe(iif('*.css', cssbeautify({ indent: '  ' })))
    .pipe(gulp.dest('dist'));
});

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

gulp.task('default', function() {
  gulp.start('build');
});
<commit_msg>Add gulp build and serve tasks<commit_after>'use strict';

var gulp = require('gulp'),
    iif = require('gulp-if'),
    sass = require('gulp-sass'),
    cssbeautify = require('gulp-cssbeautify'),
    del = require('del'),
    browserSync = require('browser-sync');

// Process app templates folder
gulp.task('buildTemplates', ['clean'], function() {
  return gulp
    .src('apps/**')
    .pipe(iif('*.scss', sass()))
    .pipe(iif('*.css', cssbeautify({ indent: '  ' })))
    .pipe(gulp.dest('dist'));
});

// Process public folder
gulp.task('buildPublic', ['clean'], function() {
  return gulp
    .src('public/**')
    .pipe(gulp.dest('dist'));
});

// Generate all files
gulp.task('build', ['buildTemplates', 'buildPublic']);

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

// Watch files for changes & reload
gulp.task('serve', ['build'], function () {
  browserSync({
    notify: false,
    server: ['dist']
  });

  gulp.watch(['public/*.*', 'apps/**/*.html', 'apps/**/*.{scss,css}'], ['build', browserSync.reload]);
});

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


<commit_before>'use strict'
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const gulpts = require('gulp-typescript');
const uglify = require('gulp-uglify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');

const tsProject = gulpts.createProject('tsconfig.json', {
    typescript: require('typescript'),
    module: "commonjs",
    sortOutput: true
});

gulp.task('tsCompile', () => {
    gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(tsProject())
        .js
        .pipe(gulp.dest('build/'));
});

gulp.task('browserify', () => {
    browserify({
            entries: ['./build/index.js']
        })
        .bundle()
        .pipe(source('lib.min.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('./dist/'))
});

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

gulp.task('default', ['tsCompile', 'browserify'], () => {
    gulp.start('watch')
});<commit_msg>Change output file name<commit_after>'use strict'
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const gulpts = require('gulp-typescript');
const uglify = require('gulp-uglify');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');

const tsProject = gulpts.createProject('tsconfig.json', {
    typescript: require('typescript'),
    module: "commonjs",
    sortOutput: true
});

gulp.task('tsCompile', () => {
    gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(tsProject())
        .js
        .pipe(gulp.dest('build/'));
});

gulp.task('browserify', () => {
    browserify({
            entries: ['./build/index.js']
        })
        .bundle()
        .pipe(source('parseley.min.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('./dist/'))
});

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

gulp.task('default', ['tsCompile', 'browserify'], () => {
    gulp.start('watch')
});<|endoftext|>


<commit_before>// Requires
var pkg = require('./package.json');
var gulp = require('gulp');
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var cssnano = require('cssnano');
var data = require('gulp-data');
var del = require('del');
var fs = require('fs');
var imagemin = require('gulp-imagemin');
var plumber = require('gulp-plumber');
var postcss = require('gulp-postcss');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var svgSprite = require('gulp-svg-sprite');
var twig = require('gulp-twig');
var uglify = require('gulp-uglify');

// BrowserSync reload
function reload(done) {
  browserSync.reload();
  done();
};

// Get data from JSON
function getData() {
  var data = JSON.parse(fs.readFileSync(pkg.paths.src.base + pkg.vars.dataName, 'utf8'));
  return data;
};

// CSS task
gulp.task('css', function() {
  var processors = [
    autoprefixer(),
    cssnano({
      preset: 'default'
    })
  ];

  return gulp.src(pkg.paths.src.css + pkg.vars.cssName)
    .pipe(plumber())
    .pipe(sass().on('error', sass.logError))
    .pipe(postcss(processors))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(pkg.paths.dist.css))
    .pipe(browserSync.stream());
});

// JS task
gulp.task('js', function() {
  return gulp.src(pkg.globs.js)
    .pipe(plumber())
    .pipe(concat(pkg.vars.jsName))
    .pipe(uglify())
    .pipe(gulp.dest(pkg.paths.dist.js));
});

// HTML task
gulp.task('html', function() {
  return gulp.src(pkg.globs.html)
    .pipe(plumber())
    .pipe(data(getData()))
    .pipe(twig())
    .pipe(gulp.dest(pkg.paths.dist.base));
});

// Images task
gulp.task('images', function() {
  return gulp.src(pkg.globs.img)
    .pipe(changed(pkg.paths.dist.img))
    .pipe(imagemin({
      interlaced: true,
      progressive: true
    }))
    .pipe(gulp.dest(pkg.paths.dist.img));
});

// Sprites task
gulp.task('sprites', function() {
  return gulp.src(pkg.globs.sprites)
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: '.',
          sprite: pkg.vars.spriteName
        }
      }
    }))
    .pipe(gulp.dest(pkg.paths.dist.sprites));
});

// Fonts task
gulp.task('fonts', function() {
  return gulp.src(pkg.globs.fonts)
    .pipe(changed(pkg.paths.dist.fonts))
    .pipe(gulp.dest(pkg.paths.dist.fonts));
})

// Clean task
gulp.task('clean', function() {
  return del(pkg.globs.clean);
});

// Serve task
gulp.task('serve', function() {
  browserSync.init({
    server: pkg.urls.local
  });
});

// Watch task
gulp.task('watch', function() {
	gulp.watch(pkg.paths.src.css + '**/*.scss', gulp.series('css'));
	gulp.watch(pkg.paths.src.js + '**/*.js', gulp.series('js', reload));
	gulp.watch([
      pkg.paths.src.base + '**/*.{html,twig}',
      pkg.paths.src.base + pkg.vars.dataName
    ], gulp.series('html', reload));
	gulp.watch(pkg.paths.src.img + '**/*', gulp.series('images'));
  gulp.watch(pkg.paths.sprites + '**/*.svg', gulp.series('sprites'));
  gulp.watch(pkg.paths.fonts + '**/*', gulp.series('fonts'))
});

// Default task
gulp.task('default',
  gulp.series(
    gulp.parallel('css', 'js', 'html', 'images', 'sprites', 'fonts'),
    gulp.parallel('serve', 'watch')
  )
);

// Build task
gulp.task('build',
  gulp.series(
    'clean',
    gulp.parallel('css', 'js', 'html', 'images', 'sprites', 'fonts')
  )
);
<commit_msg>Fix watch paths<commit_after>// Requires
var pkg = require('./package.json');
var gulp = require('gulp');
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var cssnano = require('cssnano');
var data = require('gulp-data');
var del = require('del');
var fs = require('fs');
var imagemin = require('gulp-imagemin');
var plumber = require('gulp-plumber');
var postcss = require('gulp-postcss');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var svgSprite = require('gulp-svg-sprite');
var twig = require('gulp-twig');
var uglify = require('gulp-uglify');

// BrowserSync reload
function reload(done) {
  browserSync.reload();
  done();
};

// Get data from JSON
function getData() {
  var data = JSON.parse(fs.readFileSync(pkg.paths.src.base + pkg.vars.dataName, 'utf8'));
  return data;
};

// CSS task
gulp.task('css', function() {
  var processors = [
    autoprefixer(),
    cssnano({
      preset: 'default'
    })
  ];

  return gulp.src(pkg.paths.src.css + pkg.vars.cssName)
    .pipe(plumber())
    .pipe(sass().on('error', sass.logError))
    .pipe(postcss(processors))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(pkg.paths.dist.css))
    .pipe(browserSync.stream());
});

// JS task
gulp.task('js', function() {
  return gulp.src(pkg.globs.js)
    .pipe(plumber())
    .pipe(concat(pkg.vars.jsName))
    .pipe(uglify())
    .pipe(gulp.dest(pkg.paths.dist.js));
});

// HTML task
gulp.task('html', function() {
  return gulp.src(pkg.globs.html)
    .pipe(plumber())
    .pipe(data(getData()))
    .pipe(twig())
    .pipe(gulp.dest(pkg.paths.dist.base));
});

// Images task
gulp.task('images', function() {
  return gulp.src(pkg.globs.img)
    .pipe(changed(pkg.paths.dist.img))
    .pipe(imagemin({
      interlaced: true,
      progressive: true
    }))
    .pipe(gulp.dest(pkg.paths.dist.img));
});

// Sprites task
gulp.task('sprites', function() {
  return gulp.src(pkg.globs.sprites)
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: '.',
          sprite: pkg.vars.spriteName
        }
      }
    }))
    .pipe(gulp.dest(pkg.paths.dist.sprites));
});

// Fonts task
gulp.task('fonts', function() {
  return gulp.src(pkg.globs.fonts)
    .pipe(changed(pkg.paths.dist.fonts))
    .pipe(gulp.dest(pkg.paths.dist.fonts));
})

// Clean task
gulp.task('clean', function() {
  return del(pkg.globs.clean);
});

// Serve task
gulp.task('serve', function() {
  browserSync.init({
    server: pkg.urls.local
  });
});

// Watch task
gulp.task('watch', function() {
	gulp.watch(pkg.paths.src.css + '**/*.scss', gulp.series('css'));
	gulp.watch(pkg.paths.src.js + '**/*.js', gulp.series('js', reload));
	gulp.watch([
      pkg.paths.src.base + '**/*.{html,twig}',
      pkg.paths.src.base + pkg.vars.dataName
    ], gulp.series('html', reload));
	gulp.watch(pkg.paths.src.img + '**/*', gulp.series('images'));
  gulp.watch(pkg.paths.src.sprites + '**/*.svg', gulp.series('sprites'));
  gulp.watch(pkg.paths.src.fonts + '**/*', gulp.series('fonts'))
});

// Default task
gulp.task('default',
  gulp.series(
    gulp.parallel('css', 'js', 'html', 'images', 'sprites', 'fonts'),
    gulp.parallel('serve', 'watch')
  )
);

// Build task
gulp.task('build',
  gulp.series(
    'clean',
    gulp.parallel('css', 'js', 'html', 'images', 'sprites', 'fonts')
  )
);
<|endoftext|>