<commit_before>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var through = require('through2');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var gutil = require('gulp-util');
var download = require("gulp-download");
var shell = require('gulp-shell');
var jasmine = require('gulp-jasmine');
var jasmineBrowser = require('gulp-jasmine-browser');
var reporters = require('jasmine-reporters');
var babelify = require('babelify');
var babel = require('gulp-babel');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var replace = require('gulp-replace');
var decompress = require('gulp-decompress');
var fs = require("fs");
var runSequence = require('run-sequence');
var path = require('path');
var childProcess = require("child_process");
var minimist = require('minimist');
var cucumber = require('gulp-cucumber');
var merge = require('merge-stream');

gulp.task('default', ["test"]);

gulp.task('browser', function(cb){
  runSequence('build-browser-test', 'build-browser', cb);
});

/** Build all-in-one files for use in the browser */
gulp.task('build-browser', function () {
  var browserOutput = 'lib/browser';
  // Our app bundler
  var appBundler = browserify({
    entries: ['src/index.js'],
    cache: {},
    standalone: 'neo4j',
    packageCache: {}
  }).transform(babelify.configure({
    ignore: /external/
  })).bundle();

  // Un-minified browser package
  appBundler
    .on('error', gutil.log)
    .pipe(source('neo4j-web.js'))
    .pipe(gulp.dest(browserOutput));

  return appBundler
    .on('error', gutil.log)
    .pipe(source('neo4j-web.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(browserOutput));
});

gulp.task('build-browser-test', function(){
  var browserOutput = 'lib/browser/';
  var testFiles = [];
  return gulp.src('./test/**/*.test.js')
    .pipe( through.obj( function( file, enc, cb ) {
      if(file.path.indexOf('examples.test.js') < 0) {
        testFiles.push( file.path );
      }
      cb();
    }, function(cb) {
      // At end-of-stream, push the list of files to the next step
      this.push( testFiles );
      cb();
    }))
    .pipe( through.obj( function( testFiles, enc, cb) {
      browserify({
          entries: testFiles,
          cache: {},
          debug: true
        }).transform(babelify.configure({
          ignore: /external/
        }))
        .bundle(function(err, res){
          cb();
        })
        .on('error', gutil.log)
        .pipe(source('neo4j-web.test.js'))
        .pipe(gulp.dest(browserOutput))
    },
    function(cb) {
      cb()
    }
    ));
});

var buildNode = function(options) {
  return gulp.src(options.src)
    .pipe(babel({ignore: ['src/external/**/*.js']}))
    .pipe(gulp.dest(options.dest))
};

gulp.task('nodejs', function(){
  return buildNode({
    src: 'src/**/*.js',
    dest: 'lib'
    });
});

gulp.task('all', function(cb){
  runSequence('nodejs', 'browser', cb);
});

gulp.task('test', function(cb){
  runSequence('test-nodejs', 'test-browser', 'run-tck', cb);
});

gulp.task('test-nodejs', ['nodejs'], function () {
  return gulp.src('test/**/*.test.js')
        .pipe(jasmine({
            // reporter: new reporters.JUnitXmlReporter({
            //   savePath: "build/nodejs-test-reports",
            //   consolidateAll: false
            // }),
            includeStackTrace: true
        }));
});

gulp.task('test-browser', function (cb) {
  runSequence('all', 'run-browser-test', cb)
});

gulp.task('run-browser-test', function(){
  return gulp.src('lib/browser/neo4j-web.test.js')
    .pipe(jasmineBrowser.specRunner({console: true}))
    .pipe(jasmineBrowser.headless())
});

gulp.task('watch', function () {
  return watch('src/**/*.js', batch(function (events, done) {
      gulp.start('all', done);
  }));
});

gulp.task('watch-n-test', ['test-nodejs'], function () {
  return gulp.watch(['src/**/*.js', "test/**/*.js"], ['test-nodejs'] );
});

var featureFiles   = 'https://s3-eu-west-1.amazonaws.com/remoting.neotechnology.com/driver-compliance/tck.tar.gz';
var featureHome    = './build/tck';

gulp.task('download-tck', function() {
  return download(featureFiles)
        .pipe(decompress({strip: 1}))
        .pipe(gulp.dest(featureHome));
});

gulp.task('run-tck', ['download-tck', 'nodejs'], function() {
    return gulp.src(featureHome + "/*").pipe(cucumber({
        'steps': 'test/v1/tck/steps/*.js',
        'format': 'progress',
        'tags' : ['~@fixed_session_pool', '~@db', '~@equality', '~@streaming_and_cursor_navigation']
    }));
});

/** Set the project version, controls package.json and version.js */
gulp.task('set', function() {
  // Get the --version arg from command line
  var version = minimist(process.argv.slice(2), { string: 'version' }).version;

  // Change the version in relevant files
  return gulp.src(['package.json'], {base: "./"})
      .pipe(replace('0.0.0-dev', version))
      .pipe(gulp.dest('./'));

});

var neo4jHome  = path.resolve('./build/neo4j');
var neorunPath = path.resolve('./neokit/neorun.py');
var neorunStartArgsName = "--neorun.start.args"; // use this args to provide additional args for running neorun.start

gulp.task('start-neo4j', function() {

    var neorunStartArgs = '-p neo4j'; // default args to neorun.start: change the default password to neo4j
    process.argv.slice(2).forEach(function (val) {
        if(val.startsWith(neorunStartArgsName))
        {
            neorunStartArgs = val.split("=")[1];
        }
    });

    neorunStartArgs = neorunStartArgs.match(/\S+/g) || '';

    return runScript([
        neorunPath, '--start=' + neo4jHome
    ].concat( neorunStartArgs ) );
});

gulp.task('stop-neo4j', function() {
    return runScript([
        neorunPath, '--stop=' + neo4jHome
    ]);
});

var runScript = function(cmd) {
    var spawnSync = childProcess.spawnSync, child, code;
    child = spawnSync('python', cmd);
    console.log("Script Outputs:\n" + child.stdout.toString());
    var error = child.stderr.toString();
    if (error.trim() !== "")
        console.log("Script Errors:\n"+ error);
    code = child.status;
    if( code !==0 )
    {
        throw "Script finished with code " + code
    }
};
<commit_msg>Exit correctly when tests are failing in test sequence<commit_after>/**
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var through = require('through2');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var gutil = require('gulp-util');
var download = require("gulp-download");
var shell = require('gulp-shell');
var jasmine = require('gulp-jasmine');
var jasmineBrowser = require('gulp-jasmine-browser');
var reporters = require('jasmine-reporters');
var babelify = require('babelify');
var babel = require('gulp-babel');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var replace = require('gulp-replace');
var decompress = require('gulp-decompress');
var fs = require("fs");
var runSequence = require('run-sequence');
var path = require('path');
var childProcess = require("child_process");
var minimist = require('minimist');
var cucumber = require('gulp-cucumber');
var merge = require('merge-stream');

gulp.task('default', ["test"]);

gulp.task('browser', function(cb){
  runSequence('build-browser-test', 'build-browser', cb);
});

/** Build all-in-one files for use in the browser */
gulp.task('build-browser', function () {
  var browserOutput = 'lib/browser';
  // Our app bundler
  var appBundler = browserify({
    entries: ['src/index.js'],
    cache: {},
    standalone: 'neo4j',
    packageCache: {}
  }).transform(babelify.configure({
    ignore: /external/
  })).bundle();

  // Un-minified browser package
  appBundler
    .on('error', gutil.log)
    .pipe(source('neo4j-web.js'))
    .pipe(gulp.dest(browserOutput));

  return appBundler
    .on('error', gutil.log)
    .pipe(source('neo4j-web.min.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(browserOutput));
});

gulp.task('build-browser-test', function(){
  var browserOutput = 'lib/browser/';
  var testFiles = [];
  return gulp.src('./test/**/*.test.js')
    .pipe( through.obj( function( file, enc, cb ) {
      if(file.path.indexOf('examples.test.js') < 0) {
        testFiles.push( file.path );
      }
      cb();
    }, function(cb) {
      // At end-of-stream, push the list of files to the next step
      this.push( testFiles );
      cb();
    }))
    .pipe( through.obj( function( testFiles, enc, cb) {
      browserify({
          entries: testFiles,
          cache: {},
          debug: true
        }).transform(babelify.configure({
          ignore: /external/
        }))
        .bundle(function(err, res){
          cb();
        })
        .on('error', gutil.log)
        .pipe(source('neo4j-web.test.js'))
        .pipe(gulp.dest(browserOutput))
    },
    function(cb) {
      cb()
    }
    ));
});

var buildNode = function(options) {
  return gulp.src(options.src)
    .pipe(babel({ignore: ['src/external/**/*.js']}))
    .pipe(gulp.dest(options.dest))
};

gulp.task('nodejs', function(){
  return buildNode({
    src: 'src/**/*.js',
    dest: 'lib'
    });
});

gulp.task('all', function(cb){
  runSequence('nodejs', 'browser', cb);
});

gulp.task('test', function(cb){
  runSequence('test-nodejs', 'test-browser', 'run-tck', function (err) {
    if (err) {
      var exitCode = 2;
      console.log('[FAIL] test task failed - exiting with code ' + exitCode);
      return process.exit(exitCode);
    }
    return cb();
  });
});

gulp.task('test-nodejs', ['nodejs'], function () {
  return gulp.src('test/**/*.test.js')
        .pipe(jasmine({
            // reporter: new reporters.JUnitXmlReporter({
            //   savePath: "build/nodejs-test-reports",
            //   consolidateAll: false
            // }),
            includeStackTrace: true
        }));
});

gulp.task('test-browser', function (cb) {
  runSequence('all', 'run-browser-test', cb)
});

gulp.task('run-browser-test', function(){
  return gulp.src('lib/browser/neo4j-web.test.js')
    .pipe(jasmineBrowser.specRunner({console: true}))
    .pipe(jasmineBrowser.headless())
});

gulp.task('watch', function () {
  return watch('src/**/*.js', batch(function (events, done) {
      gulp.start('all', done);
  }));
});

gulp.task('watch-n-test', ['test-nodejs'], function () {
  return gulp.watch(['src/**/*.js', "test/**/*.js"], ['test-nodejs'] );
});

var featureFiles   = 'https://s3-eu-west-1.amazonaws.com/remoting.neotechnology.com/driver-compliance/tck.tar.gz';
var featureHome    = './build/tck';

gulp.task('download-tck', function() {
  return download(featureFiles)
        .pipe(decompress({strip: 1}))
        .pipe(gulp.dest(featureHome));
});

gulp.task('run-tck', ['download-tck', 'nodejs'], function() {
    return gulp.src(featureHome + "/*").pipe(cucumber({
        'steps': 'test/v1/tck/steps/*.js',
        'format': 'progress',
        'tags' : ['~@fixed_session_pool', '~@db', '~@equality', '~@streaming_and_cursor_navigation']
    }));
});

/** Set the project version, controls package.json and version.js */
gulp.task('set', function() {
  // Get the --version arg from command line
  var version = minimist(process.argv.slice(2), { string: 'version' }).version;

  // Change the version in relevant files
  return gulp.src(['package.json'], {base: "./"})
      .pipe(replace('0.0.0-dev', version))
      .pipe(gulp.dest('./'));

});

var neo4jHome  = path.resolve('./build/neo4j');
var neorunPath = path.resolve('./neokit/neorun.py');
var neorunStartArgsName = "--neorun.start.args"; // use this args to provide additional args for running neorun.start

gulp.task('start-neo4j', function() {

    var neorunStartArgs = '-p neo4j'; // default args to neorun.start: change the default password to neo4j
    process.argv.slice(2).forEach(function (val) {
        if(val.startsWith(neorunStartArgsName))
        {
            neorunStartArgs = val.split("=")[1];
        }
    });

    neorunStartArgs = neorunStartArgs.match(/\S+/g) || '';

    return runScript([
        neorunPath, '--start=' + neo4jHome
    ].concat( neorunStartArgs ) );
});

gulp.task('stop-neo4j', function() {
    return runScript([
        neorunPath, '--stop=' + neo4jHome
    ]);
});

var runScript = function(cmd) {
    var spawnSync = childProcess.spawnSync, child, code;
    child = spawnSync('python', cmd);
    console.log("Script Outputs:\n" + child.stdout.toString());
    var error = child.stderr.toString();
    if (error.trim() !== "")
        console.log("Script Errors:\n"+ error);
    code = child.status;
    if( code !==0 )
    {
        throw "Script finished with code " + code
    }
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var path = require('path');
var concatCss = require('gulp-concat-css');
var runSequence = require('run-sequence');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var imagemin = require('gulp-imagemin');
var processhtml = require('gulp-processhtml')
var clean = require('gulp-clean');

var paths = {
  css: ['src/bower_components/bootstrap/dist/css/bootstrap.css', 'temp/css/*.css'],
  js: ['src/bower_components/jquery/dist/jquery.js', 'src/js/index.js'],
  appImages: ['src/img/Icon.png'],
  appIcons: ['src/img/IconMouseOver.png', 'src/img/IconMouseNormal.png'],
  moveStoreImages: ['src/img/Icon.png', 'src/img/Screenshot1.jpg', 'src/img/Tile.jpg'],
  moveFonts: ['src/fonts/*.*'],
  moveManifest: ['src/other/manifest.json'],
  moveStoreFiles: ['src/other/store.json', 'src/other/description.txt']
};

// ---------- Build CSS ---------

gulp.task('buildCss', function(callback) {
  runSequence('buildless',
              'concatcss',
              'minifyCss',
              callback);
});

gulp.task('buildless', function () {
  return gulp.src('src/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('temp/css'));
});

gulp.task('concatcss', function () {
  return gulp.src(paths.css)
    .pipe(concatCss('css/bundle.css'))
    .pipe(gulp.dest('temp/'));
});

gulp.task('minifyCss', function() {
  return gulp.src('temp/css/bundle.css')
    .pipe(minifyCss({
      rebase: false
    }))
    .pipe(gulp.dest('dist/app/Files/css'));
});

// ---------- Build JS ---------

gulp.task('buildJs', function(callback) {
  runSequence('uglifyJs',
              callback);
});

gulp.task('uglifyJs', function() {
  return gulp.src(paths.js)
    .pipe(concat('bundle.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist/app/Files/js'));
});

// ---------- Build Images ---------

gulp.task('buildImages', function(callback) {
  runSequence(['buildAppImages', 'buildAppIcons'],
              callback);
});

gulp.task('buildAppImages', function () {
  return gulp.src(paths.appImages)
    .pipe(imagemin({
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('dist/app/Files/img'));
});

gulp.task('buildAppIcons', function () {
  return gulp.src(paths.appIcons)
    .pipe(imagemin({
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('dist/app'));
});

// ---------- Build HTML ---------

gulp.task('buildHtml', function () {
    return gulp.src('src/index.html')
               .pipe(processhtml())
               .pipe(gulp.dest('dist/app/Files'));
});

// ---------- Move files ---------

gulp.task('moveFiles', function(callback) {
  runSequence(['moveFonts', 'moveManifest', 'moveStoreFiles', 'moveStoreImages', 'moveChangelog'],
              callback);
});

gulp.task('moveFonts', function(){
  gulp.src(paths.moveFonts, { base: './src' })
  .pipe(gulp.dest('dist/app/Files'));
});

gulp.task('moveManifest', function(){
  gulp.src(paths.moveManifest, { base: './src/other' })
  .pipe(gulp.dest('dist/app'));
});

gulp.task('moveStoreFiles', function(){
  gulp.src(paths.moveStoreFiles, { base: './src/other' })
  .pipe(gulp.dest('dist/store'));
});

gulp.task('moveStoreImages', function(){
  gulp.src(paths.moveStoreImages, { base: './src/img' })
  .pipe(gulp.dest('dist/store'));
});

gulp.task('moveChangelog', function(){
  gulp.src('CHANGELOG.md', { base: './' })
  .pipe(gulp.dest('dist'));
});

// ---------- Clean tasks ---------

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

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

// ---------- Main build task ---------

gulp.task('build', function(callback) {
  runSequence('preClean',
              ['buildCss', 'buildJs', 'buildImages', 'buildHtml', 'moveFiles'],
              'postClean',
              callback);
});

// ---------- Run Tasks ---------

gulp.task('default', [ 'build' ]);<commit_msg>Fix css url rebasing<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var path = require('path');
var concatCss = require('gulp-concat-css');
var runSequence = require('run-sequence');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var imagemin = require('gulp-imagemin');
var processhtml = require('gulp-processhtml')
var clean = require('gulp-clean');

var paths = {
  css: ['src/bower_components/bootstrap/dist/css/bootstrap.css', 'temp/css/*.css'],
  js: ['src/bower_components/jquery/dist/jquery.js', 'src/js/index.js'],
  appImages: ['src/img/Icon.png'],
  appIcons: ['src/img/IconMouseOver.png', 'src/img/IconMouseNormal.png'],
  moveStoreImages: ['src/img/Icon.png', 'src/img/Screenshot1.jpg', 'src/img/Tile.jpg'],
  moveFonts: ['src/fonts/*.*'],
  moveManifest: ['src/other/manifest.json'],
  moveStoreFiles: ['src/other/store.json', 'src/other/description.txt']
};

// ---------- Build CSS ---------

gulp.task('buildCss', function(callback) {
  runSequence('buildless',
              'concatcss',
              callback);
});

gulp.task('buildless', function () {
  return gulp.src('src/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('temp/css'));
});

gulp.task('concatcss', function () {
  return gulp.src(paths.css)
    .pipe(concatCss('css/bundle.css', {rebaseUrls: false}))
    .pipe(minifyCss({rebase: false}))
    .pipe(gulp.dest('dist/app/Files'));
});

// ---------- Build JS ---------

gulp.task('buildJs', function(callback) {
  runSequence('uglifyJs',
              callback);
});

gulp.task('uglifyJs', function() {
  return gulp.src(paths.js)
    .pipe(concat('bundle.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist/app/Files/js'));
});

// ---------- Build Images ---------

gulp.task('buildImages', function(callback) {
  runSequence(['buildAppImages', 'buildAppIcons'],
              callback);
});

gulp.task('buildAppImages', function () {
  return gulp.src(paths.appImages)
    .pipe(imagemin({
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('dist/app/Files/img'));
});

gulp.task('buildAppIcons', function () {
  return gulp.src(paths.appIcons)
    .pipe(imagemin({
      optimizationLevel: 7
    }))
    .pipe(gulp.dest('dist/app'));
});

// ---------- Build HTML ---------

gulp.task('buildHtml', function () {
    return gulp.src('src/index.html')
               .pipe(processhtml())
               .pipe(gulp.dest('dist/app/Files'));
});

// ---------- Move files ---------

gulp.task('moveFiles', function(callback) {
  runSequence(['moveFonts', 'moveManifest', 'moveStoreFiles', 'moveStoreImages', 'moveChangelog'],
              callback);
});

gulp.task('moveFonts', function(){
  gulp.src(paths.moveFonts, { base: './src' })
  .pipe(gulp.dest('dist/app/Files'));
});

gulp.task('moveManifest', function(){
  gulp.src(paths.moveManifest, { base: './src/other' })
  .pipe(gulp.dest('dist/app'));
});

gulp.task('moveStoreFiles', function(){
  gulp.src(paths.moveStoreFiles, { base: './src/other' })
  .pipe(gulp.dest('dist/store'));
});

gulp.task('moveStoreImages', function(){
  gulp.src(paths.moveStoreImages, { base: './src/img' })
  .pipe(gulp.dest('dist/store'));
});

gulp.task('moveChangelog', function(){
  gulp.src('CHANGELOG.md', { base: './' })
  .pipe(gulp.dest('dist'));
});

// ---------- Clean tasks ---------

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

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

// ---------- Main build task ---------

gulp.task('build', function(callback) {
  runSequence('preClean',
              ['buildCss', 'buildJs', 'buildImages', 'buildHtml', 'moveFiles'],
              'postClean',
              callback);
});

// ---------- Run Tasks ---------

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


<commit_before>const gulp = require('gulp');
const gulpSync = require('gulp-sync')(gulp);
const requireDir = require('require-dir');
const packageJson = require('./package.json');

const baseConfig = {
	port: 3000,
	phpPort: 3838,
	localhost: 'localhost',
	packageJson: packageJson,
	format: packageJson.projectFormat ? packageJson.projectFormat : 'default',
	compressed: true
};

const wpThemePath = 'wordpress/wp-content/themes/' + packageJson.name;
const paths = {
	default: {
		basePath: 'www/',
		pagesDest: 'www/',
		stylesDest: 'www/css',
		fontsDest: 'www/fonts',
		imagesDest: 'www/images',
		scriptsDest: 'www/js'
	},
	wordpress: {
		basePath: 'wordpress/',
		pluginsWp: 'plugins/**/*.*',
		styleWp: 'src/style.css',
		configWp: 'wp-config.php',
		pagesDest: wpThemePath,
		fontsDest: wpThemePath + '/fonts',
		imagesDest: wpThemePath + '/images',
		stylesDest: wpThemePath + '/css',
		scriptsDest: wpThemePath + '/js',
		themesWp: 'wordpress/wp-content/themes/'
	}
};

const devPaths = {
	pages: 'src/**/*.php',
	scripts: 'src/js/**/*.js',
	styles: 'src/css/**/*.sass',
	images: 'src/images/**/*.*',
	fonts: 'src/fonts/**/*.*'
};

gulp.paths = Object.assign(devPaths, paths[baseConfig.format]);
gulp.config = baseConfig;

// Gulp tasks
requireDir('tasks');

gulp.task('default', gulpSync.sync(['build', 'watch', 'connect-sync']));

gulp.task('wp', gulpSync.sync(['wp-install']));

gulp.task('build', gulpSync.sync([
	'clean', 'styles', 'scripts', 'pages', 'images', 'fonts', 'libs'
]));

gulp.task('watch', () => {
	gulp.watch(gulp.paths.styles, ['styles']);
	gulp.watch(gulp.paths.scripts, ['scripts']);
	gulp.watch(gulp.paths.pages, ['pages']);
	gulp.watch(gulp.paths.images, ['images']);
	gulp.watch(gulp.paths.fonts, ['fonts']);
});
<commit_msg>Fix bug with wordpress generated files<commit_after>const gulp = require('gulp');
const gulpSync = require('gulp-sync')(gulp);
const requireDir = require('require-dir');
const packageJson = require('./package.json');

let defaultTasks = ['build', 'watch', 'connect-sync'];

if (packageJson.projectFormat === 'wordpress') {
	defaultTasks.push('wp-build');
}

const baseConfig = {
	port: 3000,
	phpPort: 3838,
	localhost: 'localhost',
	packageJson: packageJson,
	format: packageJson.projectFormat ? packageJson.projectFormat : 'default',
	compressed: true
};

const wpThemePath = 'wordpress/wp-content/themes/' + packageJson.name;
const paths = {
	default: {
		basePath: 'www/',
		pagesDest: 'www/',
		stylesDest: 'www/css',
		fontsDest: 'www/fonts',
		imagesDest: 'www/images',
		scriptsDest: 'www/js'
	},
	wordpress: {
		basePath: 'wordpress/',
		pluginsWp: 'plugins/**/*.*',
		styleWp: 'src/style.css',
		configWp: 'wp-config.php',
		pagesDest: wpThemePath,
		fontsDest: wpThemePath + '/fonts',
		imagesDest: wpThemePath + '/images',
		stylesDest: wpThemePath + '/css',
		scriptsDest: wpThemePath + '/js',
		themesWp: 'wordpress/wp-content/themes/'
	}
};

const devPaths = {
	pages: 'src/**/*.php',
	scripts: 'src/js/**/*.js',
	styles: 'src/css/**/*.sass',
	images: 'src/images/**/*.*',
	fonts: 'src/fonts/**/*.*'
};

gulp.paths = Object.assign(devPaths, paths[baseConfig.format]);
gulp.config = baseConfig;

// Gulp tasks
requireDir('tasks');

gulp.task('default', gulpSync.sync(defaultTasks));

gulp.task('wp', gulpSync.sync(['wp-install']));

gulp.task('build', gulpSync.sync([
	'clean', 'styles', 'scripts', 'pages', 'images', 'fonts', 'libs'
]));

gulp.task('watch', () => {
	gulp.watch(gulp.paths.styles, ['styles']);
	gulp.watch(gulp.paths.scripts, ['scripts']);
	gulp.watch(gulp.paths.pages, ['pages']);
	gulp.watch(gulp.paths.images, ['images']);
	gulp.watch(gulp.paths.fonts, ['fonts']);
});
<|endoftext|>


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

var paths = {
  mochaTests: ['test/**/*[Tt]ests.js'],
  jasmineTests: ['test/**/*.Spec.js'],
  filesToLint: ['./lib/**/*.js', './test/**/*.js', 'gulpfile.js'],
  sourceJSFilesForCodeCoverage: ['./lib/**/*.js']
};

gulp.task('jscs', function() {
  return gulp.src(paths.filesToLint)
  .pipe($.jscs());
});

gulp.task('jscs-watch', ['jscs'], function() {
  $.watch(paths.filesToLint, function () {
    gulp.start('jscs');
  });
});

gulp.task('jshint', function() {
  return gulp.src(paths.filesToLint)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('test', ['jshint', 'jscs'], function(){
  return gulp.src(paths.mochaTests, { read: false })
  .pipe($.mocha({
    reporter: 'spec',
    slow: 500,
    timeout: 2000,
    globals: { }
  }));
});

gulp.task('coverage', function (cb) {
  gulp.src(paths.sourceJSFilesForCodeCoverage)
    .pipe($.istanbul()) // Covering files
    .pipe($.istanbul.hookRequire())
    .on('finish', function () {
      gulp.src(paths.mochaTests, { read: false })
      .pipe($.mocha({ reporter: 'dot' }))
      .pipe($.istanbul.writeReports()) // Creating the reports after tests ran
      .on('finish', function() {
        process.chdir(__dirname);
        cb();
      });
    });
});

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

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

gulp.task('default', ["test", "jshint"]);
<commit_msg>log finish coveralls<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var path = require('path');

var paths = {
  mochaTests: ['test/**/*[Tt]ests.js'],
  jasmineTests: ['test/**/*.Spec.js'],
  filesToLint: ['./lib/**/*.js', './test/**/*.js', 'gulpfile.js'],
  sourceJSFilesForCodeCoverage: ['./lib/**/*.js']
};

gulp.task('jscs', function() {
  return gulp.src(paths.filesToLint)
  .pipe($.jscs());
});

gulp.task('jscs-watch', ['jscs'], function() {
  $.watch(paths.filesToLint, function () {
    gulp.start('jscs');
  });
});

gulp.task('jshint', function() {
  return gulp.src(paths.filesToLint)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('test', ['jshint', 'jscs'], function(){
  return gulp.src(paths.mochaTests, { read: false })
  .pipe($.mocha({
    reporter: 'spec',
    slow: 500,
    timeout: 2000,
    globals: { }
  }));
});

gulp.task('coverage', function (cb) {
  gulp.src(paths.sourceJSFilesForCodeCoverage)
    .pipe($.istanbul()) // Covering files
    .pipe($.istanbul.hookRequire())
    .on('finish', function () {
      gulp.src(paths.mochaTests, { read: false })
      .pipe($.mocha({ reporter: 'dot' }))
      .pipe($.istanbul.writeReports()) // Creating the reports after tests ran
      .on('finish', function() {
        process.chdir(__dirname);
        cb();
      });
    });
});

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

  return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
    .pipe($.coveralls())
    .on('end', function () {
      console.log("Coverage published to coveralls.io");
    });
});

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


<commit_before>//
// BEGIN - gulp.js
//

//
// === DEPENDENCIES ===
//

var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var del = require('del');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var sourcemap = require('gulp-sourcemaps');
var vinylPaths = require('vinyl-paths');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require("gulp-uglify");
var imagemin = require('gulp-imagemin');
var htmlreplace = require('gulp-html-replace');
var replace = require('gulp-replace');
var sh = require('shelljs');
var karma = require('karma').server;
var ngConstant = require('gulp-ng-constant');
var extend = require('gulp-extend');
var gulpif = require('gulp-if');
var minifyHtml    = require('gulp-minify-html');
var templateCache = require('gulp-angular-templatecache');
var inject = require('gulp-inject');

//
// === PATHS ===
//

// Files
//
// Note: change the 'ionicbundle' entry below from 'ionic.bundle.min.js' to 'ionic.bundle.js' to debug "moduleErr"
// errors in a production build ("gulp build") - see explanation:
//
// http://www.chrisgmyr.com/2014/08/debugging-uncaught-error-injectormodulerr-in-angularjs/
//
// (the unminified ionic.bundle.js needs to have the extra console.log statement as explained in the article)
//
var files = {
  jsbundle: 'app.bundle.min.js',
  appcss: 'app.css',
  ionicappmincss: 'ionic.app.min.css',
  ionicbundle: 'ionic.bundle.min.js'    // change to 'ionic.bundle.js' for debugging moduleErr errors
};
// Paths
var paths = {
  sass: ['./scss/**/*.scss'],
  css: ['./src/css/**/*.css'],
  scripts: [
    './src/js/**/*.js',
    '!./src/js/config/config.js'   /* exclude config.js: handled separately */
  ],
  injectedScripts: [
    './src/js/app/**/*.js',
    '!./src/js/app/app.js',                   /* exclude the root module ('app' module) files */
    '!./src/js/app/application.ctrl.js',      /* exclude the root module ('app' module) files */
    '!./src/js/app/application.service.js'    /* exclude the root module ('app' module) files */
  ],
  images: ['./src/img/**/*'],
  templates: ['./src/js/**/*.html'],
  indexTemplate: ['./src/index-template.html'],
  index: ['./src/index.html'],
  extras: [],  /* whatever extra files we need */
  ionicfonts: ['./src/lib/ionic/fonts/*'],
  lib: [
    './src/lib/ionic/js/' + files.ionicbundle,
    './src/lib/parse/parse.min.js',
    './src/lib/angular-resource/angular-resource.min.js',
    './src/lib/angular-messages/angular-messages.min.js',
    './src/lib/angular-elastic/elastic.js',
    './src/lib/ngCordova/dist/ng-cordova.min.js',
    './src/lib/ionic-service-core/ionic-core.js',             /* Ionic.io libraries, to do: minify */
    './src/lib/ionic-service-analytics/ionic-analytics.js'    /* Ionic.io libraries, to do: minify */
    ],
  dist: ['./www']
};

//
// === TOP LEVEL TASKS (invoke with "gulp <task-name>") ===
//

// default task for DEV

gulp.task('default', ['dev-config', 'dev-sass', 'inject-index']);

// watch task for DEV
//
// NOTE: inject-index commented out because this isn't reliable within the "watch" task - so, if you add or remove
// Javascript files and you want to inject them into index.html, then you just need to restart "ionic serve" so that
// the "default" task can re-run 'inject-index'

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['dev-sass' /*, 'inject-index'*/]);
});

// karma tasks for TEST

var runtest = function (single) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: single,
    autoWatch: !single
  });
};

gulp.task('test', function (done) {
  runtest(false), done;
});

gulp.task('test-single', function (done) {
  runtest(true), done;
});

// build task for PROD

// Note: use before 'ionic build' or 'ionic run'.
// See: https://github.com/driftyco/ionic-cli/issues/345#issuecomment-88659079
gulp.task('build', ['clean', 'sass', 'scripts', 'prod-config', 'imagemin', 'templates',
                    'inject-index', 'index', 'copy']);

// utility tasks for DEV/PROD/TEST (whichever)

gulp.task('jshint', function() {
  gulp.src(paths.scripts)
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//
// === CHILD TASKS ===
//

// use 'del' instead of 'clean', see: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md
gulp.task('clean', function (cb) {
  del([
    paths.dist + '/**/*'
  ], cb);
});

var dosass = function(minify, sourcemaps, done) {
  gulp.src('./scss/ionic.app.scss')
  .pipe(sass())
  // this keeps the gulp build from crashing when there are errors in your SASS file
  .on("error", function(err) {
    console.log(err.toString());
    this.emit("end");
  })
  .pipe(gulp.dest(paths.dist + '/css/'))
  .pipe(gulpif(sourcemaps, sourcemap.init()))
  .pipe(gulpif(minify, minifyCss({
    keepSpecialComments: 0
  })))
  // delete the source file, see: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md#delete-files-in-a-pipeline
  .pipe(vinylPaths(del))
  .pipe(gulpif(sourcemaps, sourcemap.write()))
  .pipe(gulpif(minify, rename({ extname: '.min.css' })))
  .pipe(gulp.dest('./src/css/'))
  .on('end', done);
};

gulp.task('sass', ['clean'], function(done) {
  dosass(
    true,
    false,  // set to TRUE to get source maps
    done
  );
});

gulp.task('dev-sass', function(done) {
  dosass(
    false,
    false,
    done
  );
});

// scripts - clean dist dir then annotate, uglify, concat
gulp.task('scripts', ['clean'], function() {
  gulp.src(paths.scripts)
    .pipe(ngAnnotate({
      remove: true,
      add: true,
      single_quotes: true,
      regexp: "appModule(.*)$"  /* NOTE: this makes ngAnnotate work right even when defining modules with "appModule(...)" instead of "angular.module()" */
    }))
    .pipe(uglify())
    .pipe(concat(files.jsbundle))
    .pipe(gulp.dest(paths.dist + '/js'));
});

var config = function(src, dest) {
  gulp.src(['src/js/config/config-base.json', src])
    .pipe(extend('config.json', true))
    .pipe(ngConstant({
      deps: false
    }))
    .pipe(rename(function(path) {
      path.basename = 'config';
      path.extname = '.js';
    }))
    .pipe(gulp.dest(dest));
};

gulp.task('prod-config', ['clean'], function() {
  config('src/js/config/config-prod.json', paths.dist + '/js/config')
});

gulp.task('dev-config', function() {
  config('src/js/config/config-dev.json', 'src/js/config')
});

// imagemin images and output them in dist
gulp.task('imagemin', ['clean'], function() {
  gulp.src(paths.images)
    .pipe(imagemin())
    .pipe(gulp.dest(paths.dist + '/img'));
});

// inspired by: http://forum.ionicframework.com/t/could-i-set-up-ionic-in-such-a-way-that-it-downloads-an-entire-spa-upfront/7565/5
gulp.task('templates', ['clean', 'scripts'], function() {
  gulp.src(paths.templates)
    .pipe(minifyHtml({empty: true}))
    .pipe(templateCache({
      standalone: true,
      root: 'js'
    }))
    .pipe(gulp.dest(paths.dist + '/js'));
});

// inject javascript paths into index-template.html, producing index.html
gulp.task('inject-index', function() {
  gulp.src(paths.indexTemplate)
    .pipe(inject(
      gulp.src(paths.injectedScripts,
        {read: false}), {relative: true}))
    .pipe(rename(function(path) {
      path.basename = 'index';
      path.extname = '.html';
    }))
    .pipe(gulp.dest('./src/'));
});

// prepare index.html for dist - i.e. using minimized files
gulp.task('index', ['clean', 'inject-index'], function() {
  gulp.src(paths.index)
    .pipe(htmlreplace({
      'sass': 'css/ionic.app.min.css',
      'css': 'css/app.min.css',
      'js': 'js/app.bundle.min.js',
      'ionic': 'lib/ionic/js/' + files.ionicbundle
    }))
    // https://www.airpair.com/ionic-framework/posts/production-ready-apps-with-ionic-framework
    .pipe(replace(/<body /, '<body ng-strict-di '))
    .pipe(gulp.dest(paths.dist + '/.'));
});

// copy all other files to dist directly
gulp.task('copy', ['clean', 'sass'], function() {

  gulp.src(paths.ionicfonts)
    .pipe(gulp.dest(paths.dist + '/lib/ionic/fonts'));

  // 'base' option, see: http://www.levihackwith.com/how-to-make-gulp-copy-a-directory-and-its-contents/
  gulp.src(paths.lib, {base: './src/lib'})
    .pipe(gulp.dest(paths.dist + '/lib'));

  gulp.src('./src/css/' + files.ionicappmincss)
    .pipe(gulp.dest(paths.dist + '/css'));

  gulp.src(paths.lib, {base: './src/lib'})
    .pipe(gulp.dest(paths.dist + '/lib'));

  gulp.src(paths.extras)
    .pipe(gulp.dest(paths.dist + '/.')
  );
});

//
// === OTHER TASKS (used by Ionic CLI ?) ===
//

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

//
// END
//
<commit_msg>fixed gulp file: libs were copied 2 times<commit_after>//
// BEGIN - gulp.js
//

//
// === DEPENDENCIES ===
//

var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var del = require('del');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var sourcemap = require('gulp-sourcemaps');
var vinylPaths = require('vinyl-paths');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require("gulp-uglify");
var imagemin = require('gulp-imagemin');
var htmlreplace = require('gulp-html-replace');
var replace = require('gulp-replace');
var sh = require('shelljs');
var karma = require('karma').server;
var ngConstant = require('gulp-ng-constant');
var extend = require('gulp-extend');
var gulpif = require('gulp-if');
var minifyHtml    = require('gulp-minify-html');
var templateCache = require('gulp-angular-templatecache');
var inject = require('gulp-inject');

//
// === PATHS ===
//

// Files
//
// Note: change the 'ionicbundle' entry below from 'ionic.bundle.min.js' to 'ionic.bundle.js' to debug "moduleErr"
// errors in a production build ("gulp build") - see explanation:
//
// http://www.chrisgmyr.com/2014/08/debugging-uncaught-error-injectormodulerr-in-angularjs/
//
// (the unminified ionic.bundle.js needs to have the extra console.log statement as explained in the article)
//
var files = {
  jsbundle: 'app.bundle.min.js',
  appcss: 'app.css',
  ionicappmincss: 'ionic.app.min.css',
  ionicbundle: 'ionic.bundle.min.js'    // change to 'ionic.bundle.js' for debugging moduleErr errors
};
// Paths
var paths = {
  sass: ['./scss/**/*.scss'],
  css: ['./src/css/**/*.css'],
  scripts: [
    './src/js/**/*.js',
    '!./src/js/config/config.js'   /* exclude config.js: handled separately */
  ],
  injectedScripts: [
    './src/js/app/**/*.js',
    '!./src/js/app/app.js',                   /* exclude the root module ('app' module) files */
    '!./src/js/app/application.ctrl.js',      /* exclude the root module ('app' module) files */
    '!./src/js/app/application.service.js'    /* exclude the root module ('app' module) files */
  ],
  images: ['./src/img/**/*'],
  templates: ['./src/js/**/*.html'],
  indexTemplate: ['./src/index-template.html'],
  index: ['./src/index.html'],
  extras: [],  /* whatever extra files we need */
  ionicfonts: ['./src/lib/ionic/fonts/*'],
  lib: [
    './src/lib/ionic/js/' + files.ionicbundle,
    './src/lib/parse/parse.min.js',
    './src/lib/angular-resource/angular-resource.min.js',
    './src/lib/angular-messages/angular-messages.min.js',
    './src/lib/angular-elastic/elastic.js',
    './src/lib/ngCordova/dist/ng-cordova.min.js',
    './src/lib/ionic-service-core/ionic-core.js',             /* Ionic.io libraries, to do: minify */
    './src/lib/ionic-service-analytics/ionic-analytics.js'    /* Ionic.io libraries, to do: minify */
    ],
  dist: ['./www']
};

//
// === TOP LEVEL TASKS (invoke with "gulp <task-name>") ===
//

// default task for DEV

gulp.task('default', ['dev-config', 'dev-sass', 'inject-index']);

// watch task for DEV
//
// NOTE: inject-index commented out because this isn't reliable within the "watch" task - so, if you add or remove
// Javascript files and you want to inject them into index.html, then you just need to restart "ionic serve" so that
// the "default" task can re-run 'inject-index'

gulp.task('watch', function() {
  gulp.watch(paths.sass, ['dev-sass' /*, 'inject-index'*/]);
});

// karma tasks for TEST

var runtest = function (single) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: single,
    autoWatch: !single
  });
};

gulp.task('test', function (done) {
  runtest(false), done;
});

gulp.task('test-single', function (done) {
  runtest(true), done;
});

// build task for PROD

// Note: use before 'ionic build' or 'ionic run'.
// See: https://github.com/driftyco/ionic-cli/issues/345#issuecomment-88659079
gulp.task('build', ['clean', 'sass', 'scripts', 'prod-config', 'imagemin', 'templates',
                    'inject-index', 'index', 'copy']);

// utility tasks for DEV/PROD/TEST (whichever)

gulp.task('jshint', function() {
  gulp.src(paths.scripts)
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//
// === CHILD TASKS ===
//

// use 'del' instead of 'clean', see: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md
gulp.task('clean', function (cb) {
  del([
    paths.dist + '/**/*'
  ], cb);
});

var dosass = function(minify, sourcemaps, done) {
  gulp.src('./scss/ionic.app.scss')
  .pipe(sass())
  // this keeps the gulp build from crashing when there are errors in your SASS file
  .on("error", function(err) {
    console.log(err.toString());
    this.emit("end");
  })
  .pipe(gulp.dest(paths.dist + '/css/'))
  .pipe(gulpif(sourcemaps, sourcemap.init()))
  .pipe(gulpif(minify, minifyCss({
    keepSpecialComments: 0
  })))
  // delete the source file, see: https://github.com/gulpjs/gulp/blob/master/docs/recipes/delete-files-folder.md#delete-files-in-a-pipeline
  .pipe(vinylPaths(del))
  .pipe(gulpif(sourcemaps, sourcemap.write()))
  .pipe(gulpif(minify, rename({ extname: '.min.css' })))
  .pipe(gulp.dest('./src/css/'))
  .on('end', done);
};

gulp.task('sass', ['clean'], function(done) {
  dosass(
    true,
    false,  // set to TRUE to get source maps
    done
  );
});

gulp.task('dev-sass', function(done) {
  dosass(
    false,
    false,
    done
  );
});

// scripts - clean dist dir then annotate, uglify, concat
gulp.task('scripts', ['clean'], function() {
  gulp.src(paths.scripts)
    .pipe(ngAnnotate({
      remove: true,
      add: true,
      single_quotes: true,
      regexp: "appModule(.*)$"  /* NOTE: this makes ngAnnotate work right even when defining modules with "appModule(...)" instead of "angular.module()" */
    }))
    .pipe(uglify())
    .pipe(concat(files.jsbundle))
    .pipe(gulp.dest(paths.dist + '/js'));
});

var config = function(src, dest) {
  gulp.src(['src/js/config/config-base.json', src])
    .pipe(extend('config.json', true))
    .pipe(ngConstant({
      deps: false
    }))
    .pipe(rename(function(path) {
      path.basename = 'config';
      path.extname = '.js';
    }))
    .pipe(gulp.dest(dest));
};

gulp.task('prod-config', ['clean'], function() {
  config('src/js/config/config-prod.json', paths.dist + '/js/config')
});

gulp.task('dev-config', function() {
  config('src/js/config/config-dev.json', 'src/js/config')
});

// imagemin images and output them in dist
gulp.task('imagemin', ['clean'], function() {
  gulp.src(paths.images)
    .pipe(imagemin())
    .pipe(gulp.dest(paths.dist + '/img'));
});

// inspired by: http://forum.ionicframework.com/t/could-i-set-up-ionic-in-such-a-way-that-it-downloads-an-entire-spa-upfront/7565/5
gulp.task('templates', ['clean', 'scripts'], function() {
  gulp.src(paths.templates)
    .pipe(minifyHtml({empty: true}))
    .pipe(templateCache({
      standalone: true,
      root: 'js'
    }))
    .pipe(gulp.dest(paths.dist + '/js'));
});

// inject javascript paths into index-template.html, producing index.html
gulp.task('inject-index', function() {
  gulp.src(paths.indexTemplate)
    .pipe(inject(
      gulp.src(paths.injectedScripts,
        {read: false}), {relative: true}))
    .pipe(rename(function(path) {
      path.basename = 'index';
      path.extname = '.html';
    }))
    .pipe(gulp.dest('./src/'));
});

// prepare index.html for dist - i.e. using minimized files
gulp.task('index', ['clean', 'inject-index'], function() {
  gulp.src(paths.index)
    .pipe(htmlreplace({
      'sass': 'css/ionic.app.min.css',
      'css': 'css/app.min.css',
      'js': 'js/app.bundle.min.js',
      'ionic': 'lib/ionic/js/' + files.ionicbundle
    }))
    // https://www.airpair.com/ionic-framework/posts/production-ready-apps-with-ionic-framework
    .pipe(replace(/<body /, '<body ng-strict-di '))
    .pipe(gulp.dest(paths.dist + '/.'));
});

// copy all other files to dist directly
gulp.task('copy', ['clean', 'sass'], function() {

  gulp.src(paths.ionicfonts)
    .pipe(gulp.dest(paths.dist + '/lib/ionic/fonts'));

  // 'base' option, see: http://www.levihackwith.com/how-to-make-gulp-copy-a-directory-and-its-contents/
  gulp.src(paths.lib, {base: './src/lib'})
    .pipe(gulp.dest(paths.dist + '/lib'));

  gulp.src('./src/css/' + files.ionicappmincss)
    .pipe(gulp.dest(paths.dist + '/css'));

  gulp.src(paths.extras)
    .pipe(gulp.dest(paths.dist + '/.')
  );
});

//
// === OTHER TASKS (used by Ionic CLI ?) ===
//

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

//
// END
//
<|endoftext|>


<commit_before>var gulp = require('gulp');
var ts = require('gulp-typescript');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var ddescribeIit = require('gulp-ddescribe-iit');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var gulpFile = require('gulp-file');
var del = require('del');
var merge = require('merge2');
var clangFormat = require('clang-format');
var gulpFormat = require('gulp-clang-format');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var webpack = require('webpack');

var PATHS = {
  src: 'src/**/*.ts',
  srcIndex: 'src/index.ts',
  specs: 'src/**/*.spec.ts',
  demo: 'demo/**/*.ts',
  demoDist: 'demo/dist/**/*',
  typings: 'typings/index.d.ts',
  jasmineTypings: 'typings/globals/jasmine/index.d.ts',
  demoDocsJson: 'demo/src/docs.json'
};

function webpackCallBack(taskName, gulpDone) {
  return function(err, stats) {
    if (err) throw new gutil.PluginError(taskName, err);
    gutil.log("[" + taskName + "]", stats.toString());
    gulpDone();
  }
}

// Transpiling & Building

var csjProject = ts.createProject('tsconfig.json', {declaration: true});
var esmProject = ts.createProject('tsconfig-es2015.json');

gulp.task('clean:build', function() { return del('dist/'); });

gulp.task('cjs', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings, '!' + PATHS.specs]).pipe(sourcemaps.init()).pipe(ts(csjProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/'), tsResult.js.pipe(gulp.dest('dist/')))
  ]);
});

gulp.task('esm', function() {
  var tsResult =
      gulp.src([PATHS.src, PATHS.jasmineTypings, '!' + PATHS.specs]).pipe(sourcemaps.init()).pipe(ts(esmProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/esm')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/esm'), tsResult.js.pipe(gulp.dest('dist/esm')))
  ]);
});

gulp.task('umd', function(cb) {
  function ngExternal(ns) {
    var ng2Ns = '@angular/' + ns;
    return {root: ['ng', ns], commonjs: ng2Ns, commonjs2: ng2Ns, amd: ng2Ns};
  }

  webpack(
      {
        entry: './dist/index.js',
        output: {filename: 'dist/bundles/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'},
        externals: {'@angular/core': ngExternal('core'), '@angular/common': ngExternal('common')}
      },
      webpackCallBack('webpack', cb));
});

gulp.task('npm', function() {
  var pkgJson = require('./package.json');
  var targetPkgJson = {};
  var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

  targetPkgJson['name'] = '@ng-bootstrap/ng-bootstrap';

  fieldsToCopy.forEach(function(field) { targetPkgJson[field] = pkgJson[field]; });

  targetPkgJson['main'] = 'index.js';
  targetPkgJson['jsnext:main'] = 'esm/index.js';

  targetPkgJson.peerDependencies = {};
  Object.keys(pkgJson.dependencies).forEach(function(dependency) {
    targetPkgJson.peerDependencies[dependency] = '^' + pkgJson.dependencies[dependency];
  });

  return gulp.src('README.md')
      .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
      .pipe(gulp.dest('dist'));
});

// Testing

var testProject = ts.createProject('tsconfig.json');

function startKarmaServer(isTddMode, done) {
  var karmaServer = require('karma').Server;
  var travis = process.env.TRAVIS;

  var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode};

  if (travis) {
    config['reporters'] = ['dots'];
    config['browsers'] = ['Firefox'];
  }

  new karmaServer(config, done).start();
}

gulp.task('clean:tests', function() { return del('temp/'); });

gulp.task('build:tests', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings]).pipe(sourcemaps.init()).pipe(ts(testProject));

  return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp'));
});

gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); });

gulp.task(
    'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); });

gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); });

gulp.task('tdd', ['clean:build-tests'], function(done) {
  startKarmaServer(true, function(err) {
    done(err);
    process.exit(1);
  });

  gulp.watch(PATHS.src, ['build:tests']);
});

// Formatting

gulp.task('lint', function() {
  return gulp.src(PATHS.src).pipe(tslint({configuration: require('./tslint.json')})).pipe(tslint.report('prose', {
    summarizeFailureOutput: true
  }));
});

gulp.task('check-format', function() {
  return doCheckFormat().on(
      'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

function doCheckFormat() {
  return gulp
      .src([
        'gulpfile.js', 'karma-test-shim.js', 'misc/api-doc.js', 'misc/api-doc.spec.js', 'misc/demo-gen.js', PATHS.src
      ])
      .pipe(gulpFormat.checkFormat('file', clangFormat));
}

// Demo

gulp.task('generate-docs', function() {
  var getApiDocs = require('./misc/get-doc');
  var jsonfile = require('jsonfile');

  var docs = getApiDocs();
  jsonfile.writeFileSync(PATHS.demoDocsJson, docs);
});

gulp.task('clean:demo', function() { return del('demo/dist'); });

gulp.task('clean:demo-cache', function() { return del('.publish/'); });

gulp.task(
    'demo-server', ['generate-docs'],
    shell.task(['webpack-dev-server --port 9090 --config webpack.demo.js --hot --inline --progress']));

gulp.task(
    'build:demo', ['clean:demo', 'generate-docs'],
    shell.task(['MODE=build webpack --config webpack.demo.js --progress --profile --bail']));

gulp.task('demo-push', function() { return gulp.src(PATHS.demoDist).pipe(ghPages()); });

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:tests', 'clean:demo', 'clean:demo-cache']);

gulp.task('build', function(done) {
  runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'esm', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function(done) { runSequence('clean:demo', 'build:demo', 'demo-push', 'clean:demo-cache', done); });

gulp.task('default', function(done) { runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', done); });
<commit_msg>chore(build): exclude Jasmine matchers from build results<commit_after>var gulp = require('gulp');
var ts = require('gulp-typescript');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var ddescribeIit = require('gulp-ddescribe-iit');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var gulpFile = require('gulp-file');
var del = require('del');
var merge = require('merge2');
var clangFormat = require('clang-format');
var gulpFormat = require('gulp-clang-format');
var runSequence = require('run-sequence');
var tslint = require('gulp-tslint');
var webpack = require('webpack');

var PATHS = {
  src: 'src/**/*.ts',
  srcIndex: 'src/index.ts',
  specs: 'src/**/*.spec.ts',
  testHelpers: 'src/util/matchers.ts',
  demo: 'demo/**/*.ts',
  demoDist: 'demo/dist/**/*',
  typings: 'typings/index.d.ts',
  jasmineTypings: 'typings/globals/jasmine/index.d.ts',
  demoDocsJson: 'demo/src/docs.json'
};

function webpackCallBack(taskName, gulpDone) {
  return function(err, stats) {
    if (err) throw new gutil.PluginError(taskName, err);
    gutil.log("[" + taskName + "]", stats.toString());
    gulpDone();
  }
}

// Transpiling & Building

var cjsProject = ts.createProject('tsconfig.json', {declaration: true});
var esmProject = ts.createProject('tsconfig-es2015.json');

gulp.task('clean:build', function() { return del('dist/'); });

gulp.task('cjs', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(cjsProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/'), tsResult.js.pipe(gulp.dest('dist/')))
  ]);
});

gulp.task('esm', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.jasmineTypings, '!' + PATHS.specs, '!' + PATHS.testHelpers])
                     .pipe(sourcemaps.init())
                     .pipe(ts(esmProject));

  return merge([
    tsResult.dts.pipe(gulp.dest('dist/esm')),
    tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('dist/esm'), tsResult.js.pipe(gulp.dest('dist/esm')))
  ]);
});

gulp.task('umd', function(cb) {
  function ngExternal(ns) {
    var ng2Ns = '@angular/' + ns;
    return {root: ['ng', ns], commonjs: ng2Ns, commonjs2: ng2Ns, amd: ng2Ns};
  }

  webpack(
      {
        entry: './dist/index.js',
        output: {filename: 'dist/bundles/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'},
        externals: {'@angular/core': ngExternal('core'), '@angular/common': ngExternal('common')}
      },
      webpackCallBack('webpack', cb));
});

gulp.task('npm', function() {
  var pkgJson = require('./package.json');
  var targetPkgJson = {};
  var fieldsToCopy = ['version', 'description', 'keywords', 'author', 'repository', 'license', 'bugs', 'homepage'];

  targetPkgJson['name'] = '@ng-bootstrap/ng-bootstrap';

  fieldsToCopy.forEach(function(field) { targetPkgJson[field] = pkgJson[field]; });

  targetPkgJson['main'] = 'index.js';
  targetPkgJson['jsnext:main'] = 'esm/index.js';

  targetPkgJson.peerDependencies = {};
  Object.keys(pkgJson.dependencies).forEach(function(dependency) {
    targetPkgJson.peerDependencies[dependency] = '^' + pkgJson.dependencies[dependency];
  });

  return gulp.src('README.md')
      .pipe(gulpFile('package.json', JSON.stringify(targetPkgJson, null, 2)))
      .pipe(gulp.dest('dist'));
});

// Testing

var testProject = ts.createProject('tsconfig.json');

function startKarmaServer(isTddMode, done) {
  var karmaServer = require('karma').Server;
  var travis = process.env.TRAVIS;

  var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode};

  if (travis) {
    config['reporters'] = ['dots'];
    config['browsers'] = ['Firefox'];
  }

  new karmaServer(config, done).start();
}

gulp.task('clean:tests', function() { return del('temp/'); });

gulp.task('build:tests', function() {
  var tsResult = gulp.src([PATHS.src, PATHS.typings]).pipe(sourcemaps.init()).pipe(ts(testProject));

  return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp'));
});

gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); });

gulp.task(
    'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); });

gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); });

gulp.task('tdd', ['clean:build-tests'], function(done) {
  startKarmaServer(true, function(err) {
    done(err);
    process.exit(1);
  });

  gulp.watch(PATHS.src, ['build:tests']);
});

// Formatting

gulp.task('lint', function() {
  return gulp.src(PATHS.src).pipe(tslint({configuration: require('./tslint.json')})).pipe(tslint.report('prose', {
    summarizeFailureOutput: true
  }));
});

gulp.task('check-format', function() {
  return doCheckFormat().on(
      'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); });
});

gulp.task('enforce-format', function() {
  return doCheckFormat().on('warning', function(e) {
    console.log("ERROR: You forgot to run clang-format on your change.");
    console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format");
    process.exit(1);
  });
});

function doCheckFormat() {
  return gulp
      .src([
        'gulpfile.js', 'karma-test-shim.js', 'misc/api-doc.js', 'misc/api-doc.spec.js', 'misc/demo-gen.js', PATHS.src
      ])
      .pipe(gulpFormat.checkFormat('file', clangFormat));
}

// Demo

gulp.task('generate-docs', function() {
  var getApiDocs = require('./misc/get-doc');
  var jsonfile = require('jsonfile');

  var docs = getApiDocs();
  jsonfile.writeFileSync(PATHS.demoDocsJson, docs);
});

gulp.task('clean:demo', function() { return del('demo/dist'); });

gulp.task('clean:demo-cache', function() { return del('.publish/'); });

gulp.task(
    'demo-server', ['generate-docs'],
    shell.task(['webpack-dev-server --port 9090 --config webpack.demo.js --hot --inline --progress']));

gulp.task(
    'build:demo', ['clean:demo', 'generate-docs'],
    shell.task(['MODE=build webpack --config webpack.demo.js --progress --profile --bail']));

gulp.task('demo-push', function() { return gulp.src(PATHS.demoDist).pipe(ghPages()); });

// Public Tasks
gulp.task('clean', ['clean:build', 'clean:tests', 'clean:demo', 'clean:demo-cache']);

gulp.task('build', function(done) {
  runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'esm', 'umd', 'npm', done);
});

gulp.task(
    'deploy-demo', function(done) { runSequence('clean:demo', 'build:demo', 'demo-push', 'clean:demo-cache', done); });

gulp.task('default', function(done) { runSequence('lint', 'enforce-format', 'ddescribe-iit', 'test', done); });
<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp'),
	sass = require('gulp-sass'),
	del = require('del');

gulp.task('sass', function () {
	return gulp.src('./src/scss/**/*.scss')
		.pipe(sass({
			errLogToConsole: true
		}))
		.pipe(gulp.dest('./dist/css'));
});

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

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

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

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

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

gulp.task('static:clean', function () {
	return del.sync('./gh-pages/vendor/wikia-style-guide/dist/**');
});

gulp.task('dist:clean', function () {
	return del.sync('./dist/**');
});

gulp.task('update-static', [
	'dist:clean',
	'static:clean',
	'svg:icons',
	'svg:images',
	'sass',
	'vendor',
	'scripts',
	'templates'
], function () {
	return gulp.src('./dist/**/*')
		.pipe(gulp.dest('./gh-pages/vendor/wikia-style-guide/dist'));
});

gulp.task('watch', function () {
	gulp.watch('./src/**/*')
		.on('change', function () {
			gulp.start('update-static');
		});
});
<commit_msg>run all tasks when starting gulp watch<commit_after>'use strict';
var gulp = require('gulp'),
	sass = require('gulp-sass'),
	del = require('del');

gulp.task('sass', function () {
	return gulp.src('./src/scss/**/*.scss')
		.pipe(sass({
			errLogToConsole: true
		}))
		.pipe(gulp.dest('./dist/css'));
});

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

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

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

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

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

gulp.task('static:clean', function () {
	return del.sync('./gh-pages/vendor/wikia-style-guide/dist/**');
});

gulp.task('dist:clean', function () {
	return del.sync('./dist/**');
});

gulp.task('update-static', [
	'dist:clean',
	'static:clean',
	'svg:icons',
	'svg:images',
	'sass',
	'vendor',
	'scripts',
	'templates'
], function () {
	return gulp.src('./dist/**/*')
		.pipe(gulp.dest('./gh-pages/vendor/wikia-style-guide/dist'));
});

gulp.task('watch', ['update-static'], function () {
	gulp.watch('./src/**/*')
		.on('change', function () {
			gulp.start('update-static');
		});
});
<|endoftext|>


<commit_before>/**
*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const gulp = require('gulp');
const gulpProcess = require('gulp-process');
const gutil = require('gulp-util');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const handlebars = require('gulp-handlebars');
const rename = require('gulp-rename');
const debug = require('gulp-debug');
const gzip = require('gulp-gzip');
const uglify = require('gulp-uglify');
const defineModule = require('gulp-define-module');
const sass = require('gulp-sass');
const revAll = require('gulp-rev-all');
const respawn = require('respawn');
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const rollup = require('rollup-stream');
const rollupBabel = require('rollup-plugin-babel');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');

const production = process.env.NODE_ENV == 'production';

const paths = {
  serverScripts: {
    src: 'server/**/*.js',
    dest: 'build/'
  },
  serverTemplates: {
    src: 'server/templates/**/*.hbs',
    dest: 'build/templates'
  },
  sharedScripts: {
    src: 'shared/**/*.js',
    dest: 'build/shared'
  },
  scss: {
    src: 'client/css/**/*.scss',
    dest: 'build/static/css'
  },
  postProcess: {
    src: 'build/static/**/*.@(css|js|svg|map)',
    dest: 'build/static'
  }
};

const serverProcess = respawn(['node', `${paths.serverScripts.dest}/index.js`]);
const databaseProcess = respawn(['docker', 'start', '-a', 'bwq-mongo']);

// hook up the logging
for (const process of [serverProcess, databaseProcess]) {
  process.on('stdout', data => gutil.log(data.toString('utf-8')));
  process.on('stderr', data => gutil.log(data.toString('utf-8')));
  process.on('warn', data => gutil.log(data.toString('utf-8')));
}

// shut down gracefully
process.on('SIGINT', () => {
  serverProcess.stop(() => {
    databaseProcess.stop(() => {
      process.exit();
    });
  });
});

process.on('uncaughtException', () => {
  serverProcess.stop();
  databaseProcess.stop();
});

// TASKS:

function waitTask(ms) {
  return () => new Promise(r => setTimeout(r, ms));
}

function clean() {
  return del(['build']);
}

function serverScripts() {
  return gulp.src(paths.serverScripts.src, {
    since: gulp.lastRun(serverScripts)
  }).pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['stage-3'],
      plugins: ["transform-es2015-modules-commonjs", ["transform-react-jsx", { "pragma":"h" }]]
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.serverScripts.dest));
}

function sharedScripts() {
  return gulp.src(paths.sharedScripts.src, {
    since: gulp.lastRun(sharedScripts)
  }).pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['stage-3'],
      plugins: ["transform-es2015-modules-commonjs", ["transform-react-jsx", { "pragma":"h" }]]
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.sharedScripts.dest));
}

function serverTemplates() {
  return gulp.src(paths.serverTemplates.src, {
    since: gulp.lastRun(serverTemplates)
  }).pipe(handlebars())
    .pipe(defineModule('node'))
    .pipe(gulp.dest(paths.serverTemplates.dest));
}

function server() {
  serverProcess.start();
}

function databaseServer() {
  databaseProcess.start();
}

function serverRestart(cb) {
  serverProcess.stop(() => {
    serverProcess.start();
    cb();
  });
}

function scss() {
  return gulp.src(paths.scss.src, {
    since: gulp.lastRun(scss)
  }).pipe(sourcemaps.init())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.scss.dest));
}

function createScriptTask(src, dest) {
  const parsedPath = path.parse(src);
  let cache;
  return function script() {
    return rollup({
      entry: src,
      sourceMap: true,
      cache,
      format: 'iife',
      plugins: [
        nodeResolve({
          preferBuiltins: false,
          browser: true,
          jsnext: true,
          main: true
        }),
        commonjs({
          ignoreGlobal: true
        }),
        rollupBabel({
          presets: ['stage-3', ['es2015', {modules: false}]],
          plugins: [["transform-react-jsx", {pragma:"h"}], "external-helpers"]
        })
      ]
    }).on('bundle', function(bundle) {
      cache = bundle;
    }).pipe(source('index.js', parsedPath.dir))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(rename({basename: /\/([^\/]+)$/.exec(parsedPath.dir)[1]}))
      .pipe(production ? uglify() : gutil.noop())
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest(dest));
  }
}

const browserScripts = [
  {src: './client/js/main/index.js', dest: './build/static/js'},
  {src: './client/js/admin/index.js', dest: './build/static/js'},
  {src: './client/js/presentation/index.js', dest: './build/static/js'}
];

for (const item of browserScripts) {
  item.task = createScriptTask(item.src, item.dest);
}

function postProcess() {
  return gulp.src(paths.postProcess.src)
    .pipe(revAll.revision())
    .pipe(gzip({skipGrowingFiles: true}))
    .pipe(gulp.dest(paths.postProcess.dest))
    .pipe(revAll.manifestFile())
    .pipe(gulp.dest(paths.postProcess.dest));
}

function watch() {
  const browserScriptTasks = browserScripts.map(i => i.task);

  // server
  gulp.watch(paths.serverScripts.src, gulp.series(serverScripts, serverRestart));
  gulp.watch(paths.serverTemplates.src, gulp.series(serverTemplates, serverRestart));
  gulp.watch(paths.sharedScripts.src, gulp.series(sharedScripts, gulp.parallel(...browserScriptTasks), serverRestart));

  // client
  gulp.watch(paths.scss.src, scss);

  for (const item of browserScripts) {
    gulp.watch(path.parse(item.src).dir + '/**/*.js', item.task);
  }
}

gulp.task('serverTemplates', serverTemplates);
gulp.task('postProcess', postProcess);
gulp.task('browserScripts', gulp.parallel(...browserScripts.map(i => i.task)));

const mainBuild = gulp.series(
  clean,
  gulp.parallel(serverScripts, serverTemplates, sharedScripts, scss, 'browserScripts')
);

gulp.task('build', gulp.series(mainBuild, postProcess));

gulp.task('serve', gulp.series(
  mainBuild,
  gulp.parallel(
    databaseServer,
    // Wait for database to start up
    // TODO: I should find a better way to do this
    gulp.series(waitTask(1500), server),
    watch
  )
));
<commit_msg>This doesn't catch imported files<commit_after>/**
*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const gulp = require('gulp');
const gulpProcess = require('gulp-process');
const gutil = require('gulp-util');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const handlebars = require('gulp-handlebars');
const rename = require('gulp-rename');
const debug = require('gulp-debug');
const gzip = require('gulp-gzip');
const uglify = require('gulp-uglify');
const defineModule = require('gulp-define-module');
const sass = require('gulp-sass');
const revAll = require('gulp-rev-all');
const respawn = require('respawn');
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const rollup = require('rollup-stream');
const rollupBabel = require('rollup-plugin-babel');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');

const production = process.env.NODE_ENV == 'production';

const paths = {
  serverScripts: {
    src: 'server/**/*.js',
    dest: 'build/'
  },
  serverTemplates: {
    src: 'server/templates/**/*.hbs',
    dest: 'build/templates'
  },
  sharedScripts: {
    src: 'shared/**/*.js',
    dest: 'build/shared'
  },
  scss: {
    src: 'client/css/**/*.scss',
    dest: 'build/static/css'
  },
  postProcess: {
    src: 'build/static/**/*.@(css|js|svg|map)',
    dest: 'build/static'
  }
};

const serverProcess = respawn(['node', `${paths.serverScripts.dest}/index.js`]);
const databaseProcess = respawn(['docker', 'start', '-a', 'bwq-mongo']);

// hook up the logging
for (const process of [serverProcess, databaseProcess]) {
  process.on('stdout', data => gutil.log(data.toString('utf-8')));
  process.on('stderr', data => gutil.log(data.toString('utf-8')));
  process.on('warn', data => gutil.log(data.toString('utf-8')));
}

// shut down gracefully
process.on('SIGINT', () => {
  serverProcess.stop(() => {
    databaseProcess.stop(() => {
      process.exit();
    });
  });
});

process.on('uncaughtException', () => {
  serverProcess.stop();
  databaseProcess.stop();
});

// TASKS:

function waitTask(ms) {
  return () => new Promise(r => setTimeout(r, ms));
}

function clean() {
  return del(['build']);
}

function serverScripts() {
  return gulp.src(paths.serverScripts.src, {
    since: gulp.lastRun(serverScripts)
  }).pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['stage-3'],
      plugins: ["transform-es2015-modules-commonjs", ["transform-react-jsx", { "pragma":"h" }]]
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.serverScripts.dest));
}

function sharedScripts() {
  return gulp.src(paths.sharedScripts.src, {
    since: gulp.lastRun(sharedScripts)
  }).pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['stage-3'],
      plugins: ["transform-es2015-modules-commonjs", ["transform-react-jsx", { "pragma":"h" }]]
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.sharedScripts.dest));
}

function serverTemplates() {
  return gulp.src(paths.serverTemplates.src, {
    since: gulp.lastRun(serverTemplates)
  }).pipe(handlebars())
    .pipe(defineModule('node'))
    .pipe(gulp.dest(paths.serverTemplates.dest));
}

function server() {
  serverProcess.start();
}

function databaseServer() {
  databaseProcess.start();
}

function serverRestart(cb) {
  serverProcess.stop(() => {
    serverProcess.start();
    cb();
  });
}

function scss() {
  return gulp.src(paths.scss.src)
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.scss.dest));
}

function createScriptTask(src, dest) {
  const parsedPath = path.parse(src);
  let cache;
  return function script() {
    return rollup({
      entry: src,
      sourceMap: true,
      cache,
      format: 'iife',
      plugins: [
        nodeResolve({
          preferBuiltins: false,
          browser: true,
          jsnext: true,
          main: true
        }),
        commonjs({
          ignoreGlobal: true
        }),
        rollupBabel({
          presets: ['stage-3', ['es2015', {modules: false}]],
          plugins: [["transform-react-jsx", {pragma:"h"}], "external-helpers"]
        })
      ]
    }).on('bundle', function(bundle) {
      cache = bundle;
    }).pipe(source('index.js', parsedPath.dir))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(rename({basename: /\/([^\/]+)$/.exec(parsedPath.dir)[1]}))
      .pipe(production ? uglify() : gutil.noop())
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest(dest));
  }
}

const browserScripts = [
  {src: './client/js/main/index.js', dest: './build/static/js'},
  {src: './client/js/admin/index.js', dest: './build/static/js'},
  {src: './client/js/presentation/index.js', dest: './build/static/js'}
];

for (const item of browserScripts) {
  item.task = createScriptTask(item.src, item.dest);
}

function postProcess() {
  return gulp.src(paths.postProcess.src)
    .pipe(revAll.revision())
    .pipe(gzip({skipGrowingFiles: true}))
    .pipe(gulp.dest(paths.postProcess.dest))
    .pipe(revAll.manifestFile())
    .pipe(gulp.dest(paths.postProcess.dest));
}

function watch() {
  const browserScriptTasks = browserScripts.map(i => i.task);

  // server
  gulp.watch(paths.serverScripts.src, gulp.series(serverScripts, serverRestart));
  gulp.watch(paths.serverTemplates.src, gulp.series(serverTemplates, serverRestart));
  gulp.watch(paths.sharedScripts.src, gulp.series(sharedScripts, gulp.parallel(...browserScriptTasks), serverRestart));

  // client
  gulp.watch(paths.scss.src, scss);

  for (const item of browserScripts) {
    gulp.watch(path.parse(item.src).dir + '/**/*.js', item.task);
  }
}

gulp.task('serverTemplates', serverTemplates);
gulp.task('postProcess', postProcess);
gulp.task('browserScripts', gulp.parallel(...browserScripts.map(i => i.task)));

const mainBuild = gulp.series(
  clean,
  gulp.parallel(serverScripts, serverTemplates, sharedScripts, scss, 'browserScripts')
);

gulp.task('build', gulp.series(mainBuild, postProcess));

gulp.task('serve', gulp.series(
  mainBuild,
  gulp.parallel(
    databaseServer,
    // Wait for database to start up
    // TODO: I should find a better way to do this
    gulp.series(waitTask(1500), server),
    watch
  )
));
<|endoftext|>


<commit_before>var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var scsslint = require('gulp-scss-lint');
var stylish = require('jshint-stylish');

// Target these browsers for adding vendor prefixes to CSS
var BROWSERS = [
  "> 5%",
  "ie > 0",
  "Firefox > 0",
  "Chrome > 0",
  "Opera > 0",
  "OperaMobile > 0",
  "OperaMini > 0",
  "Safari > 0",
  "iOS > 0",
  "Blackberry > 0",
  "Android > 0"
];

// Initialize browser-sync and proxy web server
gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Pattern Library",
    server: {
      baseDir: "./dev"
    }
  });
});

// Get the patterns ready for distribution
gulp.task('dist', function() {
  gulp.src(['dev/patterns/**/*.scss', 'dev/patterns/**/*.md'])
    .pipe(plumber())
    .pipe(gulp.dest('dist/patterns'));

  gulp.src('dev/*.scss')
    .pipe(plumber())
    .pipe(rename('_pattern-library.scss'))
    .pipe(gulp.dest('dist'));

  gulp.src('dev/images/*.png')
    .pipe(plumber())
    .pipe(gulp.dest('dist/images'));
});

// Lint JavaScript and JSON files.
gulp.task('jslint', function() {
  return gulp.src(['*.json', '*.js', 'dist/patterns/**/*.json'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// Full Browser Reload (HTML, JS, JSON files)
gulp.task('reload', reload);

// Lint Sass files (.scss)
gulp.task('scss-lint', function() {
  gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
    .pipe(scsslint());
});

// Compile and prefix Sass code into CSS,
// then reload the browser (stream when possible).
gulp.task('sass', function() {
  gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: BROWSERS
    }))
    .pipe(gulp.dest('dev'))
    .pipe(browserSync.stream());
});

// Watch for changes on these files
// Run these specific tasks when files change.
gulp.task('watch', function() {
  gulp.watch(['dev/patterns/**/html/*.html', 'dev/patterns/*.html']).on('change', reload);
  gulp.watch(['*.json', '*.js', 'dist/patterns/**/*.json', 'dev/patterns/*.js'], ['jslint']).on('change', reload);
  gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'scss-lint', 'dist']);
});

// Default task -- run these tasks.
gulp.task('default', ['browser-sync', 'sass', 'dist', 'watch']);
<commit_msg>Comment out scss-lint stuff<commit_after>var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var rename = require('gulp-rename');
var sass = require('gulp-sass');
// var scsslint = require('gulp-scss-lint');
var stylish = require('jshint-stylish');

// Target these browsers for adding vendor prefixes to CSS
var BROWSERS = [
  "> 5%",
  "ie > 0",
  "Firefox > 0",
  "Chrome > 0",
  "Opera > 0",
  "OperaMobile > 0",
  "OperaMini > 0",
  "Safari > 0",
  "iOS > 0",
  "Blackberry > 0",
  "Android > 0"
];

// Initialize browser-sync and proxy web server
gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Pattern Library",
    server: {
      baseDir: "./dev"
    }
  });
});

// Get the patterns ready for distribution
gulp.task('dist', function() {
  gulp.src(['dev/patterns/**/*.scss', 'dev/patterns/**/*.md'])
    .pipe(plumber())
    .pipe(gulp.dest('dist/patterns'));

  gulp.src('dev/*.scss')
    .pipe(plumber())
    .pipe(rename('_pattern-library.scss'))
    .pipe(gulp.dest('dist'));

  gulp.src('dev/images/*.png')
    .pipe(plumber())
    .pipe(gulp.dest('dist/images'));
});

// Lint JavaScript and JSON files.
gulp.task('jslint', function() {
  return gulp.src(['*.json', '*.js', 'dist/patterns/**/*.json'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// Full Browser Reload (HTML, JS, JSON files)
gulp.task('reload', reload);

// Lint Sass files (.scss)
// gulp.task('scss-lint', function() {
//   gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
//     .pipe(scsslint());
// });

// Compile and prefix Sass code into CSS,
// then reload the browser (stream when possible).
gulp.task('sass', function() {
  gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: BROWSERS
    }))
    .pipe(gulp.dest('dev'))
    .pipe(browserSync.stream());
});

// Watch for changes on these files
// Run these specific tasks when files change.
gulp.task('watch', function() {
  gulp.watch(['dev/patterns/**/html/*.html', 'dev/patterns/*.html']).on('change', reload);
  gulp.watch(['*.json', '*.js', 'dist/patterns/**/*.json', 'dev/patterns/*.js'], ['jslint']).on('change', reload);
  gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'dist']);
  // If you have scss-lint:
  // gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'scss-lint', 'dist']);
});

// Default task -- run these tasks.
gulp.task('default', ['browser-sync', 'sass', 'dist', 'watch']);
<|endoftext|>


<commit_before>'use strict'

var join = require('path').join
var EventEmitter = require('events')

var pull = require('pull-stream')
var ref = require('ssb-ref')
var ssbKeys = require('ssb-keys')

var u = require('./util')

function isString (s) {
  return typeof s === 'string'
}

function errorCB (err) {
  if (err) throw err
}

module.exports = function (path, opts, keys) {
  //_ was legacy db. removed that, but for backwards compatibilty reasons do not change interface
  if(!path) throw new Error('path must be provided')

  keys = keys || ssbKeys.generate()

  var db = require('./db')(join(opts.path || path, 'flume'), keys, opts)

  // UGLY HACK, but...
  // fairly sure that something up the stack expects ssb to be an event emitter.
  db.__proto__ = new EventEmitter() // eslint-disable-line

  db.opts = opts

  var _get = db.get
  var _del = db.del

  const deleteFeed = (feed, cb) => {
    pull(
      db.createUserStream({ id: feed }),
      pull.asyncMap((msg, cb) => {
        const key = msg.key

        deleteMessage(key, (err) => {
          cb(err, key)
        })
      }),
      pull.collect(cb)
    )
  }

  const deleteMessage = (key, cb) => {
    db.keys.get(key, (err, val, seq) => {
      if (err) return cb(err)
      if (seq == null) cb(new Error('seq is null!'))

      _del(seq, cb)
    })
  }

  db.del = (target, cb) => {
    if (ref.isMsg(target)) {
      deleteMessage(target, cb)
    } else if (ref.isFeed(target)) {
      deleteFeed(target, cb)
    } else {
      cb(new Error('deletion target must be a message or feed'))
    }
  }

  db.get = function (key, cb) {
    let isPrivate = false
    let unbox
    let meta = false
    if (typeof key === 'object') {
      isPrivate = key.private === true
      unbox = key.unbox
      meta = key.meta
      key = key.id
    }

    if (ref.isMsg(key)) {
      return db.keys.get(key, function (err, data) {
        if (err) return cb(err)

        if (isPrivate && unbox) {
          data = db.unbox(data, unbox)
        }

        let result

        if (isPrivate) {
          result = data.value
        } else {
          result = u.originalValue(data.value)
        }

        cb(null, !meta ? result : {key: data.key, value: result, timestamp: data.timestamp})
      })
    } else if (ref.isMsgLink(key)) {
      var link = ref.parseLink(key)
      return db.get({
        id: link.link,
        private: true,
        unbox: link.query.unbox.replace(/\s/g, '+'),
        meta: link.query.meta
      }, cb)
    } else if (Number.isInteger(key)) {
      _get(key, cb) // seq
    } else {
      throw new Error('ssb-db.get: key *must* be a ssb message id or a flume offset')
    }
  }

  db.add = function (msg, cb) {
    db.queue(msg, function (err, data) {
      if (err) cb(err)
      else db.flush(function () { cb(null, data) })
    })
  }

  db.createFeed = function (keys) {
    if (!keys) keys = ssbKeys.generate()
    function add (content, cb) {
      // LEGACY: hacks to support add as a continuable
      if (!cb) { return function (cb) { add(content, cb) } }

      db.append({ content: content, keys: keys }, cb)
    }
    return {
      add: add,
      publish: add,
      id: keys.id,
      keys: keys
    }
  }

  db.createRawLogStream = function (opts) {
    return db.stream(opts)
  }

  // pull in the features that are needed to pass the tests
  // and that sbot, etc uses but are slow.
  require('./extras')(db, opts, keys)

  // writeStream - used in (legacy) replication.
  db.createWriteStream = function (cb) {
    cb = cb || errorCB
    return pull(
      pull.asyncMap(function (data, cb) {
        db.queue(data, function (err, msg) {
          if (err) {
            db.emit('invalid', err, msg)
          }
          setImmediate(cb)
        })
      }),
      pull.drain(null, function (err) {
        if (err) return cb(err)
        db.flush(cb)
      })
    )
  }

  // should be private
  db.createHistoryStream = db.clock.createHistoryStream

  // called with [id, seq] or "<id>:<seq>"
  db.getAtSequence = function (seqid, cb) {
    // will NOT expose private plaintext
    db.clock.get(isString(seqid) ? seqid.split(':') : seqid, function (err, value) {
      if (err) cb(err)
      else cb(null, u.originalData(value))
    })
  }

  db.getVectorClock = function (_, cb) {
    if (!cb) cb = _
    db.last.get(function (err, h) {
      if (err) return cb(err)
      var clock = {}
      for (var k in h) { clock[k] = h[k].sequence }
      cb(null, clock)
    })
  }

  return db
}

<commit_msg>Fix to add return when using callback<commit_after>'use strict'

var join = require('path').join
var EventEmitter = require('events')

var pull = require('pull-stream')
var ref = require('ssb-ref')
var ssbKeys = require('ssb-keys')

var u = require('./util')

function isString (s) {
  return typeof s === 'string'
}

function errorCB (err) {
  if (err) throw err
}

module.exports = function (path, opts, keys) {
  //_ was legacy db. removed that, but for backwards compatibilty reasons do not change interface
  if(!path) throw new Error('path must be provided')

  keys = keys || ssbKeys.generate()

  var db = require('./db')(join(opts.path || path, 'flume'), keys, opts)

  // UGLY HACK, but...
  // fairly sure that something up the stack expects ssb to be an event emitter.
  db.__proto__ = new EventEmitter() // eslint-disable-line

  db.opts = opts

  var _get = db.get
  var _del = db.del

  const deleteFeed = (feed, cb) => {
    pull(
      db.createUserStream({ id: feed }),
      pull.asyncMap((msg, cb) => {
        const key = msg.key

        deleteMessage(key, (err) => {
          cb(err, key)
        })
      }),
      pull.collect(cb)
    )
  }

  const deleteMessage = (key, cb) => {
    db.keys.get(key, (err, val, seq) => {
      if (err) return cb(err)
      if (seq == null) return cb(new Error('seq is null!'))

      _del(seq, cb)
    })
  }

  db.del = (target, cb) => {
    if (ref.isMsg(target)) {
      deleteMessage(target, cb)
    } else if (ref.isFeed(target)) {
      deleteFeed(target, cb)
    } else {
      cb(new Error('deletion target must be a message or feed'))
    }
  }

  db.get = function (key, cb) {
    let isPrivate = false
    let unbox
    let meta = false
    if (typeof key === 'object') {
      isPrivate = key.private === true
      unbox = key.unbox
      meta = key.meta
      key = key.id
    }

    if (ref.isMsg(key)) {
      return db.keys.get(key, function (err, data) {
        if (err) return cb(err)

        if (isPrivate && unbox) {
          data = db.unbox(data, unbox)
        }

        let result

        if (isPrivate) {
          result = data.value
        } else {
          result = u.originalValue(data.value)
        }

        cb(null, !meta ? result : {key: data.key, value: result, timestamp: data.timestamp})
      })
    } else if (ref.isMsgLink(key)) {
      var link = ref.parseLink(key)
      return db.get({
        id: link.link,
        private: true,
        unbox: link.query.unbox.replace(/\s/g, '+'),
        meta: link.query.meta
      }, cb)
    } else if (Number.isInteger(key)) {
      _get(key, cb) // seq
    } else {
      throw new Error('ssb-db.get: key *must* be a ssb message id or a flume offset')
    }
  }

  db.add = function (msg, cb) {
    db.queue(msg, function (err, data) {
      if (err) cb(err)
      else db.flush(function () { cb(null, data) })
    })
  }

  db.createFeed = function (keys) {
    if (!keys) keys = ssbKeys.generate()
    function add (content, cb) {
      // LEGACY: hacks to support add as a continuable
      if (!cb) { return function (cb) { add(content, cb) } }

      db.append({ content: content, keys: keys }, cb)
    }
    return {
      add: add,
      publish: add,
      id: keys.id,
      keys: keys
    }
  }

  db.createRawLogStream = function (opts) {
    return db.stream(opts)
  }

  // pull in the features that are needed to pass the tests
  // and that sbot, etc uses but are slow.
  require('./extras')(db, opts, keys)

  // writeStream - used in (legacy) replication.
  db.createWriteStream = function (cb) {
    cb = cb || errorCB
    return pull(
      pull.asyncMap(function (data, cb) {
        db.queue(data, function (err, msg) {
          if (err) {
            db.emit('invalid', err, msg)
          }
          setImmediate(cb)
        })
      }),
      pull.drain(null, function (err) {
        if (err) return cb(err)
        db.flush(cb)
      })
    )
  }

  // should be private
  db.createHistoryStream = db.clock.createHistoryStream

  // called with [id, seq] or "<id>:<seq>"
  db.getAtSequence = function (seqid, cb) {
    // will NOT expose private plaintext
    db.clock.get(isString(seqid) ? seqid.split(':') : seqid, function (err, value) {
      if (err) cb(err)
      else cb(null, u.originalData(value))
    })
  }

  db.getVectorClock = function (_, cb) {
    if (!cb) cb = _
    db.last.get(function (err, h) {
      if (err) return cb(err)
      var clock = {}
      for (var k in h) { clock[k] = h[k].sequence }
      cb(null, clock)
    })
  }

  return db
}

<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');

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

gulp.task('default', ['compress']);
<commit_msg>added watch task to gulpfile<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');

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

gulp.task('watch', function() {
    gulp.watch('./src/*.js', ['compress']);
});

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