<commit_before>/*
 * Copyright (c) 2016 Steven Soloff
 *
 * This is free software: you can redistribute it and/or modify it under the
 * terms of the MIT License (https://opensource.org/licenses/MIT).
 * This software comes with ABSOLUTELY NO WARRANTY.
 */

'use strict';

const _ = require('underscore');
const childProcess = require('child_process');
const del = require('del');
const fs = require('fs');
const gulp = require('gulp');

const BUILD_OUTPUT_DIR = '.build';
const FEATURES_DIR = 'features';
const NODE_MODULES_BIN_DIR = 'node_modules/.bin';
const SRC_DIR = 'src';
const CLIENT_SRC_DIR = `${SRC_DIR}/client`;
const SERVER_SRC_DIR = `${SRC_DIR}/server`;
const SUPPORT_DIR = 'support';
const TEST_DIR = 'test';
const SERVER_TEST_DIR = `${TEST_DIR}/server`;
const COMPILE_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/compile`;
const COVERAGE_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/coverage`;
const DIST_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/dist`;

const SERVER_PID = 'server.pid';
const SERVER_PID_ENCODING = 'utf8';

function exec(command, callback) {
  childProcess.exec(command, (err) => {
    if (err) {
      return callback(err);
    }
    callback();
  });
}

function runCucumber(path) {
  const cucumber = require('gulp-cucumber');
  const glob = require('glob');
  const streamToPromise = require('stream-to-promise');

  let promise = Promise.resolve();

  const featureDirs = glob.sync(`${path}/*`, {
    ignore: `${path}/support`,
  });
  featureDirs.forEach((featureDir) => {
    promise = promise.then(() => streamToPromise(gulp.src([`${featureDir}/*.feature`]).pipe(cucumber({}))));
  });

  return promise;
}

function runEsLint(globs, configPath) {
  const eslint = require('gulp-eslint');
  return gulp.src(globs)
    .pipe(eslint({
      configFile: configPath,
    }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

function runHtmlHint(stream) {
  const htmlhint = require('gulp-htmlhint');
  return stream
    .pipe(htmlhint())
    .pipe(htmlhint.failReporter());
}

function runJsDoc(configPath, callback) {
  exec(`${NODE_MODULES_BIN_DIR}/jsdoc -c ${configPath}`, callback);
}

function runUnitTests() {
  const jasmine = require('gulp-jasmine');
  return gulp.src('') // Files to process are defined in Jasmine configuration below
    .pipe(jasmine({
      config: require(`./${COMPILE_OUTPUT_DIR}/${SERVER_TEST_DIR}/.jasmine.json`),
    }));
}

function wrapHtmlFragment(content) {
  return `<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>FRAGMENT</title>
    </head>
    <body>
    ${content}
    </body>
    </html>`;
}

gulp.task('acceptance-test:client', () => {
  return runCucumber(`${FEATURES_DIR}/client`);
});

gulp.task('acceptance-test:server', () => {
  return runCucumber(`${FEATURES_DIR}/server`);
});

gulp.task('acceptance-test', (done) => {
  const runSequence = require('run-sequence');
  runSequence('acceptance-test:client', 'acceptance-test:server', done);
});

gulp.task('clean', () => {
  return del([BUILD_OUTPUT_DIR]);
});

gulp.task('compile:jison', () => {
  const jison = require('gulp-jison');
  return gulp.src(`${SRC_DIR}/**/*.jison`)
    .pipe(jison())
    .pipe(gulp.dest(`${COMPILE_OUTPUT_DIR}/${SRC_DIR}`));
});

gulp.task('compile:js', () => {
  return gulp.src([`${SRC_DIR}/**/*`, `${SUPPORT_DIR}/**/*`, `${TEST_DIR}/**/*`], {base: '.', dot: true})
    .pipe(gulp.dest(COMPILE_OUTPUT_DIR));
});

gulp.task('compile', ['compile:jison', 'compile:js']);

gulp.task('dist:client', () => {
  const eventStream = require('event-stream');
  const flatten = require('gulp-flatten');
  const mainBowerFiles = require('main-bower-files');
  const PUBLIC_DIR = 'public';
  const HTML_DIR = PUBLIC_DIR;
  const CSS_DIR = `${PUBLIC_DIR}/css`;
  const JS_DIR = `${PUBLIC_DIR}/js`;
  const JS_VENDOR_DIR = `${JS_DIR}/vendor`;

  return eventStream.merge(
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.html`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${HTML_DIR}`)),
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.css`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${CSS_DIR}`)),
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.js`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${JS_DIR}`)),
    gulp.src(mainBowerFiles('**/*.js'))
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${JS_VENDOR_DIR}`)),
    gulp.src(mainBowerFiles('**/*.css'))
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${CSS_DIR}`))
  );
});

gulp.task('dist:server', () => {
  return gulp.src(`${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/**/*.js`)
    .pipe(gulp.dest(DIST_OUTPUT_DIR));
});

gulp.task('dist', ['dist:client', 'dist:server']);

gulp.task('docs:client', (done) => {
  runJsDoc('.jsdoc-client-conf.json', done);
});

gulp.task('docs:server', (done) => {
  runJsDoc('.jsdoc-server-conf.json', done);
});

gulp.task('docs', ['docs:client', 'docs:server']);

gulp.task('instrument-for-coverage', ['compile'], () => {
  const istanbul = require('gulp-istanbul');
  return gulp.src(
    [
      `${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/**/*.js`,
      `!${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/model/dice-expression-parser.js`,
      `${COMPILE_OUTPUT_DIR}/${SERVER_TEST_DIR}/**/*.js`,
    ]
    )
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('lint:css', () => {
  const csslint = require('gulp-csslint');
  return gulp.src(`${CLIENT_SRC_DIR}/**/*.css`)
    .pipe(csslint())
    .pipe(csslint.formatter())
    .pipe(csslint.formatter('fail'));
});

gulp.task('lint:html:fragment', () => {
  const change = require('gulp-change');
  return runHtmlHint(
    gulp.src(`${CLIENT_SRC_DIR}/*/**/*.html`)
      .pipe(change(wrapHtmlFragment))
  );
});

gulp.task('lint:html:full', () => {
  return runHtmlHint(
    gulp.src(`${CLIENT_SRC_DIR}/index.html`)
  );
});

gulp.task('lint:html', ['lint:html:full', 'lint:html:fragment']);

gulp.task('lint:js:default', () => {
  return runEsLint([
    `${FEATURES_DIR}/**/*.js`,
    `${COMPILE_OUTPUT_DIR}/${SRC_DIR}/**/*.js`,
    `!${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/model/dice-expression-parser.js`,
    `${COMPILE_OUTPUT_DIR}/${TEST_DIR}/**/*.js`,
  ]);
});

gulp.task('lint:js:gulpfile', () => {
  return runEsLint('gulpfile.js', '.eslintrc-gulpfile.json');
});

gulp.task('lint:js', ['lint:js:default', 'lint:js:gulpfile']);

gulp.task('lint:json', () => {
  const jsonlint = require('gulp-jsonlint');
  return gulp.src(
    ['./*.json', `${FEATURES_DIR}/**/*.json`, `${SRC_DIR}/**/*.json`, `${TEST_DIR}/**/*.json`],
    {dot: true}
    )
    .pipe(jsonlint())
    .pipe(jsonlint.reporter())
    .pipe(jsonlint.failAfterError());
});

gulp.task('lint:package', () => {
  const gutil = require('gulp-util');
  const through = require('through2');
  const validate = require('gulp-nice-package');

  function failOnError() {
    return through.obj((file, enc, cb) => {
      let error = null;
      if (file.nicePackage.valid === false) {
        error = new gutil.PluginError(
          'gulp-nice-package',
          `Failed with ${_.size(file.nicePackage.errors)} error(s), ` +
              `${_.size(file.nicePackage.warnings)} warning(s), ` +
              `${_.size(file.nicePackage.recommendations)} recommendation(s)`
        );
      }
      return cb(error, file);
    });
  }

  return gulp.src('package.json')
    .pipe(validate())
    .pipe(failOnError());
});

gulp.task('lint', ['lint:js', 'lint:json', 'lint:package', 'lint:html', 'lint:css']);

gulp.task('publish-coverage', () => {
  const coveralls = require('gulp-coveralls');
  return gulp.src(`${COVERAGE_OUTPUT_DIR}/lcov.info`)
    .pipe(coveralls());
});

gulp.task('start-server', (done) => {
  const child = childProcess.spawn(
    process.argv[0],
    [
      `${DIST_OUTPUT_DIR}/server.js`,
      `${SERVER_TEST_DIR}/test-keys/private-key.pem`,
      `${SERVER_TEST_DIR}/test-keys/public-key.pem`,
    ],
    {
      detached: true,
      stdio: 'ignore',
    }
    )
    .on('error', done);
  child.unref();

  if (!_.isUndefined(child.pid)) {
    fs.writeFileSync(SERVER_PID, child.pid, {
      encoding: SERVER_PID_ENCODING,
    });
  }

  done();
});

gulp.task('stop-server', () => {
  const pid = fs.readFileSync(SERVER_PID, {
    encoding: SERVER_PID_ENCODING,
  });
  process.kill(pid);
  return del([SERVER_PID]);
});

gulp.task('unit-test', ['compile'], () => {
  return runUnitTests();
});

gulp.task('unit-test-with-coverage', ['instrument-for-coverage'], () => {
  const istanbul = require('gulp-istanbul');
  return runUnitTests()
    .pipe(istanbul.writeReports({
      dir: COVERAGE_OUTPUT_DIR,
      reporters: ['lcov', 'text-summary'],
    }))
    .pipe(istanbul.enforceThresholds({
      thresholds: {
        global: 90,
      },
    }));
});
<commit_msg>Reformat code<commit_after>/*
 * Copyright (c) 2016 Steven Soloff
 *
 * This is free software: you can redistribute it and/or modify it under the
 * terms of the MIT License (https://opensource.org/licenses/MIT).
 * This software comes with ABSOLUTELY NO WARRANTY.
 */

'use strict';

const _ = require('underscore');
const childProcess = require('child_process');
const del = require('del');
const fs = require('fs');
const gulp = require('gulp');

const BUILD_OUTPUT_DIR = '.build';
const FEATURES_DIR = 'features';
const NODE_MODULES_BIN_DIR = 'node_modules/.bin';
const SRC_DIR = 'src';
const CLIENT_SRC_DIR = `${SRC_DIR}/client`;
const SERVER_SRC_DIR = `${SRC_DIR}/server`;
const SUPPORT_DIR = 'support';
const TEST_DIR = 'test';
const SERVER_TEST_DIR = `${TEST_DIR}/server`;
const COMPILE_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/compile`;
const COVERAGE_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/coverage`;
const DIST_OUTPUT_DIR = `${BUILD_OUTPUT_DIR}/dist`;

const SERVER_PID = 'server.pid';
const SERVER_PID_ENCODING = 'utf8';

function exec(command, callback) {
  childProcess.exec(command, (err) => {
    if (err) {
      return callback(err);
    }
    callback();
  });
}

function runCucumber(path) {
  const cucumber = require('gulp-cucumber');
  const glob = require('glob');
  const streamToPromise = require('stream-to-promise');

  let promise = Promise.resolve();

  const featureDirs = glob.sync(`${path}/*`, {
    ignore: `${path}/support`,
  });
  featureDirs.forEach((featureDir) => {
    promise = promise.then(() => streamToPromise(gulp.src([`${featureDir}/*.feature`]).pipe(cucumber({}))));
  });

  return promise;
}

function runEsLint(globs, configPath) {
  const eslint = require('gulp-eslint');
  return gulp.src(globs)
    .pipe(eslint({
      configFile: configPath,
    }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
}

function runHtmlHint(stream) {
  const htmlhint = require('gulp-htmlhint');
  return stream
    .pipe(htmlhint())
    .pipe(htmlhint.failReporter());
}

function runJsDoc(configPath, callback) {
  exec(`${NODE_MODULES_BIN_DIR}/jsdoc -c ${configPath}`, callback);
}

function runUnitTests() {
  const jasmine = require('gulp-jasmine');
  return gulp.src('') // Files to process are defined in Jasmine configuration below
    .pipe(jasmine({
      config: require(`./${COMPILE_OUTPUT_DIR}/${SERVER_TEST_DIR}/.jasmine.json`),
    }));
}

function wrapHtmlFragment(content) {
  return `<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>FRAGMENT</title>
    </head>
    <body>
    ${content}
    </body>
    </html>`;
}

gulp.task('acceptance-test:client', () => {
  return runCucumber(`${FEATURES_DIR}/client`);
});

gulp.task('acceptance-test:server', () => {
  return runCucumber(`${FEATURES_DIR}/server`);
});

gulp.task('acceptance-test', (done) => {
  const runSequence = require('run-sequence');
  runSequence('acceptance-test:client', 'acceptance-test:server', done);
});

gulp.task('clean', () => {
  return del([BUILD_OUTPUT_DIR]);
});

gulp.task('compile:jison', () => {
  const jison = require('gulp-jison');
  return gulp.src(`${SRC_DIR}/**/*.jison`)
    .pipe(jison())
    .pipe(gulp.dest(`${COMPILE_OUTPUT_DIR}/${SRC_DIR}`));
});

gulp.task('compile:js', () => {
  return gulp.src([`${SRC_DIR}/**/*`, `${SUPPORT_DIR}/**/*`, `${TEST_DIR}/**/*`], {base: '.', dot: true})
    .pipe(gulp.dest(COMPILE_OUTPUT_DIR));
});

gulp.task('compile', ['compile:jison', 'compile:js']);

gulp.task('dist:client', () => {
  const eventStream = require('event-stream');
  const flatten = require('gulp-flatten');
  const mainBowerFiles = require('main-bower-files');
  const PUBLIC_DIR = 'public';
  const HTML_DIR = PUBLIC_DIR;
  const CSS_DIR = `${PUBLIC_DIR}/css`;
  const JS_DIR = `${PUBLIC_DIR}/js`;
  const JS_VENDOR_DIR = `${JS_DIR}/vendor`;

  return eventStream.merge(
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.html`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${HTML_DIR}`)),
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.css`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${CSS_DIR}`)),
    gulp.src(`${COMPILE_OUTPUT_DIR}/${CLIENT_SRC_DIR}/**/*.js`)
      .pipe(flatten())
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${JS_DIR}`)),
    gulp.src(mainBowerFiles('**/*.js'))
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${JS_VENDOR_DIR}`)),
    gulp.src(mainBowerFiles('**/*.css'))
      .pipe(gulp.dest(`${DIST_OUTPUT_DIR}/${CSS_DIR}`))
  );
});

gulp.task('dist:server', () => {
  return gulp.src(`${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/**/*.js`)
    .pipe(gulp.dest(DIST_OUTPUT_DIR));
});

gulp.task('dist', ['dist:client', 'dist:server']);

gulp.task('docs:client', (done) => {
  runJsDoc('.jsdoc-client-conf.json', done);
});

gulp.task('docs:server', (done) => {
  runJsDoc('.jsdoc-server-conf.json', done);
});

gulp.task('docs', ['docs:client', 'docs:server']);

gulp.task('instrument-for-coverage', ['compile'], () => {
  const istanbul = require('gulp-istanbul');
  return gulp
    .src([
      `${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/**/*.js`,
      `!${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/model/dice-expression-parser.js`,
      `${COMPILE_OUTPUT_DIR}/${SERVER_TEST_DIR}/**/*.js`,
    ])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('lint:css', () => {
  const csslint = require('gulp-csslint');
  return gulp.src(`${CLIENT_SRC_DIR}/**/*.css`)
    .pipe(csslint())
    .pipe(csslint.formatter())
    .pipe(csslint.formatter('fail'));
});

gulp.task('lint:html:fragment', () => {
  const change = require('gulp-change');
  return runHtmlHint(
    gulp.src(`${CLIENT_SRC_DIR}/*/**/*.html`)
      .pipe(change(wrapHtmlFragment))
  );
});

gulp.task('lint:html:full', () => {
  return runHtmlHint(
    gulp.src(`${CLIENT_SRC_DIR}/index.html`)
  );
});

gulp.task('lint:html', ['lint:html:full', 'lint:html:fragment']);

gulp.task('lint:js:default', () => {
  return runEsLint([
    `${FEATURES_DIR}/**/*.js`,
    `${COMPILE_OUTPUT_DIR}/${SRC_DIR}/**/*.js`,
    `!${COMPILE_OUTPUT_DIR}/${SERVER_SRC_DIR}/model/dice-expression-parser.js`,
    `${COMPILE_OUTPUT_DIR}/${TEST_DIR}/**/*.js`,
  ]);
});

gulp.task('lint:js:gulpfile', () => {
  return runEsLint('gulpfile.js', '.eslintrc-gulpfile.json');
});

gulp.task('lint:js', ['lint:js:default', 'lint:js:gulpfile']);

gulp.task('lint:json', () => {
  const jsonlint = require('gulp-jsonlint');
  return gulp
    .src(
      ['./*.json', `${FEATURES_DIR}/**/*.json`, `${SRC_DIR}/**/*.json`, `${TEST_DIR}/**/*.json`],
      {dot: true}
    )
    .pipe(jsonlint())
    .pipe(jsonlint.reporter())
    .pipe(jsonlint.failAfterError());
});

gulp.task('lint:package', () => {
  const gutil = require('gulp-util');
  const through = require('through2');
  const validate = require('gulp-nice-package');

  function failOnError() {
    return through.obj((file, enc, cb) => {
      let error = null;
      if (file.nicePackage.valid === false) {
        error = new gutil.PluginError(
          'gulp-nice-package',
          `Failed with ${_.size(file.nicePackage.errors)} error(s), ` +
              `${_.size(file.nicePackage.warnings)} warning(s), ` +
              `${_.size(file.nicePackage.recommendations)} recommendation(s)`
        );
      }
      return cb(error, file);
    });
  }

  return gulp.src('package.json')
    .pipe(validate())
    .pipe(failOnError());
});

gulp.task('lint', ['lint:js', 'lint:json', 'lint:package', 'lint:html', 'lint:css']);

gulp.task('publish-coverage', () => {
  const coveralls = require('gulp-coveralls');
  return gulp.src(`${COVERAGE_OUTPUT_DIR}/lcov.info`)
    .pipe(coveralls());
});

gulp.task('start-server', (done) => {
  const child = childProcess
    .spawn(
      process.argv[0], [
        `${DIST_OUTPUT_DIR}/server.js`,
        `${SERVER_TEST_DIR}/test-keys/private-key.pem`,
        `${SERVER_TEST_DIR}/test-keys/public-key.pem`,
      ], {
        detached: true,
        stdio: 'ignore',
      }
    )
    .on('error', done);
  child.unref();

  if (!_.isUndefined(child.pid)) {
    fs.writeFileSync(SERVER_PID, child.pid, {
      encoding: SERVER_PID_ENCODING,
    });
  }

  done();
});

gulp.task('stop-server', () => {
  const pid = fs.readFileSync(SERVER_PID, {
    encoding: SERVER_PID_ENCODING,
  });
  process.kill(pid);
  return del([SERVER_PID]);
});

gulp.task('unit-test', ['compile'], () => {
  return runUnitTests();
});

gulp.task('unit-test-with-coverage', ['instrument-for-coverage'], () => {
  const istanbul = require('gulp-istanbul');
  return runUnitTests()
    .pipe(istanbul.writeReports({
      dir: COVERAGE_OUTPUT_DIR,
      reporters: ['lcov', 'text-summary'],
    }))
    .pipe(istanbul.enforceThresholds({
      thresholds: {
        global: 90,
      },
    }));
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    eslint = require('gulp-eslint'),
    project = require('./package.json');

var paths = {
  src: './' + project.name + '.js',
  dist: '.dist/' + project.name + '.js',
  raf: './bower_components/raf.js/raf.js',
  output: './dist'
}

gulp.task('lint', function() {
  return gulp.src(paths.src)
    .pipe(eslint())
    // outputs the lint results to the console.
    .pipe(eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failOnError last.
    .pipe(eslint.failOnError());
});

gulp.task('uglify', [ 'lint' ], function() {
  return gulp.src(paths.src)
    .pipe(uglify())
    .pipe(gulp.dest(paths.output));
});

// build: generates uglified version
// and add raf version file
gulp.task('build', [ 'uglify' ], function() {
  return gulp.src([ paths.raf, paths.src ])
    .pipe(concat(project.name + '.raf.js'))
    .pipe(uglify())
    .pipe(gulp.dest(paths.output));
});

// assign default gulp task
gulp.task('default', [ 'build' ]);
<commit_msg>improve naming in gulp tasks<commit_after>'use strict';

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    eslint = require('gulp-eslint'),
    project = require('./package.json');

var paths = {
  src: './' + project.name + '.js',
  dist: '.dist/' + project.name + '.js',
  raf: './bower_components/raf.js/raf.js',
  output: './dist'
}

gulp.task('lint', function() {
  return gulp.src(paths.src)
    .pipe(eslint())
    // outputs the lint results to the console.
    .pipe(eslint.format())
    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failOnError last.
    .pipe(eslint.failOnError());
});

gulp.task('build:unbundled', [ 'lint' ], function() {
  return gulp.src(paths.src)
    .pipe(uglify())
    .pipe(gulp.dest(paths.output));
});

gulp.task('build:bundled', function() {
  return gulp.src([ paths.raf, paths.src ])
    .pipe(concat(project.name + '.raf.js'))
    .pipe(uglify())
    .pipe(gulp.dest(paths.output));
});

// build: generates uglified version
// and add raf version file
gulp.task('build', [ 'build:bundled', 'build:unbundled' ]);

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


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');

gulp.task('zip', function () {
  return gulp.src([
    'templates/*',
    'templates/app/**',
    '!**/.DS_Store'
  ], {dot: true})
  .pipe($.ignore.include({isFile: true}))
    .pipe($.zip('archive.zip'))
    .pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, 'dist'));

gulp.task('default', function (callback) {
  runSequence('clean', 'zip', callback);
});
<commit_msg>Fix directory structure in zip archive<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var del = require('del');

gulp.task('zip', function () {
  return gulp.src([
    'templates/*',
    'templates/app/**',
    '!**/.DS_Store'
  ], {base: 'templates', dot: true})
  .pipe($.ignore.include({isFile: true}))
    .pipe($.zip('archive.zip'))
    .pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, 'dist'));

gulp.task('default', function (callback) {
  runSequence('clean', 'zip', callback);
});
<|endoftext|>


<commit_before>/*jslint indent: 2, node: true, nomen: true */

var gulp = require('gulp'),
  rename = require('gulp-rename'),
  concat = require('gulp-concat'),
  preprocess = require('gulp-preprocess'),
  jslint = require('gulp-jslint'),
  clean = require('gulp-clean'),
  merge = require('gulp-merge'),
  uglify = require('gulp-uglify'),
  _scriptGlob = [
    'src/addition.js',
    'src/subtraction.js',
    'src/multiplication.js',
    'src/division.js',
    'src/unittests.js',
    'src/math.js'
  ],
  _markupGlob = 'src/*.htm';

gulp.task('clean', function () {
  "use strict";

  return gulp.src(['build/debug/*', 'build/prod/*'], {read: false}).
    pipe(clean());
});

gulp.task('build', function () {
  "use strict";

  return gulp.src('gulpfile.js').
    pipe(jslint());
});

gulp.task('scripts', ['clean'], function () {
  "use strict";

  return merge(
    gulp.src(_scriptGlob).
      pipe(jslint()),
    gulp.src(_scriptGlob).
      pipe(preprocess({context: { DEBUG: true}})).
      pipe(gulp.dest('build/debug/')),
    gulp.src(_scriptGlob).
      pipe(concat('math.js')).
      pipe(preprocess({context: { PROD: true}})).
      pipe(gulp.dest('build/prod/')).
      pipe(uglify({
        warnings: true,
        mangle: {
          toplevel: true,
          screw_ie8: true
        },
        compress: {
          screw_ie8: true
        }
      })).
      pipe(rename({ extname: '.min.js' })).
      pipe(gulp.dest('build/prod/'))
  );
});

gulp.task('markup', ['clean'], function () {
  "use strict";

  return merge(
    gulp.src(_markupGlob).
      pipe(preprocess({context: { DEBUG: true}})).
      pipe(gulp.dest('build/debug/')),
    gulp.src(_markupGlob).
      pipe(preprocess({context: { PROD: true}})).
      pipe(gulp.dest('build/prod/'))
  );
});

gulp.task('default', ['build', 'scripts', 'markup']);
<commit_msg>Added watch<commit_after>/*jslint indent: 2, node: true, nomen: true */

var gulp = require('gulp'),
  rename = require('gulp-rename'),
  concat = require('gulp-concat'),
  preprocess = require('gulp-preprocess'),
  jslint = require('gulp-jslint'),
  clean = require('gulp-clean'),
  merge = require('gulp-merge'),
  uglify = require('gulp-uglify'),
  _jslintGlob = [
    'gulpfile.js',
    'src/*.js'
  ],
  _scriptsGlob = [
    'src/addition.js',
    'src/subtraction.js',
    'src/multiplication.js',
    'src/division.js',
    'src/unittests.js',
    'src/math.js'
  ],
  _markupGlob = 'src/*.htm';

gulp.task('clean', function () {
  "use strict";

  return gulp.src(['build/debug/*', 'build/prod/*'], {read: false}).
    pipe(clean());
});

gulp.task('jslint', function () {
  "use strict";

  return gulp.src(_jslintGlob).
    pipe(jslint());
});

gulp.task('scripts', ['clean', 'jslint'], function () {
  "use strict";

  return merge(
    gulp.src(_scriptsGlob).
      pipe(preprocess({context: { DEBUG: true}})).
      pipe(gulp.dest('build/debug/')),
    gulp.src(_scriptsGlob).
      pipe(concat('math.js')).
      pipe(preprocess({context: { PROD: true}})).
      pipe(gulp.dest('build/prod/')).
      pipe(uglify({
        warnings: true,
        mangle: {
          toplevel: true,
          screw_ie8: true
        },
        compress: {
          screw_ie8: true
        }
      })).
      pipe(rename({ extname: '.min.js' })).
      pipe(gulp.dest('build/prod/'))
  );
});

gulp.task('markup', ['clean'], function () {
  "use strict";

  return merge(
    gulp.src(_markupGlob).
      pipe(preprocess({context: { DEBUG: true}})).
      pipe(gulp.dest('build/debug/')),
    gulp.src(_markupGlob).
      pipe(preprocess({context: { PROD: true}})).
      pipe(gulp.dest('build/prod/'))
  );
});

gulp.task('watch', function () {
  "use strict";

  gulp.watch(_jslintGlob, ['jslint']);
});

gulp.task('default', ['jslint', 'scripts', 'markup']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var packageJson = require('./package.json');
var loadTasks = require('module-boilerplate');

loadTasks(gulp, packageJson);<commit_msg>new gulpfile with separated tasks<commit_after>var gulp = require('gulp');
var packageJson = require('./package.json');

require('./node_modules/module-boilerplate/load-dependencies')(packageJson);

tasks = require('./node_modules/module-boilerplate/tasks.json');

for(var i in tasks) {
  require('./node_modules/module-boilerplate/tasks/' + tasks[i])(gulp, packageJson);
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var useref = require('gulp-useref');
var gulpIf = require('gulp-if');
var serve = require('gulp-serve');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var fs = require('fs-extra');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync').create();
var htmlmin = require('gulp-htmlmin');
var gzip = require('gulp-gzip');
var brotli = require('gulp-brotli');
var gzipStatic = require('connect-gzip-static');
var argv = require('yargs').argv;

// Build Dependencies
var browserify = require('browserify');
var vinylBuffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var vinylSourceStream = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var pump = require('pump');

// Development Dependencies
var jshint = require('gulp-jshint');

var compileUrl = argv.compileUrl || '//chibitronics.com/compile';

var configHandler =         /* Add a live url, /config.json, that returns our current configuration. */
    function (req, res, next) {
        if (req.url !== '/config.json') {
            return next();
        }
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.end(JSON.stringify({
            compileUrl: compileUrl
        }));
    };

// gulp-serve requires the root directory to exist already.
// Put this here to make sure they can start up.
gulp.task('serve', serve({
    root: 'build',
    middlewares: [configHandler]
}));

// This will fail if there is no "build" directory.
// That's fine, because it's impossible to serve without
// a build directory present.
try {
    gulp.task('serve-prod', serve({
        root: 'build',
        port: 80,
        hostname: "0.0.0.0",
        middlewares: [
            configHandler,
            gzipStatic(__dirname + '/build')
        ]
    }));
} catch (e) { };

gulp.task('build-html', function () {
    return gulp.src('src/*.html') /* Load all HTML files */
        .pipe(useref()) /* Combine files into one */
        .pipe(gulpIf('*.css', cssnano())) /* minify css files */
        .pipe(gulpIf('*.html', htmlmin({ collapseWhitespace: false, minifyJS: false, minifyCSS: false }))) /* also minify html */
        .pipe(gulp.dest('build')) /* Write out to 'html' output directory */
});

gulp.task('compress-gz', function () {
    return gulp.src(['build/**/*.html', 'build/**/*.css', 'build/**/*.js', 'build/**/*.map'])
        .pipe(gzip())
        .pipe(gulp.dest('build'))
});

gulp.task('compress-br', function () {
    return gulp.src(['build/**/*.html', 'build/**/*.css', 'build/**/*.js', 'build/**/*.map'])
        .pipe(brotli.compress({
            quality: 11,
            skipLarger: true
        }))
        .pipe(gulp.dest('build'))
});

gulp.task('compress-br-examples', function () {
    return gulp.src('build/examples/**')
        .pipe(brotli.compress({
            quality: 11,
            skipLarger: true
        }))
        .pipe(gulp.dest('build/examples'))
});

gulp.task('compress-gz-examples', function () {
    return gulp.src('build/examples/**')
        .pipe(gzip())
        .pipe(gulp.dest('build/examples'))
});

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

gulp.task('build-scripts', function (cb) {
    // Single entry point to browserify
    var b = browserify({
        debug: true,
        insertGlobals: true,
        entries: 'index.js',
        basedir: 'src/js'
    });

    pump([
        b.bundle(),
        vinylSourceStream('index.js'),
        vinylBuffer(),
        gulp.dest('./build/js')
    ],
        cb
    );

});

gulp.task('build-scripts-minimal', function (cb) {
    // Single entry point to browserify
    var b = browserify({
        debug: false,
        insertGlobals: true,
        entries: 'index.js',
        basedir: 'src/js'
    });

    pump([
        b.bundle(),
        vinylSourceStream('index.js'),
        vinylBuffer(),
        sourcemaps.init({ loadMaps: true }),
        // Add gulp plugins to the pipeline here.
        uglify(),
        sourcemaps.write('./'),
        gulp.dest('./build/js')
    ],
        cb
    );
});

gulp.task('build-lame', function () {
    return gulp.src('node_modules/lamejs/lame.min.js')
        .pipe(gulp.dest('build/js/'))
});

gulp.task('copy-examples', function () {
    return gulp.src('examples/**/*')
        .pipe(gulp.dest('build/examples'))
});

gulp.task('copy-images', function () {
    return gulp.src('src/images/**/*.{png,gif,jpg,svg}')
        .pipe(imagemin())
        .pipe(gulp.dest('build/images'))
});

gulp.task('clean:build', function () {
    fs.ensureDirSync('build');
    fs.removeSync('build');
    return fs.ensureDirSync('build');
});

gulp.task('cache:clear', function (callback) {
    return cache.clearAll(callback);
});

gulp.task('browserSync', function () {
    browserSync.init({
        server: {
            baseDir: 'build'
        }
    })
});

gulp.task('build', function (callback) {
    runSequence('clean:build', ['build-html',
        'lint-src', 'build-scripts', 'build-lame',
        'copy-images',
        'copy-examples',
    ],
        callback
    );
});

gulp.task('default', function (callback) {
    runSequence('clean:build', 'build', 'build-scripts-minimal',
        [
            'compress-gz',
            'compress-br',
            'compress-gz-examples',
            'compress-br-examples'
        ],
        callback
    );
});

gulp.task('watch', ['browserSync'], function () {
    gulp.watch('src/*.html', ['build-html', browserSync.reload]);
    gulp.watch('src/**/*.css', ['build-html', browserSync.reload]);
    gulp.watch('src/js/**/*.js', ['build-scripts', browserSync.reload]);
});
<commit_msg>gulpfile: rebuild when 'watch' is started<commit_after>var gulp = require('gulp');
var useref = require('gulp-useref');
var gulpIf = require('gulp-if');
var serve = require('gulp-serve');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var fs = require('fs-extra');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync').create();
var htmlmin = require('gulp-htmlmin');
var gzip = require('gulp-gzip');
var brotli = require('gulp-brotli');
var gzipStatic = require('connect-gzip-static');
var argv = require('yargs').argv;

// Build Dependencies
var browserify = require('browserify');
var vinylBuffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var vinylSourceStream = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var pump = require('pump');

// Development Dependencies
var jshint = require('gulp-jshint');

var compileUrl = argv.compileUrl || '//chibitronics.com/compile';

var configHandler =         /* Add a live url, /config.json, that returns our current configuration. */
    function (req, res, next) {
        if (req.url !== '/config.json') {
            return next();
        }
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.end(JSON.stringify({
            compileUrl: compileUrl
        }));
    };

// gulp-serve requires the root directory to exist already.
// Put this here to make sure they can start up.
gulp.task('serve', serve({
    root: 'build',
    middlewares: [configHandler]
}));

// This will fail if there is no "build" directory.
// That's fine, because it's impossible to serve without
// a build directory present.
try {
    gulp.task('serve-prod', serve({
        root: 'build',
        port: 80,
        hostname: "0.0.0.0",
        middlewares: [
            configHandler,
            gzipStatic(__dirname + '/build')
        ]
    }));
} catch (e) { };

gulp.task('build-html', function () {
    return gulp.src('src/*.html') /* Load all HTML files */
        .pipe(useref()) /* Combine files into one */
        .pipe(gulpIf('*.css', cssnano())) /* minify css files */
        .pipe(gulpIf('*.html', htmlmin({ collapseWhitespace: false, minifyJS: false, minifyCSS: false }))) /* also minify html */
        .pipe(gulp.dest('build')) /* Write out to 'html' output directory */
});

gulp.task('compress-gz', function () {
    return gulp.src(['build/**/*.html', 'build/**/*.css', 'build/**/*.js', 'build/**/*.map'])
        .pipe(gzip())
        .pipe(gulp.dest('build'))
});

gulp.task('compress-br', function () {
    return gulp.src(['build/**/*.html', 'build/**/*.css', 'build/**/*.js', 'build/**/*.map'])
        .pipe(brotli.compress({
            quality: 11,
            skipLarger: true
        }))
        .pipe(gulp.dest('build'))
});

gulp.task('compress-br-examples', function () {
    return gulp.src('build/examples/**')
        .pipe(brotli.compress({
            quality: 11,
            skipLarger: true
        }))
        .pipe(gulp.dest('build/examples'))
});

gulp.task('compress-gz-examples', function () {
    return gulp.src('build/examples/**')
        .pipe(gzip())
        .pipe(gulp.dest('build/examples'))
});

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

gulp.task('build-scripts', function (cb) {
    // Single entry point to browserify
    var b = browserify({
        debug: true,
        insertGlobals: true,
        entries: 'index.js',
        basedir: 'src/js'
    });

    pump([
        b.bundle(),
        vinylSourceStream('index.js'),
        vinylBuffer(),
        gulp.dest('./build/js')
    ],
        cb
    );

});

gulp.task('build-scripts-minimal', function (cb) {
    // Single entry point to browserify
    var b = browserify({
        debug: false,
        insertGlobals: true,
        entries: 'index.js',
        basedir: 'src/js'
    });

    pump([
        b.bundle(),
        vinylSourceStream('index.js'),
        vinylBuffer(),
        sourcemaps.init({ loadMaps: true }),
        // Add gulp plugins to the pipeline here.
        uglify(),
        sourcemaps.write('./'),
        gulp.dest('./build/js')
    ],
        cb
    );
});

gulp.task('build-lame', function () {
    return gulp.src('node_modules/lamejs/lame.min.js')
        .pipe(gulp.dest('build/js/'))
});

gulp.task('copy-examples', function () {
    return gulp.src('examples/**/*')
        .pipe(gulp.dest('build/examples'))
});

gulp.task('copy-images', function () {
    return gulp.src('src/images/**/*.{png,gif,jpg,svg}')
        .pipe(imagemin())
        .pipe(gulp.dest('build/images'))
});

gulp.task('clean:build', function () {
    fs.ensureDirSync('build');
    fs.removeSync('build');
    return fs.ensureDirSync('build');
});

gulp.task('cache:clear', function (callback) {
    return cache.clearAll(callback);
});

gulp.task('browserSync', function () {
    browserSync.init({
        server: {
            baseDir: 'build'
        }
    })
});

gulp.task('build', function (callback) {
    runSequence('clean:build', ['build-html',
        'lint-src', 'build-scripts', 'build-lame',
        'copy-images',
        'copy-examples',
    ],
        callback
    );
});

gulp.task('default', function (callback) {
    runSequence('clean:build', 'build', 'build-scripts-minimal',
        [
            'compress-gz',
            'compress-br',
            'compress-gz-examples',
            'compress-br-examples'
        ],
        callback
    );
});

gulp.task('watch', ['browserSync'], function (callback) {
    gulp.watch('src/*.html', ['build-html', browserSync.reload]);
    gulp.watch('src/**/*.css', ['build-html', browserSync.reload]);
    gulp.watch('src/js/**/*.js', ['build-scripts', browserSync.reload]);
    runSequence('clean:build', 'build', callback);
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const gulpCleanCss = require('gulp-clean-css');
const gulpHtmlMinify = require('gulp-html-minifier');
const { pipeline } = require('readable-stream');
const { addCspHashes, compilePages, buildSitemap } = require('./gulp-helpers');

const fsp = fs.promises;

const PROJECT_DIR = path.dirname(__filename);
const SRC_DIR = path.join(PROJECT_DIR, 'src');
const ASSET_DIR = path.join(PROJECT_DIR, 'src', 'assets');
const BUILD_DIR = path.join(PROJECT_DIR, 'build');

function removeBuildDir() {
    return fsp.rmdir(BUILD_DIR, { recursive: true });
}

function buildPages() {
    return pipeline(
        gulp.src(path.join(SRC_DIR, 'templates', 'pages', '*.hbs')),
        compilePages,
        gulpHtmlMinify({
            minifyCSS: true,
            minifyJS: true,
            removeComments: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true
        }),
        addCspHashes,
        gulpHtmlMinify({
            collapseWhitespace: true,
            collapseBooleanAttributes: true,
            removeAttributeQuotes: true,
            removeOptionalTags: true,
            sortAttributes: true,
            sortClassName: true,
            useShortDoctype: true,
        }),
        gulp.dest(BUILD_DIR)
    );
}

async function buildCss() {
    return pipeline(
        gulp.src(path.join(ASSET_DIR, '**', '*.css')),
        gulpCleanCss(),
        gulp.dest(path.join(BUILD_DIR, 'assets'))
    );
}

async function copyImages() {
    return pipeline(
        gulp.src([path.join(ASSET_DIR, '*.png'), path.join(ASSET_DIR, '*.jpg')]),
        gulp.dest(path.join(BUILD_DIR, 'assets'))
    );
}

function copyRootFiles() {
    return pipeline(
        gulp.src(path.join(PROJECT_DIR, 'src', 'root-files', '*')),
        gulp.dest(BUILD_DIR)
    );
}

const build = gulp.series(
    removeBuildDir,
    gulp.parallel(
        buildPages,
        buildCss,
        copyImages,
        copyRootFiles
    ),
    buildSitemap
);

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

gulp.task('watch', gulp.series(
    build,
    function watchFiles() {
        gulp.watch(['src/*', 'src/**/*'], build);
    }
));
<commit_msg>Fix build pipeline<commit_after>const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const gulpCleanCss = require('gulp-clean-css');
const gulpHtmlMinify = require('gulp-html-minifier');
const { pipeline } = require('readable-stream');
const { addCspHashes, compilePages, buildSitemap } = require('./gulp-helpers');

const fsp = fs.promises;

const PROJECT_DIR = path.dirname(__filename);
const SRC_DIR = path.join(PROJECT_DIR, 'src');
const ASSET_DIR = path.join(PROJECT_DIR, 'src', 'assets');
const BUILD_DIR = path.join(PROJECT_DIR, 'build');

function removeBuildDir() {
    if (!fs.existsSync(BUILD_DIR)) {
        return Promise.resolve();
    }
    return fsp.rm(BUILD_DIR, { recursive: true });
}

function buildPages() {
    return pipeline(
        gulp.src(path.join(SRC_DIR, 'templates', 'pages', '*.hbs')),
        compilePages,
        gulpHtmlMinify({
            minifyCSS: true,
            minifyJS: true,
            removeComments: true,
            removeRedundantAttributes: true,
            removeScriptTypeAttributes: true,
            removeStyleLinkTypeAttributes: true
        }),
        addCspHashes,
        gulpHtmlMinify({
            collapseWhitespace: true,
            collapseBooleanAttributes: true,
            removeAttributeQuotes: true,
            removeOptionalTags: true,
            sortAttributes: true,
            sortClassName: true,
            useShortDoctype: true,
        }),
        gulp.dest(BUILD_DIR)
    );
}

async function buildCss() {
    return pipeline(
        gulp.src(path.join(ASSET_DIR, '**', '*.css')),
        gulpCleanCss(),
        gulp.dest(path.join(BUILD_DIR, 'assets'))
    );
}

async function copyImages() {
    return pipeline(
        gulp.src([path.join(ASSET_DIR, '*.png'), path.join(ASSET_DIR, '*.jpg')]),
        gulp.dest(path.join(BUILD_DIR, 'assets'))
    );
}

function copyRootFiles() {
    return pipeline(
        gulp.src(path.join(PROJECT_DIR, 'src', 'root-files', '*')),
        gulp.dest(BUILD_DIR)
    );
}

const build = gulp.series(
    removeBuildDir,
    gulp.parallel(
        buildPages,
        buildCss,
        copyImages,
        copyRootFiles
    ),
    buildSitemap
);

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

gulp.task('watch', gulp.series(
    build,
    function watchFiles() {
        gulp.watch(['src/*', 'src/**/*'], build);
    }
));
<|endoftext|>


<commit_before>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const argv                      = require('yargs').argv
    const darwinInfoPlistBase       = require('./build/darwin-info-base.json')
    const exec                      = require('child_process').exec
    const fs                        = require('fs-extra')
    const gulp                      = require('gulp')
    const less                      = require('less')
    const mv                        = require('mv')
    const packageJsonFirstLoad      = require('./package.json')
    const path                      = require('path')
    const plist                     = require('plist')
    const request                   = require('request')
    const ugly                      = require('gulp-uglify')
    const util                      = require('util')

//
// ─── CONSTANTS ──────────────────────────────────────────────────────────────────
//

    const orchestraVersion   = "v1.0"
    const pathToResultDir    = '_compiled'
    const nightlyReleaseName = 'Orchestra Nightly'
    const stableReleaseName  = 'Orchestra'

    const isProductionBuild  =
        ( argv.productionBuild? true : false )

    const OrchestraNodeModules = [
        'concerto-compiler', 'messenger', 'regulex', 'monaco-editor/min/vs',
        'amdefine', 'regexpu-core', 'regexpu', 'regjsgen', 'regjsparser',
        'regenerate', 'unicode-match-property-ecmascript', 'jsesc', 'recast',
        'unicode-canonical-property-names-ecmascript', 'ast-types', 'esprima',
        'unicode-property-aliases-ecmascript', 'source-map', 'private',
        'unicode-match-property-value-ecmascript',
    ]

//
// ─── UPDATING PACKAGE JSON ──────────────────────────────────────────────────────
//

    const packageJson = Object.assign( packageJsonFirstLoad, {
        productName: ( isProductionBuild? stableReleaseName : nightlyReleaseName ),
    })

//
// ─── TOOLS ──────────────────────────────────────────────────────────────────────
//

    /** Run shell commands easy! */
    function shell ( command , callback ) {
        return new Promise(( resolve, reject ) =>
            exec( command.join(' '), err => err ? reject( err ) : resolve( ) )
        )
    }

//
// ─── COPY DIR FILES ─────────────────────────────────────────────────────────────
//

    /** Copy to binary from dir */
    function copyToBinaryFromDir ( dir, subfolder ) {
        fs.readdir( dir , ( err , files ) => {
            // if error

            if ( err )
                console.log(`Could not get files from directory ${ dir }`)

            // if right
            files.forEach( name => {
                const dest =
                    ( !( subfolder === undefined || subfolder === '' || subfolder === null )
                        ? path.join( pathToResultDir , subfolder , name )
                        : path.join( pathToResultDir , name ))

                if ( !( name.endsWith('.map') || name.endsWith('.d.ts') ) )
                    copyFile(
                        getLocalPath( path.join( dir , name ) ),
                        getLocalPath( dest )
                    )})})}

//
// ─── COPY SINGLE FILE ───────────────────────────────────────────────────────────
//

    /** Copies a file from `origin` to `destination` */
    async function copyFile ( origin, destination ) {
        if ( /\.DS_Store/.test( origin ) ) { return }

        await new Promise( ( resolve, reject ) => {
            fs.copy( origin, destination, err =>
                err ? reject(`Could not copy file ${ origin }`)
                    : resolve( ) ) })
    }

//
// ─── GET LOCAL PATH ─────────────────────────────────────────────────────────────
//

    /** Get Local Path in the current directory */
    function getLocalPath ( address ) {
        return path.join( __dirname , address )
    }

//
// ─── COPY FILES ─────────────────────────────────────────────────────────────────
//

    /** Copies static resource files into the result directory */
    gulp.task( 'copyResourceFiles', callback => {
        function copyNodeModules ( handle ) {
            const address = path.join( 'node_modules', handle )
            copyToBinaryFromDir( address, address )
        }

        // codes
        copyToBinaryFromDir( 'view' )
        copyToBinaryFromDir( 'editor' )
        copyToBinaryFromDir( 'libs' )
        copyToBinaryFromDir( 'windows' )
        copyToBinaryFromDir( 'winserver' )

        // design files
        copyToBinaryFromDir( 'resources' )
        copyToBinaryFromDir( 'designs/icon/file-icon-darwin/icns' )

        // node modules
        OrchestraNodeModules.forEach( x => copyNodeModules( x ) )

        // package
        copyFile(
            getLocalPath( 'package.json' ),
            getLocalPath( path.join( pathToResultDir , 'package.json' ) )
        )

        callback()
    })

//
// ─── GETTING COMMIT COUNT ───────────────────────────────────────────────────────
//

    gulp.task( 'get-commit-counts', callback => {
        const commitCountFilePath =
            `./${pathToResultDir}/about/commit-count.txt`
        const githubOrchestraRepositoryAPI =
            'https://api.github.com/repos/karyfoundation/orchestra/stats/contributors'

        try {
            new Promise (( resolve, reject ) => {
                const rejectHandler = ( ) =>
                    reject('Could not connect to GitHub')

                const options = {
                    url: githubOrchestraRepositoryAPI,
                    method: 'GET',
                    headers: {
                        'User-Agent':   'Super Agent/0.0.1',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }

                request( options, ( error, response, body ) => {
                    if ( !error && response.statusCode == 200 )
                        try {
                            const data = JSON.parse( body )[ 0 ].total.toString( )
                            resolve( data )
                        } catch ( parseError ) {
                            rejectHandler( )
                        }
                    else
                        rejectHandler( )
                })
            })
            .then( GitHubCommitCount => {
                fs.writeFileSync( commitCountFilePath, GitHubCommitCount )
                callback( )
            })
            .catch( e => {
                throw e
            })

        } catch ( error ) {
            try {
                shell([ 'git', 'rev-list', '--all', '--count',
                        '>', commitCountFilePath ])
                callback( )

            } catch ( error2 ) {
                callback('Could not save latest commits count')
            }
        }
    })

//
// ─── SHEETS ─────────────────────────────────────────────────────────────────────
//

    /** Compiles the Less style sheets */
    gulp.task( 'sheets', callback => {
        try {
            let lessSourceCode = fs.readFileSync(
                path.join( __dirname, 'sheets', 'ui.less' ), 'utf8' )

            less.render( lessSourceCode, ( err, output ) => {
                if ( err )
                    console.log(`Less failure: ${ err }`); return

                fs.writeFile(
                    path.join( __dirname, '_compiled/style.css' ),
                    output.css,
                    error => {
                        if ( error )
                            console.log('could not store the less file')
                        else
                            callback( )
                    }
                )
            })
        } catch ( err ) {
            console.log('Compiling less failed ' + err )
        }
    })

//
// ─── ELECTRON PACKER ────────────────────────────────────────────────────────────
//

    async function packOrchestraForDarwin ( ) {
        const iconFile =
            ( isProductionBuild ? './designs/icon-nightly/icns/icon.icns'
                                : './designs/icon/icns/icon.icns'
                                )

        // build script
        const packBashScript = [
            'electron-packager',
            ' _compiled',
            '"' + packageJson.productName + '"',
            '--platform=darwin',
            '--arch=x64',
            '--overwrite=true',
            '--app-bundle-id="org.karyfoundation.orchestra"',
            '--app-copyright="Copyright 2016-present, Kary Foundation, Inc. All rights reserved."',
            '--app-version="' + packageJson.version + '"',
            '--icon=' + iconFile,
            '--name="' + packageJson.productName + '"',
            '--out=_release',
            '--protocol="orchestra"',
            '--protocol-name="Orchestra"',
        ]

        // building
        await shell( packBashScript )
        updateDarwinInfoPlistFile( )
    }

    function updateDarwinInfoPlistFile ( ) {
        // data
        const plistFilePath =
            ( isProductionBuild ? '_release/Orchestra-darwin-x64/Orchestra.app/Contents/Info.plist'
                                : '_release/Orchestra Nightly-darwin-x64/Orchestra.app/Contents/Info.plist'
                                )

        // loading the info file
        const plistFileString =
            fs.readFileSync( plistFilePath, 'utf8' )
        const infoJSON =
            plist.parse( plistFileString )

        // adding stuff to the plist data
        const newInfoJSON =
            Object.assign( infoJSON, darwinInfoPlistBase )

        // making new plist info
        const newPlistFileString =
            plist.build( newInfoJSON )

        // done, now saving it back
        fs.writeFileSync( plistFilePath, newPlistFileString )
    }

    async function createMacDMGImage ( ) {
        const orchestraMacAppAddress =
            "_release/Orchestra-darwin-x64/Orchestra.app"

        fs.mkdirpSync('./_installers/macOS')

        await shell([
            'electron-installer-dmg',
            orchestraMacAppAddress,
            'Orchestra',
            '--out="./_installers/macOS"',
            '--icon-size=152',
            '--icon="./designs/icon/icns/icon.icns"',
            '--background="./build/dmg-back.png"',
            '--overwrite'
        ])
    }

//
// ─── PACK FOR LINUX ─────────────────────────────────────────────────────────────
//

    async function packOrchestraForLinux ( ) {
        // to be continued...
    }

//
// ─── PACK FOR WINDOWS ───────────────────────────────────────────────────────────
//

    async function packOrchestraForWindows ( ) {
        // to be continued...
    }

//
// ─── PACK ───────────────────────────────────────────────────────────────────────
//

    gulp.task( 'pack-orchestra', [ 'copyResourceFiles', 'sheets' ], callback => {
        async function packFunctionBody ( ) {
            if ( argv.debug )
                return await shell([ 'npm', 'run', 'electron' ])

            if ( argv.pack )
                await buildAllPlatforms( )

            if ( argv.installers )
                await createInstallersForAllPlatforms( )
        }

        packFunctionBody( )
            .then( callback )
            .catch( callback )
    })

//
// ─── BUILD FOR ALL PLATFORMS ────────────────────────────────────────────────────
//

    async function buildAllPlatforms ( ) {
        const platformFunctions = [ ]

        if ( argv.mac )
            platformFunctions.push( packOrchestraForDarwin )

        if ( argv.win )
            platformFunctions.push( packOrchestraForWindows )

        if ( argv.linux )
            platformFunctions.push( packOrchestraForLinux )

        await runAsyncFunctions( platformFunctions )
    }

//
// ─── CREATE INSTALLERS FOR ALL PLATFORMS ────────────────────────────────────────
//

    async function createInstallersForAllPlatforms ( ) {
        const platformFunctions = [ ]

        if ( argv.mac )
            platformFunctions.push( createMacDMGImage )

        await runAsyncFunctions(platformFunctions)
    }

//
// ─── RUN MANY ASYNC FUNCTIONS ───────────────────────────────────────────────────
//

    async function runAsyncFunctions ( functions ) {
        await Promise.all( functions.map( func => func( ) ) )
    }

//
// ─── AFTER PACK ─────────────────────────────────────────────────────────────────
//

    gulp.task( 'build-orchestra', [ 'pack-orchestra' ], ( ) => {

    })

//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//

    /** Where everything starts */
    gulp.task( 'default', [ 'build-orchestra' ])

// ────────────────────────────────────────────────────────────────────────────────
<commit_msg>so much of build file changes<commit_after>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const argv                      = require('yargs').argv
    const darwinInfoPlistBase       = require('./build/darwin-info-base.json')
    const exec                      = require('child_process').exec
    const fs                        = require('fs-extra')
    const gulp                      = require('gulp')
    const less                      = require('less')
    const mv                        = require('mv')
    const packageJsonFirstLoad      = require('./package.json')
    const path                      = require('path')
    const plist                     = require('plist')
    const request                   = require('request')
    const ugly                      = require('gulp-uglify')
    const util                      = require('util')

//
// ─── CONSTANTS ──────────────────────────────────────────────────────────────────
//

    const orchestraVersion   = "v1.0"
    const pathToResultDir    = '_compiled'
    const nightlyReleaseName = 'Orchestra Nightly'
    const stableReleaseName  = 'Orchestra'

    const isProductionBuild  =
        ( argv.productionBuild? true : false )

    const OrchestraNodeModules = [
        'concerto-compiler', 'messenger', 'regulex', 'monaco-editor/min/vs',
        'amdefine', 'regexpu-core', 'regexpu', 'regjsgen', 'regjsparser',
        'regenerate', 'unicode-match-property-ecmascript', 'jsesc', 'recast',
        'unicode-canonical-property-names-ecmascript', 'ast-types', 'esprima',
        'unicode-property-aliases-ecmascript', 'source-map', 'private',
        'unicode-match-property-value-ecmascript',
    ]

//
// ─── UPDATING PACKAGE JSON ──────────────────────────────────────────────────────
//

    const packageJson = Object.assign( packageJsonFirstLoad, {
        productName: ( isProductionBuild? stableReleaseName : nightlyReleaseName ),
    })

//
// ─── ASYNCIFY ───────────────────────────────────────────────────────────────────
//

    const asyncify = ( func, ...args ) =>
        new Promise( ( resolve, reject ) =>
            func( ...args, ( err, output ) =>
                err ? reject( err )
                    : resolve( output? output : undefined ) ) )

//
// ─── TOOLS ──────────────────────────────────────────────────────────────────────
//

    /** Run shell commands easy! */
    const shell = ( ...commands ) => asyncify( exec, commands.join(' ') )

//
// ─── COPY DIR FILES ─────────────────────────────────────────────────────────────
//

    /** Copy to binary from dir */
    function copyToBinaryFromDir ( dir, subfolder ) {
        fs.readdir( dir , ( err , files ) => {
            // if error

            if ( err )
                console.log(`Could not get files from directory ${ dir }`)

            // if right
            files.forEach( name => {
                const dest =
                    ( !( subfolder === undefined || subfolder === '' || subfolder === null )
                        ? path.join( pathToResultDir , subfolder , name )
                        : path.join( pathToResultDir , name ))

                if ( !( name.endsWith('.map') || name.endsWith('.d.ts') ) )
                    copyFile(
                        getLocalPath( path.join( dir , name ) ),
                        getLocalPath( dest )
                    )})})}

//
// ─── COPY SINGLE FILE ───────────────────────────────────────────────────────────
//

    /** Copies a file from `origin` to `destination` */
    async function copyFile ( origin, destination ) {
        if ( /\.DS_Store/.test( origin ) ) { return }

        // await new Promise( ( resolve, reject ) => {
        //     fs.copy( origin, destination, err =>
        //         err ? reject(`Could not copy file ${ origin }`)
        //             : resolve( ) ) })

        //         // ==

        await asyncify( fs.copy, origin, destination )
    }

//
// ─── GET LOCAL PATH ─────────────────────────────────────────────────────────────
//

    /** Get Local Path in the current directory */
    function getLocalPath ( address ) {
        return path.join( __dirname , address )
    }

//
// ─── COPY FILES ─────────────────────────────────────────────────────────────────
//

    /** Copies static resource files into the result directory */
    gulp.task( 'copyResourceFiles', callback => {
        function copyNodeModules ( handle ) {
            const address = path.join( 'node_modules', handle )
            copyToBinaryFromDir( address, address )
        }

        // codes
        copyToBinaryFromDir( 'view' )
        copyToBinaryFromDir( 'editor' )
        copyToBinaryFromDir( 'libs' )
        copyToBinaryFromDir( 'windows' )
        copyToBinaryFromDir( 'winserver' )

        // design files
        copyToBinaryFromDir( 'resources' )
        copyToBinaryFromDir( 'designs/icon/file-icon-darwin/icns' )

        // node modules
        OrchestraNodeModules.forEach( x => copyNodeModules( x ) )

        // package
        copyFile(
            getLocalPath( 'package.json' ),
            getLocalPath( path.join( pathToResultDir , 'package.json' ) )
        )

        callback()
    })

//
// ─── GETTING COMMIT COUNT ───────────────────────────────────────────────────────
//

    gulp.task( 'get-commit-counts', callback => {
        const commitCountFilePath =
            `./${pathToResultDir}/about/commit-count.txt`
        const githubOrchestraRepositoryAPI =
            'https://api.github.com/repos/karyfoundation/orchestra/stats/contributors'

        try {
            new Promise (( resolve, reject ) => {
                const rejectHandler = ( ) =>
                    reject('Could not connect to GitHub')

                const options = {
                    url: githubOrchestraRepositoryAPI,
                    method: 'GET',
                    headers: {
                        'User-Agent':   'Super Agent/0.0.1',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                }

                request( options, ( error, response, body ) => {
                    if ( !error && response.statusCode == 200 )
                        try {
                            const data = JSON.parse( body )[ 0 ].total.toString( )
                            resolve( data )
                        } catch ( parseError ) {
                            rejectHandler( )
                        }
                    else
                        rejectHandler( )
                })
            })
            .then( GitHubCommitCount => {
                fs.writeFileSync( commitCountFilePath, GitHubCommitCount )
                callback( )
            })
            .catch( e => {
                throw e
            })

        } catch ( error ) {
            try {
                shell( 'git', 'rev-list', '--all', '--count',
                        '>', commitCountFilePath )
                callback( )

            } catch ( error2 ) {
                callback('Could not save latest commits count')
            }
        }
    })

//
// ─── SHEETS ─────────────────────────────────────────────────────────────────────
//

    /** Compiles the Less style sheets */
    gulp.task( 'sheets', async callback => {
        try {
            let lessSourceCode = fs.readFileSync(
                path.join( __dirname, 'sheets', 'ui.less' ), 'utf8' )

            const renderedLess =
                await asyncify( less.render, lessSourceCode )

            asyncify( fs.writeFile,
                path.join( __dirname, '_compiled/style.css' ),
                output.css
            )

            // less.render( lessSourceCode, ( err, output ) => {
            //     if ( err )
            //         console.log(`Less failure: ${ err }`); return

            //     asyncify( fs.writeFile,
            //         path.join( __dirname, '_compiled/style.css' ),
            //         output.css
            //     )

            //     // fs.writeFile(
            //     //     path.join( __dirname, '_compiled/style.css' ),
            //     //     output.css,
            //     //     error => {
            //     //         if ( error )
            //     //             console.log('could not store the less file')
            //     //         else
            //     //             callback( )
            //     //     }
            //     // )
            // })
        } catch ( err ) {
            console.log('Compiling less failed ' + err )
        }
    })

//
// ─── ELECTRON PACKER ────────────────────────────────────────────────────────────
//

    async function packOrchestraForDarwin ( ) {
        const iconFile =
            ( isProductionBuild ? './designs/icon-nightly/icns/icon.icns'
                                : './designs/icon/icns/icon.icns'
                                )

        // build script
        const packBashScript = [
            'electron-packager',
            ' _compiled',
            '"' + packageJson.productName + '"',
            '--platform=darwin',
            '--arch=x64',
            '--overwrite=true',
            '--app-bundle-id="org.karyfoundation.orchestra"',
            '--app-copyright="Copyright 2016-present, Kary Foundation, Inc. All rights reserved."',
            '--app-version="' + packageJson.version + '"',
            '--icon=' + iconFile,
            '--name="' + packageJson.productName + '"',
            '--out=_release',
            '--protocol="orchestra"',
            '--protocol-name="Orchestra"',
        ]

        // building
        await shell( ...packBashScript )
        updateDarwinInfoPlistFile( )
    }

    function updateDarwinInfoPlistFile ( ) {
        // data
        const plistFilePath =
            ( isProductionBuild ? '_release/Orchestra-darwin-x64/Orchestra.app/Contents/Info.plist'
                                : '_release/Orchestra Nightly-darwin-x64/Orchestra.app/Contents/Info.plist'
                                )

        // loading the info file
        const plistFileString =
            fs.readFileSync( plistFilePath, 'utf8' )
        const infoJSON =
            plist.parse( plistFileString )

        // adding stuff to the plist data
        const newInfoJSON =
            Object.assign( infoJSON, darwinInfoPlistBase )

        // making new plist info
        const newPlistFileString =
            plist.build( newInfoJSON )

        // done, now saving it back
        fs.writeFileSync( plistFilePath, newPlistFileString )
    }

    async function createMacDMGImage ( ) {
        const orchestraMacAppAddress =
            "_release/Orchestra-darwin-x64/Orchestra.app"

        fs.mkdirpSync('./_installers/macOS')

        await shell(
            'electron-installer-dmg',
            orchestraMacAppAddress,
            'Orchestra',
            '--out="./_installers/macOS"',
            '--icon-size=152',
            '--icon="./designs/icon/icns/icon.icns"',
            '--background="./build/dmg-back.png"',
            '--overwrite'
        )
    }

//
// ─── PACK FOR LINUX ─────────────────────────────────────────────────────────────
//

    async function packOrchestraForLinux ( ) {
        // to be continued...
    }

//
// ─── PACK FOR WINDOWS ───────────────────────────────────────────────────────────
//

    async function packOrchestraForWindows ( ) {
        // to be continued...
    }

//
// ─── PACK ───────────────────────────────────────────────────────────────────────
//

    gulp.task( 'pack-orchestra', [ 'copyResourceFiles', 'sheets' ], callback => {
        async function packFunctionBody ( ) {
            if ( argv.debug )
                return await shell( 'npm', 'run', 'electron' )

            if ( argv.pack )
                await buildAllPlatforms( )

            if ( argv.installers )
                await createInstallersForAllPlatforms( )
        }

        packFunctionBody( )
            .then( callback )
            .catch( callback )
    })

//
// ─── BUILD FOR ALL PLATFORMS ────────────────────────────────────────────────────
//

    async function buildAllPlatforms ( ) {
        const platformFunctions = [ ]

        if ( argv.mac )
            platformFunctions.push( packOrchestraForDarwin )

        if ( argv.win )
            platformFunctions.push( packOrchestraForWindows )

        if ( argv.linux )
            platformFunctions.push( packOrchestraForLinux )

        await runAsyncFunctions( platformFunctions )
    }

//
// ─── CREATE INSTALLERS FOR ALL PLATFORMS ────────────────────────────────────────
//

    async function createInstallersForAllPlatforms ( ) {
        const platformFunctions = [ ]

        if ( argv.mac )
            platformFunctions.push( createMacDMGImage )

        await runAsyncFunctions(platformFunctions)
    }

//
// ─── RUN MANY ASYNC FUNCTIONS ───────────────────────────────────────────────────
//

    async function runAsyncFunctions ( functions ) {
        await Promise.all( functions.map( func => func( ) ) )
    }

//
// ─── AFTER PACK ─────────────────────────────────────────────────────────────────
//

    gulp.task( 'build-orchestra', [ 'pack-orchestra' ], ( ) => {

    })

//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//

    /** Where everything starts */
    gulp.task( 'default', [ 'build-orchestra' ])

// ────────────────────────────────────────────────────────────────────────────────
<|endoftext|>


<commit_before>// imports

const json     = require('./package.json')
const sync     = require('browser-sync')
const del      = require('del')
const fs       = require('fs')
const gulp     = require('gulp')
const notifier = require('node-notifier')
const rollup   = require('rollup')
const babel    = require('rollup-plugin-babel')
const uglify   = require('rollup-plugin-uglify')

// error handler

const onError = function(error) {
  notifier.notify({
    'title': 'Error',
    'message': 'Compilation failure.'
  })

  console.log(error)
  this.emit('end')
}

// clean

gulp.task('clean', () => del('dist/**/*.js', 'dist/**/*.map'))

// attribution

const attribution =
`/*!
 * Jump.js ${ json.version } - ${ json.description }
 * Copyright (c) ${ new Date().getFullYear() } ${ json.author } - ${ json.homepage }
 * License: ${ json.license }
 */

`

// js

const read = {
  entry: 'src/jump.js',
  sourceMap: true,
  plugins: [
    babel(),
    uglify()
  ]
}

const write = {
  format: 'umd',
  exports: 'default',
  moduleName: 'Jump',
  sourceMap: true
}

gulp.task('js', () => {
  return rollup
    .rollup(read)
    .then(bundle => {
      // generate the bundle
      const files = bundle.generate(write)

      // cache path to JS dist file
      const dist = 'dist/jump.min.js'

      // write the attribution
      fs.writeFileSync(dist, attribution)

      // write the JS and sourcemap
      fs.appendFileSync(dist, files.code)
      fs.writeFileSync('dist/maps/jump.js.map', files.map.toString())
    })
})

// server

const server = sync.create()
const reload = sync.reload

const sendMaps = (req, res, next) => {
  const filename = req.url.split('/').pop()
  const extension = filename.split('.').pop()

  if(extension === 'css' || extension === 'js') {
    res.setHeader('X-SourceMap', '/maps/' + filename + '.map')
  }

  return next()
}

const options = {
  notify: false,
  server: {
    baseDir: 'dist',
    middleware: [
      sendMaps
    ]
  },
  watchOptions: {
    ignored: '*.map'
  }
}

gulp.task('server', () => sync(options))

// watch

gulp.task('watch', () => {
  gulp.watch('src/jump.js', ['js', reload])
})

// build and default tasks

gulp.task('build', ['clean', 'js'])
gulp.task('default', ['build', 'server', 'watch'])
<commit_msg>add proper sequencing to build task<commit_after>// imports

const json     = require('./package.json')
const sync     = require('browser-sync')
const del      = require('del')
const fs       = require('fs')
const gulp     = require('gulp')
const notifier = require('node-notifier')
const rollup   = require('rollup')
const babel    = require('rollup-plugin-babel')
const uglify   = require('rollup-plugin-uglify')

// error handler

const onError = function(error) {
  notifier.notify({
    'title': 'Error',
    'message': 'Compilation failure.'
  })

  console.log(error)
  this.emit('end')
}

// clean

gulp.task('clean', () => del('dist/**/*.js', 'dist/**/*.map'))

// attribution

const attribution =
`/*!
 * Jump.js ${ json.version } - ${ json.description }
 * Copyright (c) ${ new Date().getFullYear() } ${ json.author } - ${ json.homepage }
 * License: ${ json.license }
 */

`

// js

const read = {
  entry: 'src/jump.js',
  sourceMap: true,
  plugins: [
    babel(),
    uglify()
  ]
}

const write = {
  format: 'umd',
  exports: 'default',
  moduleName: 'Jump',
  sourceMap: true
}

gulp.task('js', () => {
  return rollup
    .rollup(read)
    .then(bundle => {
      // generate the bundle
      const files = bundle.generate(write)

      // cache path to JS dist file
      const dist = 'dist/jump.min.js'

      // write the attribution
      fs.writeFileSync(dist, attribution)

      // write the JS and sourcemap
      fs.appendFileSync(dist, files.code)
      fs.writeFileSync('dist/maps/jump.js.map', files.map.toString())
    })
})

// server

const server = sync.create()
const reload = sync.reload

const sendMaps = (req, res, next) => {
  const filename = req.url.split('/').pop()
  const extension = filename.split('.').pop()

  if(extension === 'css' || extension === 'js') {
    res.setHeader('X-SourceMap', '/maps/' + filename + '.map')
  }

  return next()
}

const options = {
  notify: false,
  server: {
    baseDir: 'dist',
    middleware: [
      sendMaps
    ]
  },
  watchOptions: {
    ignored: '*.map'
  }
}

gulp.task('server', () => sync(options))

// watch

gulp.task('watch', () => {
  gulp.watch('src/jump.js', ['js', reload])
})

// build and default tasks

gulp.task('build', ['clean'], () => gulp.start('js'))
gulp.task('default', ['build', 'server', 'watch'])
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var ts = require('gulp-typescript');
var tsconfig = require('./tsconfig.json');
var exec = require('child_process').exec;

var paths = {
	bin: 'bin/**/*',
	typescript: 'src/**/*.ts',
	javascript: '**/*.js',
	metadata: ['**/package.json', '!node_modules/**/package.json', '**/tsconfig.json', '**/jsconfig.json']
}

gulp.task('compile', function () {
	return gulp
		.src(paths.typescript)
		.pipe(ts(tsconfig.compilerOptions))
		.pipe(gulp.dest('.'));
});

function updatePackage(version) {
	var originalContents = fs.readFileSync('package.json', 'utf8');
	var pkg = JSON.parse(originalContents);

	pkg.version = version;

	var updatedContents = JSON.stringify(pkg, null, '\t');
	fs.writeFileSync('package.json', updatedContents);
}

function appendVersionToBuildNumber(version) {
	var buildNumber = process.env.BUILD_BUILDNUMBER + '_' + version;
	console.log('##vso[build.updatebuildnumber]%s', buildNumber);
}

gulp.task('stamp', function (callback) {
	exec('git describe --abbrev=0', function (err, stdout, stderr) {
		var version = stdout.toString().split('\n')[0];
		console.log('git detected version was: %s', version);
		updatePackage(version);
		appendVersionToBuildNumber(version);
		callback(err);
	});
});

gulp.task('pack', function (callback) {
	exec('npm pack', function (err, stdout, stderr) {
		console.log(stdout);
		console.log(stderr);
		callback(err);
	});
});

gulp.task('watch', ['default'], function () {
	gulp.watch(paths.metadata, ['pack']);
	gulp.watch(paths.bin, ['pack']);
	gulp.watch(paths.javascript, ['pack']);
	gulp.watch(paths.typescript, ['compile']);
});

gulp.task('default', ['stamp', 'compile', 'pack']);<commit_msg>Added doc generation to the build.<commit_after>var gulp = require('gulp');
var fs = require('fs');
var ts = require('gulp-typescript');
var tsconfig = require('./tsconfig.json');
var exec = require('child_process').exec;

var paths = {
	bin: 'bin/**/*',
	typescript: 'src/**/*.ts',
	javascript: '**/*.js',
	docs: 'docs/**/*',
	metadata: ['**/package.json', '!node_modules/**/package.json', '**/tsconfig.json', '**/jsconfig.json']
}

gulp.task('compile', function () {
	return gulp
		.src(paths.typescript)
		.pipe(ts(tsconfig.compilerOptions))
		.pipe(gulp.dest('.'));
});

function updatePackage(version) {
	var originalContents = fs.readFileSync('package.json', 'utf8');
	var pkg = JSON.parse(originalContents);

	pkg.version = version;

	var updatedContents = JSON.stringify(pkg, null, '\t');
	fs.writeFileSync('package.json', updatedContents);
}

function appendVersionToBuildNumber(version) {
	var buildNumber = process.env.BUILD_BUILDNUMBER + '_' + version;
	console.log('##vso[build.updatebuildnumber]%s', buildNumber);
}

gulp.task('stamp', function (callback) {
	exec('git describe --abbrev=0', function (err, stdout, stderr) {
		var version = stdout.toString().split('\n')[0];
		console.log('git detected version was: %s', version);
		updatePackage(version);
		appendVersionToBuildNumber(version);
		callback(err);
	});
});

gulp.task('pack', function (callback) {
	exec('npm pack', function (err, stdout, stderr) {
		console.log(stdout);
		console.log(stderr);
		callback(err);
	});
});

gulp.task('docs', function (callback) {
	exec('make -C docs html', function(err, stdout, stderr) {
		console.log(stdout);
		console.log(stderr);
		callback(err);
	});
});

gulp.task('watch', ['default'], function () {
	gulp.watch(paths.metadata, ['pack']);
	gulp.watch(paths.bin, ['pack']);
	gulp.watch(paths.javascript, ['pack']);
	gulp.watch(paths.typescript, ['compile']);
	gulp.watch(paths.docs, ['docs']);
});

gulp.task('default', ['stamp', 'compile', 'pack', 'docs']);<|endoftext|>


<commit_before>var gulp = require('gulp');
var config = {
    directory: "./",
    js: "js/app.js",
    css: "css/app.css",
    icons: "node_modules/geomicons-open/icons/*.svg"
};

function build() {

    var nunjucks = require('static-engine-renderer-nunjucks');
    var render = require('static-engine-render');
    var page;

    nunjucks.configure('./templates/', {
        autoescape: true
    });

    render.configure('./');

    page = render('/index.html', nunjucks('index.html'));

    return page([{}]);
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var minifycss = require('gulp-minify-css');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src(config.css)
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(minifycss())
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('gulp-browserify');

    return gulp.src(config.js)
        .pipe(browserify())
        .pipe(uglify({
            preserveComments: 'some'
        }))
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function html(){

    var htmlmin = require('gulp-htmlmin');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(cheerio(function ($) {

            var uses = [];

            $('use').each(function(){

                $(this).replaceWith($('path' + $(this).attr('xlink:href')).clone());
            });

            $('svg defs').parent().remove();
        }))
        .pipe(gulp.dest(config.directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var concat = require('gulp-concat');
    var footer = require('gulp-footer');
    var header = require('gulp-header');

    return gulp.src(config.icons)
        .pipe(cheerio(function ($) {
            var $path = $('svg').children('path');
            var id = $('svg').attr('id');
            $path.attr('id', id);
            $('svg').replaceWith($path[0]);
        }))
        .pipe(concat('icons.svg'))
        .pipe(header(
            '<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'
        ))
        .pipe(footer('</defs></svg>'))
        .pipe(gulp.dest('templates/temp'));
}

gulp.task('default', gulp.series(icons, build, html, gulp.parallel(css, js)));

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

    gulp.watch(['css/**/**.css', 'js/**/**.js', 'templates/**/**.html'], 'default');
});

gulp.task('serve', gulp.parallel('default', 'watch', function(done){

    var express = require('express');
    var static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(static(config.directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8080, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}));
<commit_msg>Organize tasks better<commit_after>var gulp = require('gulp');
var config = {
    directory: "./",
    js: "js/app.js",
    css: "css/app.css",
    icons: "node_modules/geomicons-open/icons/*.svg"
};

function pages() {

    var nunjucks = require('static-engine-renderer-nunjucks');
    var render = require('static-engine-render');
    var page;

    nunjucks.configure('./templates/', {
        autoescape: true
    });

    render.configure('./');

    page = render('/index.html', nunjucks('index.html'));

    return page([{}]);
}

function css(){

    var autoprefixer = require('gulp-autoprefixer');
    var uncss = require('gulp-uncss');
    var minifycss = require('gulp-minify-css');
    var glob = require('glob');
    var rework = require('gulp-rework');
    var concat = require('gulp-concat');
    var calc = require('rework-calc');
    var media = require('rework-custom-media');
    var npm = require('rework-npm');
    var vars = require('rework-vars');
    var colors = require('rework-plugin-colors');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');

    return gulp.src(config.css)
        .pipe(rework(
            npm(),
            vars(),
            media(),
            calc,
            colors()
        ))
        .pipe(autoprefixer('> 1%', 'last 2 versions'))
        .pipe(concat("index.css"))
        .pipe(uncss({
            html: glob.sync('index.html')
        }))
        .pipe(minifycss())
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('head').append('<style type="text/css">'+file.contents+'</style>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function js() {

    var concat = require('gulp-concat');
    var uglify = require('gulp-uglify');
    var tap = require('gulp-tap');
    var cheerio = require('gulp-cheerio');
    var browserify = require('gulp-browserify');

    return gulp.src(config.js)
        .pipe(browserify())
        .pipe(uglify({
            preserveComments: 'some'
        }))
        .pipe(tap(function(file){

            return gulp.src('index.html')
                .pipe(cheerio(function($){

                    $('body').append('<script>'+file.contents+'</script>');
                }))
                .pipe(gulp.dest(config.directory));
        }));
}

function optimize(){

    var htmlmin = require('gulp-htmlmin');
    var cheerio = require('gulp-cheerio');

    return gulp.src('index.html')
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(cheerio(function ($) {

            var uses = [];

            $('use').each(function(){

                $(this).replaceWith($('path' + $(this).attr('xlink:href')).clone());
            });

            $('svg defs').parent().remove();
        }))
        .pipe(gulp.dest(config.directory));
}

function icons() {

    var cheerio = require('gulp-cheerio');
    var concat = require('gulp-concat');
    var footer = require('gulp-footer');
    var header = require('gulp-header');

    return gulp.src(config.icons)
        .pipe(cheerio(function ($) {
            var $path = $('svg').children('path');
            var id = $('svg').attr('id');
            $path.attr('id', id);
            $('svg').replaceWith($path[0]);
        }))
        .pipe(concat('icons.svg'))
        .pipe(header(
            '<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'
        ))
        .pipe(footer('</defs></svg>'))
        .pipe(gulp.dest('templates/temp'));
}

function serve(done){

    var express = require('express');
    var static = require('express-static');
    var logger = require('express-log');

    var app = express();

    app.use(logger());

    app.use(static(config.directory));

    app.use(function(req, res, next){

        res.redirect('/');
    });

    var server = app.listen(8080, function(){
        console.log('server is running at %s', server.address().port);
    });

    done();
}

function watch() {

    gulp.watch(['css/**/**.css', 'js/**/**.js', 'templates/**/**.html'], 'default');
}

gulp.task('default', gulp.series(icons, pages, optimize, gulp.parallel(css, js)));

gulp.task('dev', gulp.parallel('default', watch, serve));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var sass = require('gulp-sass')
var cleanCss = require('gulp-clean-css')
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var csscomb = require('gulp-csscomb');
var ejs = require("gulp-ejs");
var imagemin = require('gulp-imagemin');
var rimraf = require('rimraf');
var plumber = require('gulp-plumber');
var notify = require("gulp-notify");
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var concat = require('gulp-concat');

/**
 * 開発中のソースパス。
 */
var develop = {
  'ejs': ['develop/**/*.ejs', '!' + 'develop/**/_*.ejs'],
  'json': 'develop/assets/resources/site.json',
  'sass': 'develop/assets/sass/**/*.scss',
  'js': 'develop/assets/js/*.js',
  'vendor': 'develop/assets/js/vendor/**/*.js',
  'image': 'develop/assets/images/**/*.{png,jpg,gif,svg}'
}

/**
 * リリースパス。
 */
var release = {
  'root': 'release/',
  'html': 'release/',
  'css': 'release/css/',
  'js': 'release/js/',
  'vendor': 'release/js/vendor/',
  'image': 'release/images/'
}

/**
 * `.ejs`を`.html`にコンパイルしてから、リリースのためのディレクトリに吐きだします。
 */
var fs = require('fs');
var json = JSON.parse(fs.readFileSync(develop.json));
gulp.task('ejs', function() {
  gulp.src(develop.ejs)
  // jsonファイルを渡して、吐き出すファイルの拡張子を.htmlに変更する。
  .pipe(ejs(json, {"ext": ".html"}))
  .pipe(gulp.dest(release.html));
});

/**
 * `.scss`を`.css`にコンパイルしてから、リリースのためのディレクトリに吐きだします。
 * ベンダープレフィックスを付与後、csscombで整形されます。
 */
gulp.task('sass', function(){
  return gulp.src(develop.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(autoprefixer({
      browsers: ['last 4 versions'],
    }))
    .pipe(csscomb())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.css));
});

gulp.task('cleanCss', function(){
  return gulp.src(develop.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(autoprefixer({
      browsers: ['last 4 versions'],
    }))
    .pipe(csscomb())
    .pipe(rename({suffix: '.min'}))
    .pipe(cleanCss())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.css));
});

/**
 * デフォルトjsファイルとjQueryをリリースのためのディレクトリに吐きだします。
 */
gulp.task('js', function() {
  return gulp.src(develop.js)
    .pipe(gulp.dest(release.js));
});

/**
 * vendorsディレクトリにあるjQueryプラグインなどのファイルを連結してリリースディレクトリに吐き出します。
 */
gulp.task('vendor', function() {
  return gulp.src(develop.vendor)
    .pipe(sourcemaps.init())
    .pipe(concat('vendor.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.vendor));
});

/**
 * 画像ファイルをリリースのためのディレクトリに吐きだします。
 */
gulp.task('image', function() {
  return gulp.src(develop.image)
  .pipe(gulp.dest(release.image));
});

/**
 * 画像ファイルを圧縮後、リリースのためのディレクトリに吐きだします。
 */
gulp.task('imagemin', function() {
  return gulp.src(develop.image)
  .pipe(imagemin({
    // jpgをロスレス圧縮（画質を落とさず、メタデータを削除）。
    progressive: true,
    // gifをインターレースgifにします。
    interlaced: true,
    // PNGファイルの圧縮率（7が最高）を指定します。
    optimizationLevel: 7
  }))
  .pipe(gulp.dest(release.image));
});

/**
 * releaseディレクトリを削除します。
 */
gulp.task('clean', function (cb) {
  rimraf(release.root, cb);
});

/**
 * 一連のタスクを処理します（画像の圧縮はreleaseタスク）。
 */
gulp.task('build', ['ejs', 'sass', 'js', 'vendor', 'image']);

/**
 * watchタスクを指定します。
 */
gulp.task('watch', ['build'],function() {
  gulp.watch(develop.ejs, ['ejs']);
  gulp.watch(develop.sass, ['sass']);
  gulp.watch(develop.js, ['js']);
  gulp.watch(develop.vendor, ['vendor']);
  gulp.watch(develop.image, ['image']);
});

/**
 * ローカルサーバーを起動します。
 */
gulp.task('browser-sync', function() {
  browserSync({
    server: {
      baseDir: release.root,
      index: "index.html"
    }
  });
});

/**
 * 開発に使用するタスクです。
 * releaseディレクトリを削除後、watchタスクを処理します。
 */
gulp.task('default', ['clean'], function() {
  runSequence(
    'watch'
  )
});

/**
 * 開発に使用するタスクです。
 * releaseディレクトリを削除後、watchタスクを処理、
 * ブラウザを起動し、リアルタイムに更新を反映させます。
 */
gulp.task('develop', ['clean'], function() {
  runSequence(
    'watch',
    'browser-sync'
  )
});

/**
 * リリースに使用するタスクです。
 * releaseディレクトリを最新の状態にしてから、画像の圧縮をします。
 */
gulp.task('release', ['clean'], function() {
  runSequence(
    'ejs',
    'sass',
    'cleanCss',
    'js',
    'vendor',
    'imagemin'
  )
});<commit_msg>gulpfile.js内を整理<commit_after>var gulp = require('gulp');
var ejs = require("gulp-ejs");
var sass = require('gulp-sass')
var autoprefixer = require('gulp-autoprefixer');
var csscomb = require('gulp-csscomb');
var cleanCss = require('gulp-clean-css')
var imagemin = require('gulp-imagemin');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var rimraf = require('rimraf');
var plumber = require('gulp-plumber');
var notify = require("gulp-notify");
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');

/**
 * 開発中のソースパス。
 */
var develop = {
  'ejs': ['develop/**/*.ejs', '!' + 'develop/**/_*.ejs'],
  'json': 'develop/assets/resources/site.json',
  'sass': 'develop/assets/sass/**/*.scss',
  'js': 'develop/assets/js/*.js',
  'vendor': 'develop/assets/js/vendor/**/*.js',
  'image': 'develop/assets/images/**/*.{png,jpg,gif,svg}'
}

/**
 * リリースパス。ディレクトリ名はプロジェクトにあわせて変更します。
 */
var release = {
  'root': 'release/',
  'html': 'release/',
  'css': 'release/css/',
  'js': 'release/js/',
  'vendor': 'release/js/vendor/',
  'image': 'release/images/'
}

/**
 * `.ejs`を`.html`にコンパイルしてから、リリースディレクトリに出力します。
 */
var fs = require('fs');
var json = JSON.parse(fs.readFileSync(develop.json));
gulp.task('ejs', function() {
  return gulp.src(develop.ejs)
    // jsonファイルを渡して、吐き出すファイルの拡張子を.htmlに変更する。
    .pipe(ejs(json, {"ext": ".html"}))
    .pipe(gulp.dest(release.html));
});

/**
 * `.scss`を`.css`にコンパイルしてから、リリースディレクトリに出力します。
 * ベンダープレフィックスを付与後、csscombで整形されます。
 */
gulp.task('sass', function(){
  return gulp.src(develop.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(autoprefixer({
      browsers: ['last 4 versions'],
    }))
    .pipe(csscomb())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.css));
});

/**
 * sassタスクにミニファイとリネームを追加します。
 */
gulp.task('cleanCss', function(){
  return gulp.src(develop.sass)
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
    .pipe(autoprefixer({
      browsers: ['last 4 versions'],
    }))
    .pipe(csscomb())
    .pipe(rename({suffix: '.min'}))
    .pipe(cleanCss())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.css));
});

/**
 * デフォルトjsファイルとjQueryをリリースディレクトリに出力します。
 */
gulp.task('js', function() {
  return gulp.src(develop.js)
    .pipe(gulp.dest(release.js));
});

/**
 * vendorディレクトリにあるjQueryプラグインなどのファイルを連結してリリースディレクトリに出力します。
 */
gulp.task('vendor', function() {
  return gulp.src(develop.vendor)
    .pipe(sourcemaps.init())
    .pipe(concat('vendor.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(release.vendor));
});

/**
 * 画像ファイルをリリースディレクトリに出力します。
 */
gulp.task('image', function() {
  return gulp.src(develop.image)
    .pipe(gulp.dest(release.image));
});

/**
 * imageタスクに画像ファイルの圧縮を追加します。
 */
gulp.task('imagemin', function() {
  return gulp.src(develop.image)
    .pipe(imagemin({
      // jpgをロスレス圧縮（画質を落とさず、メタデータを削除）。
      progressive: true,
      // gifをインターレースgifにします。
      interlaced: true,
      // PNGファイルの圧縮率（7が最高）を指定します。
      optimizationLevel: 7
    }))
    .pipe(gulp.dest(release.image));
});

/**
 * releaseディレクトリを削除します。
 */
gulp.task('clean', function (cb) {
  rimraf(release.root, cb);
});

/**
 * 一連のタスクを処理します（画像の圧縮はreleaseタスクでおこないます）。
 */
gulp.task('build', ['ejs', 'sass', 'js', 'vendor', 'image']);

/**
 * watchタスクを指定します。
 */
gulp.task('watch', ['build'],function() {
  gulp.watch(develop.ejs, ['ejs']);
  gulp.watch(develop.sass, ['sass']);
  gulp.watch(develop.js, ['js']);
  gulp.watch(develop.vendor, ['vendor']);
  gulp.watch(develop.image, ['image']);
});

/**
 * ローカルサーバーを起動します。
 */
gulp.task('browser-sync', function() {
  browserSync({
    server: {
      baseDir: release.root,
      index: "index.html"
    }
  });
});

/**
 * 開発に使用するタスクです。
 * releaseディレクトリを削除後、watchタスクを処理します。
 */
gulp.task('default', ['clean'], function() {
  runSequence(
    'watch'
  )
});

/**
 * 開発に使用するタスクです。
 * gulpタスクにbrowser-syncを追加します。
 * ローカルサーバーを起動し、リアルタイムに更新を反映させます。
 */
gulp.task('develop', ['clean'], function() {
  runSequence(
    'watch',
    'browser-sync'
  )
});

/**
 * リリースに使用するタスクです。
 * releaseディレクトリを最新の状態にしてから、ファイルの圧縮をします。
 */
gulp.task('release', ['clean'], function() {
  runSequence(
    ['ejs', 'sass', 'cleanCss', 'js', 'vendor','imagemin']
  )
});<|endoftext|>