<commit_before>var EXPRESS_PORT = 4000;
var EXPRESS_ROOT = __dirname + '/app';
var EXPRESS_DOCS_ROOT = __dirname + '/angus-site/_site';
var LIVERELOAD_PORT = 35729;

// Load plugins
var gulp = require('gulp'),
  sass = require('gulp-ruby-sass'),
  autoprefixer = require('gulp-autoprefixer'),
  minifycss = require('gulp-minify-css'),
  jshint = require('gulp-jshint'),
  uglify = require('gulp-uglify'),
  imagemin = require('gulp-imagemin'),
  rename = require('gulp-rename'),
  clean = require('gulp-clean'),
  concat = require('gulp-concat'),
  notify = require('gulp-notify'),
  cache = require('gulp-cache'),
  livereload = require('gulp-livereload'),
  lr = require('tiny-lr'),
  server = lr(),
  gutil = require('gulp-util'),
  pkg = require('./package.json'),
  exec = require('gulp-exec');

// Set up server
function startExpress(root) {
  var express = require('express');
  var app = express();
  app.use(require('connect-livereload')());
  app.use(express.static(root));
  app.listen(EXPRESS_PORT);
}

// Scripts
gulp.task('scripts', function() {
  return gulp.src([
    'app/scripts/services/famous.js',
    'app/scripts/services/famousDecorator.js',
    'app/scripts/directives/**/*.js'
  ])
  .pipe(jshint('.jshintrc'))
  .pipe(jshint.reporter('default'))
  .pipe(concat('famous.angular.js'))
  .pipe(gulp.dest('app/scripts'))
  .pipe(livereload(server))
  .pipe(notify({ message: 'Scripts task complete' }));
});

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

// Watch
gulp.task('watch', function(event) {
  server.listen(LIVERELOAD_PORT, function (err) {
	  if (err) {
	    return console.log(err)
	  };

	  // Watch .js files
	  gulp.watch([
	      'app/scripts/*/**/*.js',
	      'app/scripts/app.js',
	      '!app/scripts/famous.angular.js',
	      'app/index.html',
	      'app/views/**/*.html'
	    ],
	    ['build']
	  ).on('change',
	    function(file){
	      server.changed(file.path);
	    }
	  );
  });
});

// Build for dist
gulp.task('build', ['clean', 'scripts'], function(event) {
	return gulp.src('app/scripts/famous.angular.js')
	.pipe(gulp.dest('dist/scripts'))
	.pipe(uglify())
	.pipe(rename({suffix: '.min'}))
	.pipe(gulp.dest('dist/scripts'))
	.pipe(notify({ message: 'Build task complete' }));
})

gulp.task('docs', ['scripts'], function(done) {
	var dgeni = require('dgeni'),
		semver = require('semver'),
		argv = require('minimist')(process.argv.slice(2)),
		docVersion = argv['doc-version'];

	if (docVersion != 'unstable' && !semver.valid(docVersion)) {
		console.log('Usage: gulp docs --doc-version=(unstable|versionName)');
		if(pkg.version) {
			console.log('Current package.json version is: '+pkg.version);
		}
		console.log('No version selected, using unstable');
		docVersion = 'unstable';
	}
	process.env.DOC_VERSION = docVersion;

	gutil.log('Generating documentation for ', gutil.colors.cyan(docVersion));
	var generateDocs = dgeni.generator('docs-generation/docs.config.js');
	return generateDocs().then(function() {
		gutil.log('Docs for', gutil.colors.cyan(docVersion), 'generated!');
	});
});

gulp.task('build-site', ['docs'], function(done) {
	return gulp.src('./angus-site/scss/*.scss')
		.pipe(sass())
		.pipe(gulp.dest('./angus-site/css'))
		.pipe(exec("jekyll build --source ./angus-site/ --destination ./angus-site/_site/"))
		.pipe(notify({ message: 'Jekyll build task complete' }));
});

gulp.task('site', function(done) {
	startExpress(EXPRESS_DOCS_ROOT);
	gutil.log('Server running at Docs for', gutil.colors.cyan('http://localhost:'+EXPRESS_PORT+'/'));
});

// Default task
gulp.task('default', ['scripts'], function() {
  startExpress(EXPRESS_ROOT);
  gulp.start('watch');
});<commit_msg>Add watch task for when developing in angus-site submodule.<commit_after>var EXPRESS_PORT = 4000;
var EXPRESS_ROOT = __dirname + '/app';
var EXPRESS_DOCS_ROOT = __dirname + '/angus-site/_site';
var LIVERELOAD_PORT = 35729;

// Load plugins
var gulp = require('gulp'),
  sass = require('gulp-ruby-sass'),
  autoprefixer = require('gulp-autoprefixer'),
  minifycss = require('gulp-minify-css'),
  jshint = require('gulp-jshint'),
  uglify = require('gulp-uglify'),
  imagemin = require('gulp-imagemin'),
  rename = require('gulp-rename'),
  clean = require('gulp-clean'),
  concat = require('gulp-concat'),
  notify = require('gulp-notify'),
  cache = require('gulp-cache'),
  livereload = require('gulp-livereload'),
  lr = require('tiny-lr'),
  server = lr(),
  gutil = require('gulp-util'),
  pkg = require('./package.json'),
  exec = require('gulp-exec');

// Set up server
function startExpress(root) {
  var express = require('express');
  var app = express();
  app.use(require('connect-livereload')());
  app.use(express.static(root));
  app.listen(EXPRESS_PORT);
}

// Scripts
gulp.task('scripts', function() {
  return gulp.src([
    'app/scripts/services/famous.js',
    'app/scripts/services/famousDecorator.js',
    'app/scripts/directives/**/*.js'
  ])
  .pipe(jshint('.jshintrc'))
  .pipe(jshint.reporter('default'))
  .pipe(concat('famous.angular.js'))
  .pipe(gulp.dest('app/scripts'))
  .pipe(livereload(server))
  .pipe(notify({ message: 'Scripts task complete' }));
});

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

// Watch
gulp.task('watch', function(event) {
  server.listen(LIVERELOAD_PORT, function (err) {
	  if (err) {
	    return console.log(err)
	  };

	  // Watch .js files
	  gulp.watch([
	      'app/scripts/*/**/*.js',
	      'app/scripts/app.js',
	      '!app/scripts/famous.angular.js',
	      'app/index.html',
	      'app/views/**/*.html'
	    ],
	    ['build']
	  ).on('change',
	    function(file){
	      server.changed(file.path);
	    }
	  );
  });
});

// Build for dist
gulp.task('build', ['clean', 'scripts'], function(event) {
	return gulp.src('app/scripts/famous.angular.js')
	.pipe(gulp.dest('dist/scripts'))
	.pipe(uglify())
	.pipe(rename({suffix: '.min'}))
	.pipe(gulp.dest('dist/scripts'))
	.pipe(notify({ message: 'Build task complete' }));
})

gulp.task('docs', ['scripts'], function(done) {
	var dgeni = require('dgeni'),
		semver = require('semver'),
		argv = require('minimist')(process.argv.slice(2)),
		docVersion = argv['doc-version'];

	if (docVersion != 'unstable' && !semver.valid(docVersion)) {
		console.log('Usage: gulp docs --doc-version=(unstable|versionName)');
		if(pkg.version) {
			console.log('Current package.json version is: '+pkg.version);
		}
		console.log('No version selected, using unstable');
		docVersion = 'unstable';
	}
	process.env.DOC_VERSION = docVersion;

	gutil.log('Generating documentation for ', gutil.colors.cyan(docVersion));
	var generateDocs = dgeni.generator('docs-generation/docs.config.js');
	return generateDocs().then(function() {
		gutil.log('Docs for', gutil.colors.cyan(docVersion), 'generated!');
	});
});

gulp.task('build-site', ['docs'], function(done) {
	return gulp.src('./angus-site/scss/*.scss')
		.pipe(sass())
		.pipe(gulp.dest('./angus-site/css'))
		.pipe(exec("jekyll build --source ./angus-site/ --destination ./angus-site/_site/"))
		.pipe(notify({ message: 'Jekyll build task complete' }));
});

// Only jekyll-build, without compiling docs, for faster run-time and to
// prevent infinite loop when watching over files
gulp.task('build-jekyll', function(done) {
	return gulp.src('./angus-site/scss/*.scss')
		.pipe(sass())
		.pipe(gulp.dest('./angus-site/css'))
		.pipe(exec("jekyll build --source ./angus-site/ --destination ./angus-site/_site/"))
    // Live reloading not working for some reason
    .pipe(livereload(server));
});

/***********************************************************************
* Watch task for developing the angular-site submodule
***********************************************************************/
gulp.task('dev-site', ['build-jekyll'], function() {
  server.listen(LIVERELOAD_PORT, function (err) {
	  if (err) {
	    return console.log(err);
	  }

	  // Watch .css and .html files inside angus-site submodule
	  gulp.watch([
        // This might go over the watch limit
	      'angus-site/**/*.css',
	      'angus-site/**/*.html',
        // Do NOT watch the compile _site directory, else the watch will create
        // an infinite loop
        '!angus-site/_site'
	    ],
	    ['build-jekyll']
	  );
  });

  gulp.start('site');
});

gulp.task('site', function(done) {
	startExpress(EXPRESS_DOCS_ROOT);
	gutil.log('Server running at Docs for', gutil.colors.cyan('http://localhost:'+EXPRESS_PORT+'/'));
});

// Default task
gulp.task('default', ['scripts'], function() {
  startExpress(EXPRESS_ROOT);
  gulp.start('watch');
});
<|endoftext|>


<commit_before>var gulp = require("gulp");
var eslint = require("gulp-eslint");
var rollup = require("gulp-rollup");
var rename = require("gulp-rename");
var babel = require("gulp-babel");
var uglify = require("gulp-uglify");

var destFolder = "./dist";

gulp.task("default", function () {
    process.env.NODE_ENV = "release";
    return gulp.src("./src/**/*.js")
        // ----------- linting --------------
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError()) // --> failing if errors
        // ----------- rolling up --------------
        .pipe(rollup({
            format: "umd",
            moduleName: "LazyLoad",
            entry: "./src/lazyload.js"
        }))
        .pipe(rename("lazyload.es2015.js"))
        .pipe(gulp.dest(destFolder)) // --> writing rolledup
        // ----------- babelizing --------------
        .pipe(babel())
        .pipe(rename("lazyload.js"))
        .pipe(gulp.dest(destFolder)) // --> writing babelized ES5
        // ----------- minifying --------------
        .pipe(uglify())
        .pipe(rename("lazyload.min.js"))
        .pipe(gulp.dest(destFolder)); // --> writing uglified
});

gulp.task("watch", function () {
    gulp.watch("./src/**/*.js", ["default"]);
    // Other watchers
});<commit_msg>Updated rollup options<commit_after>var gulp = require("gulp");
var eslint = require("gulp-eslint");
var rollup = require("gulp-rollup");
var rename = require("gulp-rename");
var babel = require("gulp-babel");
var uglify = require("gulp-uglify");

var destFolder = "./dist";

gulp.task("default", function () {
    process.env.NODE_ENV = "release";
    return gulp.src("./src/**/*.js")
        // ----------- linting --------------
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError()) // --> failing if errors
        // ----------- rolling up --------------
        .pipe(rollup({
            input: "./src/lazyload.js",
            output: { name: "LazyLoad", format: "umd" }
        }))
        .pipe(rename("lazyload.es2015.js"))
        .pipe(gulp.dest(destFolder)) // --> writing rolledup
        // ----------- babelizing --------------
        .pipe(babel())
        .pipe(rename("lazyload.js"))
        .pipe(gulp.dest(destFolder)) // --> writing babelized ES5
        // ----------- minifying --------------
        .pipe(uglify())
        .pipe(rename("lazyload.min.js"))
        .pipe(gulp.dest(destFolder)); // --> writing uglified
});

gulp.task("watch", function () {
    gulp.watch("./src/**/*.js", ["default"]);
    // Other watchers
});<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var spawn = require('child_process').spawn;
var Q = require('q');
var release = require('.').release

gulp.task('release', function() {
    return release(
        {
            releaseCallback: function(answers) {
                var deferred = Q.defer();
                spawn('node',
                    ['node_modules/npm/bin/npm-cli.js', 'publish', '.', '--tag', answers.tag, '--access', 'public'],
                    {
                        stdio: 'inherit'
                    })
                    .on('close', function(err) {
                        if (err) {
                            deferred.reject(err);
                        }
                        deferred.resolve();
                    });
                return deferred.promise;
            }
        });
});
<commit_msg>try again to use spawn npm-cli<commit_after>'use strict';

var gulp = require('gulp');
var spawn = require('child_process').spawn;
var Q = require('q');
var release = require('.').release

gulp.task('release', function() {
    return release(
        {
            releaseCallback: function(answers) {
                var deferred = Q.defer();
                spawn('node',
                    ['node_modules/npm/bin/npm-cli.js', 'publish', '.', '--access', 'public'],
                    {
                        stdio: 'inherit'
                    })
                    .on('close', function(err) {
                        if (err) {
                            deferred.reject(err);
                        }
                        deferred.resolve();
                    });
                return deferred.promise;
            }
        });
});
<|endoftext|>


<commit_before>/////
// Mostly stolen from https://github.com/pkozlowski-opensource/ng2-play
/////

var gulp = require('gulp');
var karma = require('karma').server;
var buildConfig = require('./scripts/build/config');

var concat = require('gulp-concat');
var debug = require('gulp-debug');
var del = require('del');
var exec = require('gulp-exec');
var karma = require('karma').server;
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var shell = require('gulp-shell');
var traceur = require('gulp-traceur');
var wrap = require("gulp-wrap");

gulp.task('default', ['js', 'html', 'sass', 'libs', 'playgroundJs', 'playgroundFiles', 'demo']);

gulp.task('watch', ['default'], function() {
  var http = require('http');
  var connect = require('connect');
  var serveStatic = require('serve-static');
  var port = 9000;

  gulp.watch(buildConfig.src.html, ['html']);
  gulp.watch(buildConfig.src.js, ['js']);
  gulp.watch(buildConfig.src.scss, ['sass']);
  gulp.watch(buildConfig.src.playgroundJs, ['playgroundJs']);
  gulp.watch(buildConfig.src.playgroundFiles, ['playgroundFiles']);

  var app = connect().use(serveStatic(__dirname + '/' + buildConfig.dist));  // serve everything that is static
  http.createServer(app).listen(port);
  console.log('Serving `dist` on http://localhost:' + port);
});

gulp.task('lint', shell.task([
  './node_modules/.bin/standard'
]));

gulp.task('karma', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma.conf.js' });
});
gulp.task('karma-watch', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma-watch.conf.js' });
});

gulp.task('sass-watch', ['sass'], function () {
  gulp.watch('src/**/*.scss', ['sass']);
});

gulp.task('sass', function(done) {
  gulp.src('src/components/app/ionic.scss')
    .pipe(sass({
      onError: function(err) {
        console.log(err);
      }
    }))
    .pipe(gulp.dest('dist/css'))
    .on('end', done);
});

gulp.task('clean', function(done) {
  del([buildConfig.dist], done);
});

gulp.task('playgroundFiles', function() {
  return gulp.src(buildConfig.src.playgroundFiles)
    .pipe(gulp.dest(buildConfig.dist));
});

gulp.task('playgroundJs', function() {
  return gulp.src(buildConfig.src.playgroundJs)
    .pipe(rename({extname: ''})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(plumber())
    .pipe(traceur({
        modules: 'instantiate',
        moduleName: true,
        annotations: true,
        types: true
    }))
    .pipe(rename({extname: '.js'})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(gulp.dest(buildConfig.dist));
});

function traceurCompile() {
  return lazypipe()
    ();
}
gulp.task('js', function () {
  return gulp.src(buildConfig.src.js)
    .pipe(rename(function(file) {
      // Forces the files to register themselves with 'ionic' prefix
      file.dirname = 'ionic/' + file.dirname;
    }))
    .pipe(rename({extname: ''})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(plumber())
    .pipe(traceur({
        modules: 'instantiate',
        moduleName: true,
        annotations: true,
        types: true
    }))
    .pipe(rename({extname: '.js'})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    // compiled js files in playground go to the playground root, everything else goes in /ionic
    .pipe(gulp.dest('dist'));
});

gulp.task('html', function () {
  // Don't do anything with html for now
  // return gulp.src(buildConfig.src.html)
  //   .pipe(gulp.dest(buildConfig.dist));
});

gulp.task('libs', ['angular2'], function () {
  return gulp.src(buildConfig.lib)
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('angular2', function () {
  //transpile & concat
  return gulp.src([
    'node_modules/angular2/es6/prod/*.es6',
    'node_modules/angular2/es6/prod/src/**/*.es6'
  ], {
    base: 'node_modules/angular2/es6/prod'
  })
    .pipe(rename(function(path){
        path.dirname = 'angular2/' + path.dirname; //this is not ideal... but not sure how to change angular's file structure
        path.extname = ''; //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    }))
    .pipe(traceur({ modules: 'instantiate', moduleName: true}))
    .pipe(concat('angular2.js'))
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('demo', function () {
  gulp.src(["./src/components/**/examples/**/index.html"])
    .pipe(debug({title: 'Generating Demo:'}))
    .pipe(wrap({ src: './scripts/examples/template/index.html'}))
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace("/examples/","/");
    }))
    .pipe(gulp.dest("./dist/examples"));
});
<commit_msg>feat(build): build demos on html change in components<commit_after>/////
// Mostly stolen from https://github.com/pkozlowski-opensource/ng2-play
/////

var gulp = require('gulp');
var karma = require('karma').server;
var buildConfig = require('./scripts/build/config');

var concat = require('gulp-concat');
var debug = require('gulp-debug');
var del = require('del');
var exec = require('gulp-exec');
var karma = require('karma').server;
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var shell = require('gulp-shell');
var traceur = require('gulp-traceur');
var wrap = require("gulp-wrap");

gulp.task('default', ['js', 'html', 'sass', 'libs', 'playgroundJs', 'playgroundFiles', 'demo']);

gulp.task('watch', ['default'], function() {
  var http = require('http');
  var connect = require('connect');
  var serveStatic = require('serve-static');
  var port = 9000;

  gulp.watch(buildConfig.src.html, ['html', 'demo']);
  gulp.watch(buildConfig.src.js, ['js']);
  gulp.watch(buildConfig.src.scss, ['sass']);
  gulp.watch(buildConfig.src.playgroundJs, ['playgroundJs']);
  gulp.watch(buildConfig.src.playgroundFiles, ['playgroundFiles']);

  var app = connect().use(serveStatic(__dirname + '/' + buildConfig.dist));  // serve everything that is static
  http.createServer(app).listen(port);
  console.log('Serving `dist` on http://localhost:' + port);
});

gulp.task('lint', shell.task([
  './node_modules/.bin/standard'
]));

gulp.task('karma', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma.conf.js' });
});
gulp.task('karma-watch', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma-watch.conf.js' });
});

gulp.task('sass-watch', ['sass'], function () {
  gulp.watch('src/**/*.scss', ['sass']);
});

gulp.task('sass', function(done) {
  gulp.src('src/components/app/ionic.scss')
    .pipe(sass({
      onError: function(err) {
        console.log(err);
      }
    }))
    .pipe(gulp.dest('dist/css'))
    .on('end', done);
});

gulp.task('clean', function(done) {
  del([buildConfig.dist], done);
});

gulp.task('playgroundFiles', function() {
  return gulp.src(buildConfig.src.playgroundFiles)
    .pipe(gulp.dest(buildConfig.dist));
});

gulp.task('playgroundJs', function() {
  return gulp.src(buildConfig.src.playgroundJs)
    .pipe(rename({extname: ''})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(plumber())
    .pipe(traceur({
        modules: 'instantiate',
        moduleName: true,
        annotations: true,
        types: true
    }))
    .pipe(rename({extname: '.js'})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(gulp.dest(buildConfig.dist));
});

function traceurCompile() {
  return lazypipe()
    ();
}
gulp.task('js', function () {
  return gulp.src(buildConfig.src.js)
    .pipe(rename(function(file) {
      // Forces the files to register themselves with 'ionic' prefix
      file.dirname = 'ionic/' + file.dirname;
    }))
    .pipe(rename({extname: ''})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    .pipe(plumber())
    .pipe(traceur({
        modules: 'instantiate',
        moduleName: true,
        annotations: true,
        types: true
    }))
    .pipe(rename({extname: '.js'})) //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    // compiled js files in playground go to the playground root, everything else goes in /ionic
    .pipe(gulp.dest('dist'));
});

gulp.task('html', function () {
  // Don't do anything with html for now
  // return gulp.src(buildConfig.src.html)
  //   .pipe(gulp.dest(buildConfig.dist));
});

gulp.task('libs', ['angular2'], function () {
  return gulp.src(buildConfig.lib)
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('angular2', function () {
  //transpile & concat
  return gulp.src([
    'node_modules/angular2/es6/prod/*.es6',
    'node_modules/angular2/es6/prod/src/**/*.es6'
  ], {
    base: 'node_modules/angular2/es6/prod'
  })
    .pipe(rename(function(path){
        path.dirname = 'angular2/' + path.dirname; //this is not ideal... but not sure how to change angular's file structure
        path.extname = ''; //hack, see: https://github.com/sindresorhus/gulp-traceur/issues/54
    }))
    .pipe(traceur({ modules: 'instantiate', moduleName: true}))
    .pipe(concat('angular2.js'))
    .pipe(gulp.dest('dist/lib'));
});

gulp.task('demo', function () {
  gulp.src(["./src/components/**/examples/**/index.html"])
    .pipe(debug({title: 'Generating Demo:'}))
    .pipe(wrap({ src: './scripts/examples/template/index.html'}))
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace("/examples/","/");
    }))
    .pipe(gulp.dest("./dist/examples"));
});
<|endoftext|>


<commit_before>'use strict';
/* ---------- */
/* variables */
var srcFile = 'html.sortable.src.js';
/* ---------- */
/* setup */
var gulp = require('gulp');
var log = require('gulp-util').log;
var rename = require('gulp-rename');
var del = require('del');
var bump = require('gulp-bump');
var semver = require('semver');
var shell = require('gulp-shell');
var minimist = require('minimist');
var prompt = require('gulp-prompt');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var umd = require('gulp-umd');
var strip = require('gulp-strip-code');
/* ---------- */
/* error handling */
var reportError = function(error) {
  if (error.message !== undefined) {
    log(error.message);
  } else {
    log(error);
  }
};
/* ---------- */
/* linting */
gulp.task('lint', function() {
  gulp.src([
    'src/' + srcFile,
    'src/html.sortable.angular.js'
  ])
    .pipe(jscs())
      .on('error', reportError)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    ;
});
/* ---------- */
/* convert to umd */
gulp.task('umd', function() {
  return gulp.src('src/' + srcFile)
    .pipe(strip({
      //jscs:disable
      start_comment: 'start-testing',
      end_comment: 'end-testing'
      //jscs:enable
    }))
    .pipe(umd({
      dependencies: function() {
        return [{
          name: '$',
          amd: 'jquery',
          cjs: 'jquery',
          global: 'jQuery'
        }];
      },
      exports: function() {
        return 'sortable';
      },
      namespace: function() {
        return 'sortable';
      }
    }))
    .pipe(rename('html.sortable.js'))
    .pipe(gulp.dest('src/'));
});
/* ---------- */
/* build */
gulp.task('build-version', ['umd'], function() {
  // clear dist
  del.sync('./dist/*', {force: true});
  // copy files to dist
  gulp.src(['src/html.sortable.js', 'src/html.sortable.angular.js'])
    .pipe(gulp.dest('./dist'))
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(jshint())
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist'))
    // remove umd
    .on('end', function() {
      del.sync('./src/html.sortable.js', {force: true});
    });

});
/* bump version */
gulp.task('bump-version', function() {
  var msg = 'Are you sure you want to bump the version to ';
  if (process.argv.slice(2) === 'publish') {
    msg = 'Are you sure you want to publish the version ';
  }

  var args = minimist(process.argv.slice(3));
  var v = args.v || args.version;
  if (v === undefined) {
    v = semver.inc(require('./package.json').version, 'patch');
  }

  return gulp.src(['./package.json', './bower.json'])
    .pipe(prompt.confirm(msg + v))
    .pipe(bump({version: v}))
    .pipe(shell([
      "git shortlog -ns master | awk '$1 >= 1 {print $0}' | cut -d' ' -f2- > AUTHORS",
      "git add AUTHORS ./package.json ./bower.json && git commit -m 'bump to version v"+v+"'"
    ]))
    .pipe(gulp.dest('./'));
});
/* tag version */
gulp.task('tag-version', ['bump-version'], function() {
  var args = minimist(process.argv.slice(3));
  var v = args.v || args.version;
  if (v === undefined) {
    delete require.cache[require.resolve('./package.json')];
    v = require('./package.json').version;
  }
  return gulp.src('')
    .pipe(shell([
      'git tag v' + v
    ]));
});
/* publish version */
gulp.task('publish-version', ['tag-version'], function() {
  return gulp.src('')
    .pipe(shell([
      'git push --tags'
    ])
  );
});
/* ---------- */
/* tasks */
gulp.task('test', ['lint']);
gulp.task('build', ['umd', 'build-version', 'test']);
gulp.task('publish', ['bump-version', 'tag-version', 'publish-version']);
<commit_msg>fix gulp publish<commit_after>'use strict';
/* ---------- */
/* variables */
var srcFile = 'html.sortable.src.js';
/* ---------- */
/* setup */
var gulp = require('gulp');
var log = require('gulp-util').log;
var rename = require('gulp-rename');
var del = require('del');
var bump = require('gulp-bump');
var semver = require('semver');
var shell = require('gulp-shell');
var minimist = require('minimist');
var prompt = require('gulp-prompt');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var umd = require('gulp-umd');
var strip = require('gulp-strip-code');
/* ---------- */
/* error handling */
var reportError = function(error) {
  if (error.message !== undefined) {
    log(error.message);
  } else {
    log(error);
  }
};
/* ---------- */
/* linting */
gulp.task('lint', function() {
  gulp.src([
    'src/' + srcFile,
    'src/html.sortable.angular.js'
  ])
    .pipe(jscs())
      .on('error', reportError)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'))
    ;
});
/* ---------- */
/* convert to umd */
gulp.task('umd', function() {
  return gulp.src('src/' + srcFile)
    .pipe(strip({
      //jscs:disable
      start_comment: 'start-testing',
      end_comment: 'end-testing'
      //jscs:enable
    }))
    .pipe(umd({
      dependencies: function() {
        return [{
          name: '$',
          amd: 'jquery',
          cjs: 'jquery',
          global: 'jQuery'
        }];
      },
      exports: function() {
        return 'sortable';
      },
      namespace: function() {
        return 'sortable';
      }
    }))
    .pipe(rename('html.sortable.js'))
    .pipe(gulp.dest('src/'));
});
/* ---------- */
/* build */
gulp.task('build-version', ['umd'], function() {
  // clear dist
  del.sync('./dist/*', {force: true});
  // copy files to dist
  gulp.src(['src/html.sortable.js', 'src/html.sortable.angular.js'])
    .pipe(gulp.dest('./dist'))
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(jshint())
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist'))
    // remove umd
    .on('end', function() {
      del.sync('./src/html.sortable.js', {force: true});
    });

});
/* bump version */
gulp.task('bump-version', function() {
  var msg = 'Are you sure you want to bump the version to ';
  if (process.argv.slice(2) === 'publish') {
    msg = 'Are you sure you want to publish the version ';
  }

  var args = minimist(process.argv.slice(3));
  var v = args.v || args.version;
  if (v === undefined) {
    v = semver.inc(require('./package.json').version, 'patch');
  }

  return gulp.src(['./package.json', './bower.json'])
    .pipe(prompt.confirm(msg + v))
    .pipe(bump({version: v}))
    .pipe(gulp.dest('./'));
});

gulp.task('add-files', ['bump-version'], function() {
  var v = require('./package.json').version;
  return gulp.src([])
    .pipe(shell([
      "git shortlog -ns master | awk '$1 >= 1 {print $0}' | cut -d' ' -f2- > AUTHORS",
      "git add AUTHORS ./package.json ./bower.json ./dist/* && git commit -m 'bump to version v"+v+"'"
    ]))
});
/* tag version */
gulp.task('tag-version', ['add-files'], function() {
  var args = minimist(process.argv.slice(3));
  var v = args.v || args.version;
  if (v === undefined) {
    delete require.cache[require.resolve('./package.json')];
    v = require('./package.json').version;
  }
  return gulp.src('')
    .pipe(shell([
      'git tag v' + v
    ]));
});
/* publish version */
gulp.task('publish-version', ['tag-version'], function() {
  return gulp.src('')
    .pipe(shell([
      'git push --tags'
    ])
  );
});
/* ---------- */
/* tasks */
gulp.task('test', ['lint']);
gulp.task('build', ['umd', 'build-version', 'test']);
gulp.task('publish', ['bump-version', 'add-files', 'tag-version', 'publish-version']);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var es = require('event-stream');
var webserver = require('gulp-webserver');
var debug = require('gulp-debug');
var minifyHTML = require('gulp-minify-html');
var templateCache = require('gulp-angular-templatecache');
var uglifycss = require('gulp-uglifycss');
var ngmin = require('gulp-ngmin');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var bower = require('gulp-bower');
var header = require('gulp-header');
var pkg = require('./package.json');
var fs = require('fs');
var clean = require('gulp-clean');
var rename = require('gulp-rename');

// Reference the module
var D2UConverter = new require('dos2unix').dos2unix;

// Setup default options
var defaultOptions = {
  glob: {
    cwd: __dirname
  },
  maxConcurrency: 50
};

var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
//  new Date(),
  ' * @link <%= pkg.homepage %>',
  ' * @license <%= pkg.license %>',
  ' * @license <%= pkg.author %>',
  ' */',
  ''].join('\n');

gulp.task('clean', function () {
    var cleanScript = gulp.src('./dist', { read: false }).pipe(clean());
    return es.concat.apply(null, [cleanScript]);
});

gulp.task('build',["clean"], function () {
    var scripts1 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist'));
    var scripts2 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist'));

    //var cdn1 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/lightservice/' + pkg.version));
    //var cdn2 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/lightservice/' + pkg.version));

    var cdn3 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));
    var cdn4 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));

    return es.concat.apply(null, [scripts1, scripts2,/* cdn2,cdn1,*/ cdn3, cdn4]);
});

gulp.task('post-build-visual-component', ["build"], function () {
    var scripts1 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.min.js']).pipe(concat("visual.lightservice.min.js")).pipe(gulp.dest('./dist'));
    var scripts2 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.js']).pipe(concat("visual.lightservice.js")).pipe(gulp.dest('./dist'));

    var cdn1 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.min.js']).pipe(concat("visual.lightservice.min.js")).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));
    var cdn2 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.js']).pipe(concat("visual.lightservice.js")).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));

    return es.concat.apply(null, [scripts1, cdn1, scripts2, cdn2]);
});

gulp.task('default', ['post-build-visual-component'], function () {
    gulp.src(['src/lightservice-timemachine.js', 'dist/lightservice-timemachine.min.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist-lightservice-timemachine/'));
	// Create a new `dos2unix` instance and add important event listeners
var d2u = new D2UConverter(defaultOptions)
  .on('error', function(err) {
    console.error(err);
  })
  .on('end', function(stats) {
    console.log(stats);
  });
	d2u.process(['cdn/package.json']);
});<commit_msg>cleanup gulp<commit_after>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var es = require('event-stream');
var webserver = require('gulp-webserver');
var debug = require('gulp-debug');
var minifyHTML = require('gulp-minify-html');
var templateCache = require('gulp-angular-templatecache');
var uglifycss = require('gulp-uglifycss');
var ngmin = require('gulp-ngmin');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var bower = require('gulp-bower');
var header = require('gulp-header');
var pkg = require('./package.json');
var fs = require('fs');
var clean = require('gulp-clean');
var rename = require('gulp-rename');

var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
//  new Date(),
  ' * @link <%= pkg.homepage %>',
  ' * @license <%= pkg.license %>',
  ' * @license <%= pkg.author %>',
  ' */',
  ''].join('\n');

gulp.task('clean', function () {
    var cleanScript = gulp.src('./dist', { read: false }).pipe(clean());
    return es.concat.apply(null, [cleanScript]);
});

gulp.task('build',["clean"], function () {
    var scripts1 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist'));
    var scripts2 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist'));

    //var cdn1 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/lightservice/' + pkg.version));
    //var cdn2 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/lightservice/' + pkg.version));

    var cdn3 = gulp.src(['./src/*.js']).pipe(uglify()).pipe(rename({ suffix: '.min' })).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));
    var cdn4 = gulp.src(['./src/*.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));

    return es.concat.apply(null, [scripts1, scripts2,/* cdn2,cdn1,*/ cdn3, cdn4]);
});

gulp.task('post-build-visual-component', ["build"], function () {
    var scripts1 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.min.js']).pipe(concat("visual.lightservice.min.js")).pipe(gulp.dest('./dist'));
    var scripts2 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.js']).pipe(concat("visual.lightservice.js")).pipe(gulp.dest('./dist'));

    var cdn1 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.min.js']).pipe(concat("visual.lightservice.min.js")).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));
    var cdn2 = gulp.src(['lib/js/cytoscape-dagre.js', 'lib/js/dagre.min.js', 'lib/js/cytoscape.min.js', './dist/visual.lightservice.js']).pipe(concat("visual.lightservice.js")).pipe(gulp.dest('./cdn/cdnjs/ajax/libs/lightservice/' + pkg.version));

    return es.concat.apply(null, [scripts1, cdn1, scripts2, cdn2]);
});

gulp.task('default', ['post-build-visual-component'], function () {
    gulp.src(['src/lightservice-timemachine.js', 'dist/lightservice-timemachine.min.js']).pipe(header(banner, { pkg: pkg })).pipe(gulp.dest('./dist-lightservice-timemachine/'));
});<|endoftext|>


<commit_before>angular.module('teamform-db', ['firebase'])
.factory('teamformDb', ['$firebaseObject', '$firebaseArray', TeamformDb]);

function TeamformDb($firebaseObject, $firebaseArray) {
	initalizeFirebase();
  var service = {
    loginWithFacebook: loginWithFacebook,
    saveNewFBUser: saveNewFBUser,
    getUser: getUser,
    getEvent: getEvent,
    getEventAdminData: getEventAdminData,
    getAllTeams: getAllTeams,
    getTeam: getTeam,
    setTeamData: setTeamData,
    getAllMembers: getAllMembers,
    getMember: getMember,
    setMemberData: setMemberData,
  };
  return service;

  function loginWithFacebook() {
    var provider = new firebase.auth.FacebookAuthProvider();
    return firebase.auth().signInWithPopup(provider);
  }

  function saveNewFBUser(
    fbID,
    name,
    email,
    profilePicUrl,
    token,
    refreshToken,
    callback) {
    var refPath = "user/" + fbID;
    var ref = firebase.database().ref(refPath);
    var data = {
        'fb_id': fbID,
        'fb_name': name,
        'display_name': name,
        'email': email,
        'profile_pic_url': profilePicUrl,
        'token': token,
        'refresh_token': refreshToken,
        'created_at': Date.now(),
    };
    ref.set(data, callback);
  }

  function getUser(userID) {
    var refPath =  'user/' + userID;
    ref = firebase.database().ref(refPath);
    var param = $firebaseObject(ref);
    return param;
  }

  function getEvent(eventName) {
  	var refPath = eventName + "/admin/param";
  	ref = firebase.database().ref(refPath);
  	var param = $firebaseObject(ref);
  	return param;
  }

  function getEventAdminData(eventName, callback) {
  	var refPath =  eventName + "/admin";
  	retrieveOnceFirebase(firebase, refPath, callback);
  }

  function getAllTeams(eventName) {
  	var refPath = eventName + '/team';
    return $firebaseArray(firebase.database().ref(refPath));
  };

  function getTeam(eventName, teamID, callback) {
		var refPath = eventName + "/team/" + teamID;
		retrieveOnceFirebase(firebase, refPath, callback);
  };

  function setTeamData(eventName, teamID, data, callback) {
    var refPath = eventName + "/team/" + teamID;
    var ref = firebase.database().ref(refPath);
    ref.set(data, callback);
  };

  function getAllMembers(eventName) {
  	var refPath = eventName + "/member";
    return $firebaseArray(firebase.database().ref(refPath));
  };

  function getMember(eventName, userID, callback) {
  	var refPath = eventName + "/member/" + userID;
    retrieveOnceFirebase(firebase, refPath, callback);
  }

  function setMemberData(eventName, userID, data, callback) {
  	var refPath = eventName + "/member/" + userID;
    var ref = firebase.database().ref(refPath);
    ref.set(data, callback);
  }
}<commit_msg>Add events db data into event scope<commit_after>angular.module('teamform-db', ['firebase'])
.factory('teamformDb', ['$firebaseObject', '$firebaseArray', TeamformDb]);

function TeamformDb($firebaseObject, $firebaseArray) {
	initalizeFirebase();

  var eventScope = 'events/';

  var service = {
    loginWithFacebook: loginWithFacebook,
    saveNewFBUser: saveNewFBUser,
    getUser: getUser,
    getEvent: getEvent,
    getEventAdminData: getEventAdminData,
    getAllTeams: getAllTeams,
    getTeam: getTeam,
    setTeamData: setTeamData,
    getAllMembers: getAllMembers,
    getMember: getMember,
    setMemberData: setMemberData,
  };
  return service;

  function loginWithFacebook() {
    var provider = new firebase.auth.FacebookAuthProvider();
    return firebase.auth().signInWithPopup(provider);
  }

  function saveNewFBUser(
    fbID,
    name,
    email,
    profilePicUrl,
    token,
    refreshToken,
    callback) {
    var refPath = "user/" + fbID;
    var ref = firebase.database().ref(refPath);
    var data = {
        'fb_id': fbID,
        'fb_name': name,
        'display_name': name,
        'email': email,
        'profile_pic_url': profilePicUrl,
        'token': token,
        'refresh_token': refreshToken,
        'created_at': Date.now(),
    };
    ref.set(data, callback);
  }

  function getUser(userID) {
    var refPath =  'user/' + userID;
    ref = firebase.database().ref(refPath);
    var param = $firebaseObject(ref);
    return param;
  }

  function getEvent(eventName) {
  	var refPath = eventScope + eventName + "/admin/param";
  	ref = firebase.database().ref(refPath);
  	var param = $firebaseObject(ref);
  	return param;
  }

  function getEventAdminData(eventName, callback) {
  	var refPath =  eventScope + eventName + "/admin";
  	retrieveOnceFirebase(firebase, refPath, callback);
  }

  function getAllTeams(eventName) {
  	var refPath = eventScope + eventName + '/team';
    return $firebaseArray(firebase.database().ref(refPath));
  };

  function getTeam(eventName, teamID, callback) {
		var refPath = eventScope + eventName + "/team/" + teamID;
		retrieveOnceFirebase(firebase, refPath, callback);
  };

  function setTeamData(eventName, teamID, data, callback) {
    var refPath = eventScope + eventName + "/team/" + teamID;
    var ref = firebase.database().ref(refPath);
    ref.set(data, callback);
  };

  function getAllMembers(eventName) {
  	var refPath = eventScope + eventName + "/member";
    return $firebaseArray(firebase.database().ref(refPath));
  };

  function getMember(eventName, userID, callback) {
  	var refPath = eventScope + eventName + "/member/" + userID;
    retrieveOnceFirebase(firebase, refPath, callback);
  }

  function setMemberData(eventName, userID, data, callback) {
  	var refPath = eventScope + eventName + "/member/" + userID;
    var ref = firebase.database().ref(refPath);
    ref.set(data, callback);
  }
}<|endoftext|>


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

var autoprefixer = require('gulp-autoprefixer');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sequence = require('run-sequence');
var rimraf = require('rimraf');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var webserver = require('gulp-webserver');

var paths = {
    assets: [
        './src/**/*.*',
        '!./src/{scss,js}/**/*.*'
    ],
    // Sass
    sass: [
        './src/scss/**/*.scss'
    ],
    // JavaScript dependencies
    libs: [
        './node_modules/babel-polyfill/dist/polyfill.js'
    ],
    // These files are for your app's JavaScript
    app: [
        './src/js/**/*.js'
    ]
};

// Default task: builds your app, starts a server, and recompiles assets when they change
gulp.task('default', ['server'], function () {
    // Watch Sass
    gulp.watch(['./src/scss/**/*', './scss/**/*'], ['sass']);

    // Watch JavaScript
    gulp.watch(paths.app, ['uglify:app']);

    // Watch static files
    gulp.watch(['./src/**/*.*', '!./src/templates/**/*.*', '!./src/{scss,js}/**/*.*'], ['copy']);

    // Watch app templates
    gulp.watch(['./src/templates/**/*.html'], ['copy:templates']);
});

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

// Copies everything in the client folder except templates, Sass, and JS
gulp.task('copy', function () {
    return gulp.src(paths.assets, {
        base: './src/'
    }).pipe(gulp.dest('./build'));
});

// Builds your entire app once, without starting a server
gulp.task('build', function (cb) {
    sequence('clean', ['copy', 'sass', 'uglify'], cb);
});

gulp.task('uglify', ['uglify:assets', 'uglify:app']);

gulp.task('uglify:assets', function () {
    return gulp.src(paths.libs)
        .pipe(uglify())
        .pipe(gulp.dest('./build/js/'));
});

gulp.task('uglify:app', function () {
    return gulp.src(paths.app)
        // .pipe(concat('app.js'))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('./build/js/'));
});

// Compiles Sass
gulp.task('sass', function () {
    return gulp.src(paths.sass)
        .pipe(sass())
        .pipe(autoprefixer({
            browsers: ['last 2 versions', 'ie 10']
        }))
        .pipe(gulp.dest('./build/css/'))
        ;
});

// Starts a test server, which you can view at http://localhost:3000
gulp.task('server', ['build'], function () {
    gulp.src('./build')
        .pipe(webserver({
            port: process.env.PORT || 5000,
            host: '0.0.0.0',
            fallback: 'index.html'
        }))
    ;
});
<commit_msg>Gulp configuration: HTTPS and Proxy settings<commit_after>var gulp = require('gulp');

var autoprefixer = require('gulp-autoprefixer');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sequence = require('run-sequence');
var rimraf = require('rimraf');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var webserver = require('gulp-webserver');

var paths = {
    assets: [
        './src/**/*.*',
        '!./src/{scss,js}/**/*.*'
    ],
    // Sass
    sass: [
        './src/scss/**/*.scss'
    ],
    // JavaScript dependencies
    libs: [
        './node_modules/babel-polyfill/dist/polyfill.js'
    ],
    // These files are for your app's JavaScript
    app: [
        './src/js/**/*.js'
    ]
};

// Default task: builds your app, starts a server, and recompiles assets when they change
gulp.task('default', ['server'], function () {
    // Watch Sass
    gulp.watch(['./src/scss/**/*', './scss/**/*'], ['sass']);

    // Watch JavaScript
    gulp.watch(paths.app, ['uglify:app']);

    // Watch static files
    gulp.watch(['./src/**/*.*', '!./src/templates/**/*.*', '!./src/{scss,js}/**/*.*'], ['copy']);

    // Watch app templates
    gulp.watch(['./src/templates/**/*.html'], ['copy:templates']);
});

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

// Copies everything in the client folder except templates, Sass, and JS
gulp.task('copy', function () {
    return gulp.src(paths.assets, {
        base: './src/'
    }).pipe(gulp.dest('./build'));
});

// Builds your entire app once, without starting a server
gulp.task('build', function (cb) {
    sequence('clean', ['copy', 'sass', 'uglify'], cb);
});

gulp.task('uglify', ['uglify:assets', 'uglify:app']);

gulp.task('uglify:assets', function () {
    return gulp.src(paths.libs)
        .pipe(uglify())
        .pipe(gulp.dest('./build/js/'));
});

gulp.task('uglify:app', function () {
    return gulp.src(paths.app)
    // .pipe(concat('app.js'))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('./build/js/'));
});

// Compiles Sass
gulp.task('sass', function () {
    return gulp.src(paths.sass)
        .pipe(sass())
        .pipe(autoprefixer({
            browsers: ['last 2 versions', 'ie 10']
        }))
        .pipe(gulp.dest('./build/css/'))
        ;
});

// Starts a test server, which you can view at http://localhost:3000
gulp.task('server', ['build'], function () {
    gulp.src('./build')
        .pipe(webserver({
            port: process.env.PORT || 5000,
            host: '0.0.0.0',
            fallback: 'index.html',
            https: true,
            proxies: [{
                source: '/api/',
                target: 'http://localhost:8080/'
            }]
        }))
    ;
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    mocha = require('gulp-mocha'),
    istanbul = require('gulp-istanbul'),
    exit = require('gulp-exit');

var TESTS = './test/*.js';
var SRC = './lib/**/*.js';
var MOCHA_OPTS = {
  timeout: 20000
};

gulp.task('clean', function() {
  var del = require('del');
  return del(['./coverage/']);
});

gulp.task('lint', function() {
  var eslint = require('gulp-eslint');

  var t = gulp.src([
    SRC,
    TESTS,
    'gulpfile.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
  return t;
});

gulp.task('test', ['lint'], function() {
  return gulp.src([TESTS])
    .pipe(mocha(MOCHA_OPTS))
    .pipe(exit());
});

gulp.task('doc', function() {
  var documentation = require('gulp-documentation');
  return gulp.src([SRC])
    .pipe(documentation({
      format: 'html',
      github: true
    }))
    .pipe(gulp.dest('doc'));
});

gulp.task('doc-deploy', ['doc'], function() {
  var ghPages = require('gulp-gh-pages');
  return gulp.src('./doc/**/*')
    .pipe(ghPages());
});

gulp.task('pre-coverage', ['clean'], function() {
  return gulp.src([SRC])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('coverage', ['pre-coverage'], function() {
  var t = gulp.src([TESTS])
  .pipe(mocha(MOCHA_OPTS).on('error', function(er) {
    gutil.log(er);
    t.end();
  }))
  .pipe(istanbul.writeReports({
    dir: './coverage'
  }))
  return t;
});

gulp.task('ci', ['coverage'], function() {
  var coveralls = require('gulp-coveralls');
  gulp.src('./coverage/**/lcov.info')
  .pipe(coveralls());
});

gulp.task('watch', ['coverage'], function() {
  return gulp.watch([SRC, TESTS], ['coverage']);
});

gulp.task('serve', ['watch'], function() {
  var gls = require('gulp-live-server');
  var open = require('open');
  var server = gls['static']('coverage/lcov-report');
  server.start();
  open('http://localhost:3000/');
  return gulp.watch(['coverage/lcov-report/**/*.html'], function(file) {
    return server.notify.apply(server, [file]);
  });
});

gulp.task('default', ['coverage']);
<commit_msg>Forgot to update gulpfile.js<commit_after>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    mocha = require('gulp-mocha'),
    istanbul = require('gulp-istanbul'),
    exit = require('gulp-exit');

var TESTS = './test/*.js';
var SRC = './lib/**/*.js';
var MOCHA_OPTS = {
  timeout: 20000
};

gulp.task('clean', function() {
  var del = require('del');
  return del(['./coverage/']);
});

gulp.task('lint', function() {
  var eslint = require('gulp-eslint');

  var t = gulp.src([
    SRC,
    TESTS,
    'gulpfile.js'
  ])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
  return t;
});

gulp.task('test', ['lint'], function() {
  return gulp.src([TESTS])
    .pipe(mocha(MOCHA_OPTS))
    .pipe(exit());
});

gulp.task('doc', function() {
  var documentation = require('gulp-documentation');
  return gulp.src([SRC])
    .pipe(documentation({
      format: 'html',
      github: true
    }))
    .pipe(gulp.dest('doc'));
});

gulp.task('doc-deploy', ['doc'], function() {
  var ghPages = require('gulp-gh-pages');
  return gulp.src('./doc/**/*')
    .pipe(ghPages());
});

gulp.task('pre-coverage', ['clean'], function() {
  return gulp.src([SRC])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('coverage', ['pre-coverage'], function() {
  var t = gulp.src([TESTS])
  .pipe(mocha(MOCHA_OPTS).on('error', function(er) {
    gutil.log(er);
    t.end();
  }))
  .pipe(istanbul.writeReports({
    dir: './coverage'
  }));
  return t;
});

gulp.task('ci', ['coverage'], function() {
  var coveralls = require('gulp-coveralls');
  gulp.src('./coverage/**/lcov.info')
  .pipe(coveralls());
});

gulp.task('watch', ['coverage'], function() {
  return gulp.watch([SRC, TESTS], ['coverage']);
});

gulp.task('serve', ['watch'], function() {
  var gls = require('gulp-live-server');
  var open = require('open');
  var server = gls['static']('coverage/lcov-report');
  server.start();
  open('http://localhost:3000/');
  return gulp.watch(['coverage/lcov-report/**/*.html'], function(file) {
    return server.notify.apply(server, [file]);
  });
});

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


<commit_before>"use strict";

var gulp = require("gulp"),
    gp_cached = require('gulp-cached'),
    gp_changed = require("gulp-changed"),
    gp_clean = require("gulp-clean"),
    gp_concat = require("gulp-concat"),
    gp_less = require("gulp-less"),
    gp_rename = require("gulp-rename"),
    gp_sourcemaps = require("gulp-sourcemaps"),
    gp_uglify = require("gulp-uglify"),
    gp_util = require("gulp-util");

var path = require("path");

var staticPrefix = "src/sentry/static/sentry",
    distPath = staticPrefix + "/dist";

var jsDistros = {
  "app": [
    file("scripts/core.js"),
    file("scripts/models.js"),
    file("scripts/templates.js"),
    file("scripts/utils.js"),
    file("scripts/collections.js"),
    file("scripts/charts.js"),
    file("scripts/views.js"),
    file("scripts/app.js")
  ],

  "app-legacy": [
    file("scripts/sentry.core.js"),
    file("scripts/sentry.charts.js"),
    file("scripts/sentry.stream.js"),
  ],

  "vendor-jquery": [
    vendorFile("jquery/dist/jquery.min.js"),
    file("scripts/lib/jquery.migrate.js"),

    vendorFile("jquery-flot/jquery.flot.js"),
    vendorFile("jquery-flot/jquery.flot.resize.js"),
    vendorFile("jquery-flot/jquery.flot.stack.js"),
    vendorFile("jquery-flot/jquery.flot.time.js"),
    file("scripts/lib/jquery.flot.dashes.js"),
    file("scripts/lib/jquery.flot.tooltip.js"),

    file("scripts/lib/jquery.animate-colors.js"),
    file("scripts/lib/jquery.clippy.min.js"),
    file("scripts/lib/jquery.cookie.js")
  ],

  "vendor-backbone": [
    file("scripts/lib/json2.js"),
    file("scripts/lib/underscore.js"),
    file("scripts/lib/backbone.js")
  ],

  "vendor-bootstrap": [
    vendorFile("bootstrap/js/bootstrap-transition.js"),
    vendorFile("bootstrap/js/bootstrap-alert.js"),
    vendorFile("bootstrap/js/bootstrap-button.js"),
    vendorFile("bootstrap/js/bootstrap-carousel.js"),
    vendorFile("bootstrap/js/bootstrap-collapse.js"),
    vendorFile("bootstrap/js/bootstrap-dropdown.js"),
    vendorFile("bootstrap/js/bootstrap-modal.js"),
    vendorFile("bootstrap/js/bootstrap-tooltip.js"),
    vendorFile("bootstrap/js/bootstrap-popover.js"),
    vendorFile("bootstrap/js/bootstrap-scrollspy.js"),
    vendorFile("bootstrap/js/bootstrap-tab.js"),
    vendorFile("bootstrap/js/bootstrap-typeahead.js"),
    vendorFile("bootstrap/js/bootstrap-affix.js"),
    file("scripts/lib/bootstrap-datepicker.js")
  ],

  "vendor-misc": [
    vendorFile("moment/min/moment.min.js"),
    vendorFile("simple-slider/js/simple-slider.min.js"),
    file("scripts/lib/select2/select2.js")
  ],

  "raven": [
    vendorFile("raven-js/dist/raven.min.js")
  ]
}

function file(name) {
  return path.join(__dirname, staticPrefix, name);
}

function vendorFile(name) {
  return path.join(__dirname, staticPrefix, "vendor", name);
}

function buildJsCompileTask(name, fileList) {
  // TODO(dcramer): sourcemaps do not have the correct path to the
  // originaly files
  return gulp.src(fileList)
    .pipe(gp_cached('js_' + name))
    .pipe(gp_sourcemaps.init())
    .pipe(gp_concat(distroName + ".js"))
    .pipe(gulp.dest(distPath))
    .pipe(gp_uglify())
    .pipe(gp_rename(distroName + ".min.js"))
    .pipe(gp_sourcemaps.write("./", {
      includeContent: false
    }))
    .pipe(gulp.dest(distPath))
    .on("error", gp_util.log);
}

function buildCssCompileTask(name, fileList) {
  return gulp.src(fileList)
    .pipe(gp_cached('css_' + name))
    .pipe(gp_sourcemaps.init())
    .pipe(gp_less({
        paths: [vendorFile("bootstrap/less")]
    }))
    .pipe(gp_concat(name))
    .pipe(gp_sourcemaps.write("./", {
      includeContent: false
    }))
    .pipe(gulp.dest(distPath))
    .on("error", gp_util.log);
}

gulp.task("clean", function () {
  return gulp.src(distPath, {read: false})
    .pipe(gp_clean());
});

gulp.task("dist:css", function () {
  return buildCssCompileTask("sentry.css", [file("less/sentry.less")]);
});

// create a gulp task for each JS distro
var jsDistroNames = [], jsTask;
for (var distroName in jsDistros) {
  jsTask = buildJsCompileTask(distroName, jsDistros[distroName]);
  gulp.task("dist:js:" + distroName, function(){
    jsTask;
  });
  jsDistroNames.push(distroName);
}

gulp.task("dist:js", jsDistroNames.map(function(n) { return "dist:js:" + n; }));

gulp.task("dist", ["dist:js", "dist:css"]);

gulp.task("watch:css", function(){
  gulp.watch(file("less/sentry.less"), ["dist:css"]);
});

gulp.task("watch:js:vendor-misc", function(){
  var files = [
    vendorFile("moment/min/moment.min.js"),
    vendorFile("simple-slider/js/simple-slider.min.js"),
    file("scripts/lib/select2/select2.js")
  ];

  gulp.watch(files, ["dist:js:vendor-misc"]);
});

gulp.task("watch:js", ["watch:js:vendor-misc"]);

gulp.task("watch", ["watch:js", "watch:css"]);

gulp.task("default", ["dist"]);

// // Lint JavaScript
// gulp.task("jshint", function () {
//   return gulp.src(staticPrefix + "/**/*.js")
//     .pipe(reload({stream: true, once: true}))
//     .pipe($.jshint())
//     .pipe($.jshint.reporter("jshint-stylish"))
//     .pipe($.if(!browserSync.active, $.jshint.reporter("fail")));
// });

// // Optimize Images
// gulp.task("images", function () {
//   return gulp.src(staticPrefix + "images/**/*")
//     .pipe($.cache($.imagemin({
//       progressive: true,
//       interlaced: true
//     })))
//     .pipe(gulp.dest("dist/images"))
//     .pipe($.size({title: "images"}));
// });

// // Build javascript distribution
//   {input} --source-map-root={relroot}/ --source-map-url={name}.map{ext} --source-map={relpath}/{name}.map{ext} -o {output}

//   var sourceMap = UglifyJS.SourceMap({
//     file : null, // the compressed file name
//     root : null, // the root URL to the original sources
//     orig : null, // the input source map
//   });

//   gulp.src("lib/*.js")
//     .pipe(uglify({
//       output: {
//         source_map: sourceMap
//       }
//     }))
//     .pipe(gulp.dest("dist"))
// });
<commit_msg>Add remaining watch tasks<commit_after>"use strict";

var gulp = require("gulp"),
    gp_cached = require('gulp-cached'),
    gp_changed = require("gulp-changed"),
    gp_clean = require("gulp-clean"),
    gp_concat = require("gulp-concat"),
    gp_less = require("gulp-less"),
    gp_rename = require("gulp-rename"),
    gp_sourcemaps = require("gulp-sourcemaps"),
    gp_uglify = require("gulp-uglify"),
    gp_util = require("gulp-util");

var path = require("path");

var staticPrefix = "src/sentry/static/sentry",
    distPath = staticPrefix + "/dist";

var jsDistros = {
  "app": [
    file("scripts/core.js"),
    file("scripts/models.js"),
    file("scripts/templates.js"),
    file("scripts/utils.js"),
    file("scripts/collections.js"),
    file("scripts/charts.js"),
    file("scripts/views.js"),
    file("scripts/app.js")
  ],

  "app-legacy": [
    file("scripts/sentry.core.js"),
    file("scripts/sentry.charts.js"),
    file("scripts/sentry.stream.js"),
  ],

  "vendor-jquery": [
    vendorFile("jquery/dist/jquery.min.js"),
    file("scripts/lib/jquery.migrate.js"),

    vendorFile("jquery-flot/jquery.flot.js"),
    vendorFile("jquery-flot/jquery.flot.resize.js"),
    vendorFile("jquery-flot/jquery.flot.stack.js"),
    vendorFile("jquery-flot/jquery.flot.time.js"),
    file("scripts/lib/jquery.flot.dashes.js"),
    file("scripts/lib/jquery.flot.tooltip.js"),

    file("scripts/lib/jquery.animate-colors.js"),
    file("scripts/lib/jquery.clippy.min.js"),
    file("scripts/lib/jquery.cookie.js")
  ],

  "vendor-backbone": [
    file("scripts/lib/json2.js"),
    file("scripts/lib/underscore.js"),
    file("scripts/lib/backbone.js")
  ],

  "vendor-bootstrap": [
    vendorFile("bootstrap/js/bootstrap-transition.js"),
    vendorFile("bootstrap/js/bootstrap-alert.js"),
    vendorFile("bootstrap/js/bootstrap-button.js"),
    vendorFile("bootstrap/js/bootstrap-carousel.js"),
    vendorFile("bootstrap/js/bootstrap-collapse.js"),
    vendorFile("bootstrap/js/bootstrap-dropdown.js"),
    vendorFile("bootstrap/js/bootstrap-modal.js"),
    vendorFile("bootstrap/js/bootstrap-tooltip.js"),
    vendorFile("bootstrap/js/bootstrap-popover.js"),
    vendorFile("bootstrap/js/bootstrap-scrollspy.js"),
    vendorFile("bootstrap/js/bootstrap-tab.js"),
    vendorFile("bootstrap/js/bootstrap-typeahead.js"),
    vendorFile("bootstrap/js/bootstrap-affix.js"),
    file("scripts/lib/bootstrap-datepicker.js")
  ],

  "vendor-misc": [
    vendorFile("moment/min/moment.min.js"),
    vendorFile("simple-slider/js/simple-slider.min.js"),
    file("scripts/lib/select2/select2.js")
  ],

  "raven": [
    vendorFile("raven-js/dist/raven.min.js")
  ]
}

function file(name) {
  return path.join(__dirname, staticPrefix, name);
}

function vendorFile(name) {
  return path.join(__dirname, staticPrefix, "vendor", name);
}

function buildJsCompileTask(name, fileList) {
  // TODO(dcramer): sourcemaps do not have the correct path to the
  // originaly files
  return gulp.src(fileList)
    .pipe(gp_cached('js_' + name))
    .pipe(gp_sourcemaps.init())
    .pipe(gp_concat(distroName + ".js"))
    .pipe(gulp.dest(distPath))
    .pipe(gp_uglify())
    .pipe(gp_rename(distroName + ".min.js"))
    .pipe(gp_sourcemaps.write("./", {
      includeContent: false
    }))
    .pipe(gulp.dest(distPath))
    .on("error", gp_util.log);
}

function buildJsWatchTask(name, fileList) {
  return gulp.watch(fileList, ["dist:js:" + name]);
};

function buildCssCompileTask(name, fileList) {
  return gulp.src(fileList)
    .pipe(gp_cached('css_' + name))
    .pipe(gp_sourcemaps.init())
    .pipe(gp_less({
        paths: [vendorFile("bootstrap/less")]
    }))
    .pipe(gp_concat(name))
    .pipe(gp_sourcemaps.write("./", {
      includeContent: false
    }))
    .pipe(gulp.dest(distPath))
    .on("error", gp_util.log);
}

gulp.task("clean", function () {
  return gulp.src(distPath, {read: false})
    .pipe(gp_clean());
});

gulp.task("dist:css", function () {
  return buildCssCompileTask("sentry.css", [file("less/sentry.less")]);
});

// create a gulp task for each JS distro
var jsDistroNames = [], jsTask;
for (var distroName in jsDistros) {
  jsTask = buildJsCompileTask(distroName, jsDistros[distroName]);
  gulp.task("dist:js:" + distroName, function(){
    jsTask;
  });

  jsTask = buildJsWatchTask(distroName, jsDistros[distroName]);
  gulp.task("watch:js:" + distroName, function(){
    jsTask;
  });

  jsDistroNames.push(distroName);
}

gulp.task("dist:js", jsDistroNames.map(function(n) { return "dist:js:" + n; }));

gulp.task("dist", ["dist:js", "dist:css"]);

gulp.task("watch:css", function(){
  gulp.watch(file("less/sentry.less"), ["dist:css"]);
});

gulp.task("watch:js", jsDistroNames.map(function(n) { return "watch:js:" + n; }));

gulp.task("watch", ["watch:js", "watch:css"]);

gulp.task("default", ["dist"]);

// // Lint JavaScript
// gulp.task("jshint", function () {
//   return gulp.src(staticPrefix + "/**/*.js")
//     .pipe(reload({stream: true, once: true}))
//     .pipe($.jshint())
//     .pipe($.jshint.reporter("jshint-stylish"))
//     .pipe($.if(!browserSync.active, $.jshint.reporter("fail")));
// });

// // Optimize Images
// gulp.task("images", function () {
//   return gulp.src(staticPrefix + "images/**/*")
//     .pipe($.cache($.imagemin({
//       progressive: true,
//       interlaced: true
//     })))
//     .pipe(gulp.dest("dist/images"))
//     .pipe($.size({title: "images"}));
// });

// // Build javascript distribution
//   {input} --source-map-root={relroot}/ --source-map-url={name}.map{ext} --source-map={relpath}/{name}.map{ext} -o {output}

//   var sourceMap = UglifyJS.SourceMap({
//     file : null, // the compressed file name
//     root : null, // the root URL to the original sources
//     orig : null, // the input source map
//   });

//   gulp.src("lib/*.js")
//     .pipe(uglify({
//       output: {
//         source_map: sourceMap
//       }
//     }))
//     .pipe(gulp.dest("dist"))
// });
<|endoftext|>


<commit_before>// QA specific gulpfile. Had problems with csscss so haven't put that in yet.

var gulp = require('gulp'),
    cleanhtml = require('gulp-cleanhtml'),
    csslint = require('gulp-csslint'),
    htmlhint = require('gulp-htmlhint'),
    jshint = require('gulp-jshint'),
    notify = require('gulp-notify'),
    plumber = require('gulp-plumber'),
    size = require('gulp-size'),
    uncss = require('gulp-uncss'),
    w3cjs = require('gulp-w3cjs'),
    gulputil = require('gulp-util');

var fs = require('fs'),
    mkdirp = require('mkdirp');

var reportsDir = './reports/json'

    //Individual Tasks

gulp.task('markymark', function() {
  gulp.src('build/*.html')
    .pipe(plumber())
    .pipe(htmlhint())
    .pipe(htmlhint.reporter())
    .pipe(notify("The Funky Bunch has hinted."));
});

gulp.task('wildstyle', function() {
  mkdirp(reportsDir);

  var jsonReporter = function (file) {
    if (file && file.csslint) {
      fs.writeFileSync(reportsDir + '/csshint-' + file.path.split('/').pop().split('.').shift() + '.json', JSON.stringify(file.csslint, null, 2));
    }
  };

  gulp.src('build/css/*.css')
    .pipe(plumber())
    .pipe(csslint())
    .pipe(csslint.reporter(jsonReporter))
    .pipe(notify("All right, all right, all right! CSS busted"));
});

gulp.task('validation', function() {
  gulp.src('build/*.html')
    .pipe(w3cjs())
    .pipe(notify("Validation Complete!"));
});

gulp.task('uncss', function() {
  gulp.src('build/css/*.css')
    .pipe(plumber())
    .pipe(uncss({
      html: ['build/index.html']
    }))
    .pipe(gulp.dest('build/linted/css'))
    pipe(notify('Removed unused styles'));
});

gulp.task('cleanhtml', function() {
  gulp.src('build/*.html')
    .pipe(plumber())
    .pipe(cleanhtml())
    .pipe(gulp.dest('build/linted'))
    .pipe(notify('Cleaned up html'));
});

gulp.task('size', function() {
  gulp.src('build')
    .pipe(size(showFiles));
});

gulp.task('jshint', function() {
  gulp.src('build/js/*.js')
    .pipe(jshint('build/js/.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(notify('JS has been hinted'));
});
<commit_msg>adds report for htmllint<commit_after>// QA specific gulpfile. Had problems with csscss so haven't put that in yet.

var gulp = require('gulp'),
    cleanhtml = require('gulp-cleanhtml'),
    csslint = require('gulp-csslint'),
    htmlhint = require('gulp-htmlhint'),
    jshint = require('gulp-jshint'),
    notify = require('gulp-notify'),
    plumber = require('gulp-plumber'),
    size = require('gulp-size'),
    uncss = require('gulp-uncss'),
    w3cjs = require('gulp-w3cjs'),
    gulputil = require('gulp-util');

var fs = require('fs'),
    mkdirp = require('mkdirp');

var reportsDir = './reports/json'

    //Individual Tasks

gulp.task('markymark', function() {
  var jsonReporter = function (file) {
    if (file && file.htmlhint) {
      fs.writeFileSync(reportsDir + '/htmlhint-' + file.path.split('/').pop().split('.').shift() + '.json', JSON.stringify(file.htmlhint, null, 2));
    }
  };

  gulp.src('build/*.html')
    .pipe(plumber())
    .pipe(htmlhint())
    .pipe(htmlhint.reporter(jsonReporter))
    .pipe(notify("The Funky Bunch has hinted."));
});

gulp.task('wildstyle', function() {
  mkdirp(reportsDir);

  var jsonReporter = function (file) {
    if (file && file.csslint) {
      fs.writeFileSync(reportsDir + '/csshint-' + file.path.split('/').pop().split('.').shift() + '.json', JSON.stringify(file.csslint, null, 2));
    }
  };

  gulp.src('build/css/*.css')
    .pipe(plumber())
    .pipe(csslint())
    .pipe(csslint.reporter(jsonReporter))
    .pipe(notify("All right, all right, all right! CSS busted"));
});

gulp.task('validation', function() {
  gulp.src('build/*.html')
    .pipe(w3cjs())
    .pipe(notify("Validation Complete!"));
});

gulp.task('uncss', function() {
  gulp.src('build/css/*.css')
    .pipe(plumber())
    .pipe(uncss({
      html: ['build/index.html']
    }))
    .pipe(gulp.dest('build/linted/css'))
    pipe(notify('Removed unused styles'));
});

gulp.task('cleanhtml', function() {
  gulp.src('build/*.html')
    .pipe(plumber())
    .pipe(cleanhtml())
    .pipe(gulp.dest('build/linted'))
    .pipe(notify('Cleaned up html'));
});

gulp.task('size', function() {
  gulp.src('build')
    .pipe(size(showFiles));
});

gulp.task('jshint', function() {
  gulp.src('build/js/*.js')
    .pipe(jshint('build/js/.jshintrc'))
    .pipe(jshint.reporter('default'))
    .pipe(notify('JS has been hinted'));
});
<|endoftext|>


<commit_before>var overrides = function () {

}

// this is a copy of jscad function
overrides.generateOutputFile = function () {
  this.clearOutputFile();
  if(!this.hasValidCurrentObject)
    return;
  var blob = this.currentObjectToBlob();

  var format = this.selectedFormat();

  var formatInfo = this.formatInfo (format);

  /*displayName: "STL",
extension: "stl",
mimetype: "application/sla",*/

  var params = {};
  try {params = this.getParamValues ()} catch (e) {};

  var suffix = '';
  if ('part' in params && params.part.match (/(\w+)/)) {
    suffix += '-' + params.part.match (/(\w+)/)[1].toLowerCase ();
  }

  if ('version' in params && params.version.match (/([\w\.\-_]+)/)) {
    suffix += '-v' + params.version.match (/([\w\.\-_]+)/)[1];
  }

  var path = require ('path');

  var fileName = atom.showSaveDialogSync ({
    defaultPath: path.join (path.dirname (this.filename), path.basename (this.filename, path.extname (this.filename)) + suffix + '.' + formatInfo.extension),
    filters: [
      {name: formatInfo.displayName, extensions: [formatInfo.extension]}
    ]
  });

  if (!fileName)
    return;

  var fileExt = path.extname (fileName).substr (1);

  console.log ("saving into", fileName, fileExt);

  var fs = require ('fs');

  var reader = new FileReader();
  reader.addEventListener("loadend", function() {
    // TODO: find a way to pass ArrayBuffer into node
    // TODO: show progress bar
    // var resultStr = String.fromCharCode.apply(null, new Uint8Array(reader.result));
    // var resultStr = String.fromCharCode.apply(null, reader.result);
    var resultStr = reader.result;
    var firstComma = resultStr.indexOf(',');
    var data = unescape(resultStr.substring(firstComma + 1));

    var buffer = new Buffer(data, 'base64');

    fs.writeFile (fileName, buffer);
  });
  reader.readAsDataURL (blob);
}

overrides.parseJsCadScriptSync = function parseJsCadScriptSync (script, mainParameters, options) {
    var workerscript = "";
    workerscript += "var _csg_includesdir=" + JSON.stringify(options.includesDir + '/')+"; ";
    workerscript += script;
    workerscript += OpenJsCad.makeAbsoluteUrl.toString().replace ('function', 'function _csg_makeAbsoluteURL')+";\n";
    workerscript += OpenJsCad.includeJscad.toString().replace ('function', 'function include')+'\n';

    return parseJsCadScriptSync.__old (workerscript, mainParameters, options);
}

overrides.parseJsCadScriptSync.static = true;

overrides.parseJsCadScriptASync = function parseJsCadScriptASync (script, mainParameters, options, callback) {
    var workerscript = "";
    workerscript += "var _csg_includesdir=" + JSON.stringify(options.includesDir + '/')+"; ";
    workerscript += script;
    workerscript += OpenJsCad.makeAbsoluteUrl.toString().replace ('function', 'function _csg_makeAbsoluteURL')+";\n";
    workerscript += OpenJsCad.includeJscad.toString().replace ('function', 'function include')+'\n';

    return parseJsCadScriptASync.__old (workerscript, mainParameters, options, callback);
}

overrides.parseJsCadScriptASync.static = true;

overrides.includeJscad = function (fn) {
// include the requested script via MemFs if possible
  if (typeof(gMemFs) == 'object') {
    for (var i = 0; i < gMemFs.length; i++) {
      if (gMemFs[i].name == fn) {
        eval(gMemFs[i].source);
        return;
      }
    }
  }
// include the requested script via importScripts
  var url = _csg_makeAbsoluteURL(fn, _csg_includesdir);
  if (fn.match(/^(https:|http:)/i)) {
    url = fn;
  }
  if (typeof importScripts !== "undefined") {
    console.log (url + '(' + _csg_includesdir + ', ' + fn + ')');
    if (url[0] === '/') {
      url = 'file://' + url;
    }
    importScripts(url);
  } else if (typeof evalFile !== 'undefined') {
    // this is pointless to have urls when processing imports in node
    evalFile (url);
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open('GET',url,false);
    xhr.onload = function() {
      var src = this.responseText;
      eval(src);
    };
    xhr.onerror = function(e) {
      console.log (e);
      throw e;
    };
    xhr.send();
  }
  return true;
};

overrides.includeJscad.static = true;

// parse the jscad script to get the parameter definitions
overrides.getParamDefinitions = function getParamDefinitions (script, options) {

  var params = [];

   if (typeof process !== "undefined" && process.versions && process.versions.node) {
    // for node we have vm module
    var vm = require ('vm');
    var sandbox = {
      _csg_includesdir: options.includesDir + '/',
      _csg_makeAbsoluteURL: OpenJsCad.makeAbsoluteUrl,
      // include: includeJscad,
      evalFile: function (path) {
        var fs = require ('fs');
        var c = fs.readFileSync (path);

        var vm = require ('vm');

        vm.runInContext (c, sandbox);
      },
      params: [],
      require: require,
      console: console
    };

    vm.createContext(sandbox);

    vm.runInContext (OpenJsCad.includeJscad.toString ().replace ('function', 'function include'), sandbox, {
    });

    // first try to execute the script itself
    // will throw exception in case of any error
    vm.runInContext (script, sandbox, {
      // filename <string> Specifies the filename used in stack traces produced by this script.
      lineOffset: 1, // <number> Specifies the line number offset that is displayed in stack traces produced by this script.
      columnOffset: 1, // <number> Specifies the column number offset that is displayed in stack traces produced by this script.
      // displayErrors <boolean> When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.
      // timeout <number> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.
    });

    vm.runInContext ("if(typeof(getParameterDefinitions) == 'function') {params = getParameterDefinitions();}", sandbox, {});

    params = sandbox.params;
  } else {
    return getParamDefinitions.__old (script, options);
  }

  if( (typeof(params) != "object") || (typeof(params.length) != "number") )
  {
    throw new Error("The getParameterDefinitions() function should return an array with the parameter definitions");
  }
  return params;
};

overrides.getParamDefinitions.static = true;

module.exports = overrides;
<commit_msg>propose to export files to the same dir with jscad<commit_after>var overrides = function () {

}

// this is a copy of jscad function
overrides.generateOutputFile = function () {
  this.clearOutputFile();
  if(!this.hasValidCurrentObject)
    return;
  var blob = this.currentObjectToBlob();

  var format = this.selectedFormat();

  var formatInfo = this.formatInfo (format);

  /*displayName: "STL",
extension: "stl",
mimetype: "application/sla",*/

  var params = {};
  try {params = this.getParamValues ()} catch (e) {};

  var suffix = '';
  if ('part' in params && params.part.match (/(\w+)/)) {
    suffix += '-' + params.part.match (/(\w+)/)[1].toLowerCase ();
  }

  if ('version' in params && params.version.match (/([\w\.\-_]+)/)) {
    suffix += '-v' + params.version.match (/([\w\.\-_]+)/)[1];
  }

  var path = require ('path');

  var fileName = atom.showSaveDialogSync ({
    defaultPath: path.join (this.dirname || path.dirname (this.filename), path.basename (this.filename, path.extname (this.filename)) + suffix + '.' + formatInfo.extension),
    filters: [
      {name: formatInfo.displayName, extensions: [formatInfo.extension]}
    ]
  });

  if (!fileName)
    return;

  var fileExt = path.extname (fileName).substr (1);

  console.log ("saving into", fileName, fileExt);

  var fs = require ('fs');

  var reader = new FileReader();
  reader.addEventListener("loadend", function() {
    // TODO: find a way to pass ArrayBuffer into node
    // TODO: show progress bar
    // var resultStr = String.fromCharCode.apply(null, new Uint8Array(reader.result));
    // var resultStr = String.fromCharCode.apply(null, reader.result);
    var resultStr = reader.result;
    var firstComma = resultStr.indexOf(',');
    var data = unescape(resultStr.substring(firstComma + 1));

    var buffer = new Buffer(data, 'base64');

    fs.writeFile (fileName, buffer);
  });
  reader.readAsDataURL (blob);
}

overrides.parseJsCadScriptSync = function parseJsCadScriptSync (script, mainParameters, options) {
    var workerscript = "";
    workerscript += "var _csg_includesdir=" + JSON.stringify(options.includesDir + '/')+"; ";
    workerscript += script;
    workerscript += OpenJsCad.makeAbsoluteUrl.toString().replace ('function', 'function _csg_makeAbsoluteURL')+";\n";
    workerscript += OpenJsCad.includeJscad.toString().replace ('function', 'function include')+'\n';

    return parseJsCadScriptSync.__old (workerscript, mainParameters, options);
}

overrides.parseJsCadScriptSync.static = true;

overrides.parseJsCadScriptASync = function parseJsCadScriptASync (script, mainParameters, options, callback) {
    var workerscript = "";
    workerscript += "var _csg_includesdir=" + JSON.stringify(options.includesDir + '/')+"; ";
    workerscript += script;
    workerscript += OpenJsCad.makeAbsoluteUrl.toString().replace ('function', 'function _csg_makeAbsoluteURL')+";\n";
    workerscript += OpenJsCad.includeJscad.toString().replace ('function', 'function include')+'\n';

    return parseJsCadScriptASync.__old (workerscript, mainParameters, options, callback);
}

overrides.parseJsCadScriptASync.static = true;

overrides.includeJscad = function (fn) {
// include the requested script via MemFs if possible
  if (typeof(gMemFs) == 'object') {
    for (var i = 0; i < gMemFs.length; i++) {
      if (gMemFs[i].name == fn) {
        eval(gMemFs[i].source);
        return;
      }
    }
  }
// include the requested script via importScripts
  var url = _csg_makeAbsoluteURL(fn, _csg_includesdir);
  if (fn.match(/^(https:|http:)/i)) {
    url = fn;
  }
  if (typeof importScripts !== "undefined") {
    console.log (url + '(' + _csg_includesdir + ', ' + fn + ')');
    if (url[0] === '/') {
      url = 'file://' + url;
    }
    importScripts(url);
  } else if (typeof evalFile !== 'undefined') {
    // this is pointless to have urls when processing imports in node
    evalFile (url);
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open('GET',url,false);
    xhr.onload = function() {
      var src = this.responseText;
      eval(src);
    };
    xhr.onerror = function(e) {
      console.log (e);
      throw e;
    };
    xhr.send();
  }
  return true;
};

overrides.includeJscad.static = true;

// parse the jscad script to get the parameter definitions
overrides.getParamDefinitions = function getParamDefinitions (script, options) {

  var params = [];

   if (typeof process !== "undefined" && process.versions && process.versions.node) {
    // for node we have vm module
    var vm = require ('vm');
    var sandbox = {
      _csg_includesdir: options.includesDir + '/',
      _csg_makeAbsoluteURL: OpenJsCad.makeAbsoluteUrl,
      // include: includeJscad,
      evalFile: function (path) {
        var fs = require ('fs');
        var c = fs.readFileSync (path);

        var vm = require ('vm');

        vm.runInContext (c, sandbox);
      },
      params: [],
      require: require,
      console: console
    };

    vm.createContext(sandbox);

    vm.runInContext (OpenJsCad.includeJscad.toString ().replace ('function', 'function include'), sandbox, {
    });

    // first try to execute the script itself
    // will throw exception in case of any error
    vm.runInContext (script, sandbox, {
      // filename <string> Specifies the filename used in stack traces produced by this script.
      lineOffset: 1, // <number> Specifies the line number offset that is displayed in stack traces produced by this script.
      columnOffset: 1, // <number> Specifies the column number offset that is displayed in stack traces produced by this script.
      // displayErrors <boolean> When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.
      // timeout <number> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.
    });

    vm.runInContext ("if(typeof(getParameterDefinitions) == 'function') {params = getParameterDefinitions();}", sandbox, {});

    params = sandbox.params;
  } else {
    return getParamDefinitions.__old (script, options);
  }

  if( (typeof(params) != "object") || (typeof(params.length) != "number") )
  {
    throw new Error("The getParameterDefinitions() function should return an array with the parameter definitions");
  }
  return params;
};

overrides.getParamDefinitions.static = true;

module.exports = overrides;
<|endoftext|>


<commit_before>'use strict'

require('localenvironment')
const gulp = require('gulp')
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const cp = require('child_process')
const header = require('gulp-header')
const footer = require('gulp-footer')
const sourcemaps = require('gulp-sourcemaps')
const ShortBus = require('shortbus')
const del = require('del')
const MustHave = require('musthave')
const mh = new MustHave({
  throwOnError: false
})
const GithubPublisher = require('publish-release')
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
let headerComment = '/**\n  * v' + pkg.version + ' generated on: '
  + (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear()
  + ', Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD).\n  */\n'

var DIR = {
  source: path.resolve('./src'),
  dist: path.resolve('./dist')
}

// Build a release
gulp.task('build', ['clean', 'generate'])

// Check versions for Bower & npm
// gulp.task('version', function (next) {
//   console.log('Checking versions.')
//
//   // Sync Bower
//   var bower = require('./bower.json')
//   if (bower.version !== pkg.version) {
//     console.log('Updating bower package.')
//     bower.version = pkg.version
//     fs.writeFileSync(path.resolve('./bower.json'), JSON.stringify(bower, null, 2))
//   }
// })

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  try {
    fs.accessSync(DIR.dist, fs.F_OK)
    del.sync(DIR.dist)
  } catch (e) {}
  fs.mkdirSync(DIR.dist)
  next()
})

const common = [
  'utility.js',
  'data/httpproxy.js',
  'driver.js',
  'loader.js',
  'state.js',
  'task.js',
  'taskrunner.js',
  'viewregistry.js',
  'viewcomponent.js'
]

const minifyConfig = {
  presets: ['es2015', 'es2017'],
  mangle: true,
  compress: {
    dead_code: true,
    global_defs: {
      DEBUG: false
    },
    warnings: true,
    drop_debugger: true,
    unused: true,
    if_return: true,
    passes: 3
  }
}

const babelConfig = {
  presets: ['es2015', 'es2017']
}

const expand = function (array) {
  return array.map(function (file) {
    return path.join(DIR.source, file)
  })
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

require('colors')
gulp.task('generate', function () {
  console.log('Generating distribution files in ', DIR.dist)
  const tasks = new ShortBus()
  const mapRoot = 'https://cdn.author.io/ngnx/' + pkg.version
  const srcmapcfg = {
    includeContent: true,
    sourceMappingURL: function (file) {
      return mapRoot + '/' + file.relative + '.map'
    },
    sourceURL: function (file) {
      return file.relative.replace('.min.js', '.js')
    }
  }

  const pkg = require('./package.json')

  common.forEach(function (filename) {
    tasks.add('Generating common file:' + filename, function (cont) {
      gulp.src(path.join(DIR.source, filename))
        .pipe(concat(filename.replace('.js', '.min.js').replace(path.sep, '.')))
        .pipe(babel(babelConfig))
        .pipe(uglify(minifyConfig))
        .pipe(header(headerComment))
        .pipe(sourcemaps.write('./sourcemaps', srcmapcfg))
        .pipe(gulp.dest(DIR.dist))
        .on('end', cont)
    })
  })

  // Generate full project
  tasks.add('Generating debug version: chassis.x.dev.js', function (cont) {
    gulp.src(expand(common))
      .pipe(concat('chassis.x.dev.js'))
      .pipe(header(headerComment))
      .pipe(footer(`Object.defineProperty(NGNX, 'version', NGN.const('${pkg.version}'))`))
      .pipe(gulp.dest(DIR.dist))
      .on('end', cont)
  })

  tasks.add('Generate full library: chassis.x.min.js', function (cont) {
    return gulp.src(expand(common))
      .pipe(concat('chassis.x.min.js'))
      .pipe(babel(babelConfig))
      .pipe(uglify(minifyConfig))
      .pipe(header(headerComment))
      .pipe(footer(`Object.defineProperty(NGNX, 'version', NGN.const('${pkg.version}'))`))
      .pipe(sourcemaps.write('./sourcemaps', srcmapcfg))
      .pipe(gulp.dest(DIR.dist))
      .on('end', cont)
  })

  tasks.on('stepstarted', (step) => {
    console.log(step.number + ')', step.name)
  })

  tasks.process(true)
})

gulp.task('prereleasecheck', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ""
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      next()
    } else {
      console.log('The version has not changed (' + pkg.version + '). A new release is unnecessary. Aborting deployment with success code.')
      process.exit(0)
    }
  })
})

gulp.task('release', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ""
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      if (!mh.hasAll(process.env, 'GITHUB_TOKEN', 'GITHUB_ACCOUNT', 'GITHUB_REPO')) {
        throw new Error('Release not possible. Missing data: ' + mh.missing.join(', '))
      }

      // Check if the release already exists.
      const https = require('https')

      https.get({
        hostname: 'api.github.com',
        path: '/repos/' + process.env.GITHUB_ACCOUNT + '/' + process.env.GITHUB_REPO + '/releases',
        headers: {
          'user-agent': 'Release Checker'
        }
      }, function (res) {
        let data = ""
        res.on('data', function (chunk) {
          data += chunk
        })

        res.on('error', function (err) {
          throw err
        })

        res.on('end', function () {
          data = JSON.parse(data).filter(function (release) {
            return release.tag_name === pkg.version
          })

          if (data.length > 0) {
            console.log('Release ' + pkg.version + ' already exists. Aboting without error.')
            process.exit(0)
          }

          const assets = walk(DIR.dist).sort()

          GithubPublisher({
            token: process.env.GITHUB_TOKEN,
            owner: process.env.GITHUB_ACCOUNT,
            repo: process.env.GITHUB_REPO,
            tag: pkg.version,
            name: pkg.version,
            notes: 'Releasing v' + pkg.version,
            draft: false,
            prerelease: false,
            reuseRelease: true,
            reuseDraftOnly: true,
            assets: assets,
            // apiUrl: 'https://myGHEserver/api/v3',
            target_commitish: 'master'
          }, function (err, release) {
            if (err) {
              err.errors.forEach(function (e) {
                console.error((e.resource + ' ' + e.code).red.bold)
              })
              process.exit(1)
            }
            console.log(release)
          })
        })
      })
    }
  })
})
<commit_msg>Fixed build process<commit_after>'use strict'

require('localenvironment')
const gulp = require('gulp')
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const cp = require('child_process')
const header = require('gulp-header')
const footer = require('gulp-footer')
const sourcemaps = require('gulp-sourcemaps')
const ShortBus = require('shortbus')
const del = require('del')
const MustHave = require('musthave')
const mh = new MustHave({
  throwOnError: false
})
const GithubPublisher = require('publish-release')
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
let headerComment = '/**\n  * v' + pkg.version + ' generated on: '
  + (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear()
  + ', Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD).\n  */\n'

var DIR = {
  source: path.resolve('./src'),
  dist: path.resolve('./dist')
}

// Build a release
gulp.task('build', ['clean', 'generate'])

// Check versions for Bower & npm
// gulp.task('version', function (next) {
//   console.log('Checking versions.')
//
//   // Sync Bower
//   var bower = require('./bower.json')
//   if (bower.version !== pkg.version) {
//     console.log('Updating bower package.')
//     bower.version = pkg.version
//     fs.writeFileSync(path.resolve('./bower.json'), JSON.stringify(bower, null, 2))
//   }
// })

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  try {
    fs.accessSync(DIR.dist, fs.F_OK)
    del.sync(DIR.dist)
  } catch (e) {}
  fs.mkdirSync(DIR.dist)
  next()
})

const common = [
  'utility.js',
  'data/httpproxy.js',
  'driver.js',
  'loader.js',
  'state.js',
  'task.js',
  'taskrunner.js',
  'viewregistry.js',
  'viewcomponent.js'
]

const minifyConfig = {
  presets: ['es2015', 'es2017'],
  mangle: true,
  compress: {
    dead_code: true,
    global_defs: {
      DEBUG: false
    },
    warnings: true,
    drop_debugger: true,
    unused: true,
    if_return: true,
    passes: 3
  }
}

const babelConfig = {
  presets: ['es2015', 'es2017']
}

const expand = function (array) {
  return array.map(function (file) {
    return path.join(DIR.source, file)
  })
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

require('colors')
gulp.task('generate', function () {
  console.log('Generating distribution files in ', DIR.dist)
  const tasks = new ShortBus()
  const mapRoot = 'https://cdn.author.io/ngnx/' + pkg.version
  const srcmapcfg = {
    includeContent: true,
    sourceMappingURL: function (file) {
      return mapRoot + '/' + file.relative + '.map'
    },
    sourceURL: function (file) {
      return file.relative.replace('.min.js', '.js')
    }
  }

  common.forEach(function (filename) {
    tasks.add('Generating common file:' + filename, function (cont) {
      gulp.src(path.join(DIR.source, filename))
        .pipe(concat(filename.replace('.js', '.min.js').replace(path.sep, '.')))
        .pipe(babel(babelConfig))
        .pipe(uglify(minifyConfig))
        .pipe(header(headerComment))
        .pipe(sourcemaps.write('./sourcemaps', srcmapcfg))
        .pipe(gulp.dest(DIR.dist))
        .on('end', cont)
    })
  })

  // Generate full project
  tasks.add('Generating debug version: chassis.x.dev.js', function (cont) {
    gulp.src(expand(common))
      .pipe(concat('chassis.x.dev.js'))
      .pipe(header(headerComment))
      .pipe(footer(`Object.defineProperty(NGNX, 'version', NGN.const('${pkg.version}'))`))
      .pipe(gulp.dest(DIR.dist))
      .on('end', cont)
  })

  tasks.add('Generate full library: chassis.x.min.js', function (cont) {
    return gulp.src(expand(common))
      .pipe(concat('chassis.x.min.js'))
      .pipe(babel(babelConfig))
      .pipe(uglify(minifyConfig))
      .pipe(header(headerComment))
      .pipe(footer(`Object.defineProperty(NGNX, 'version', NGN.const('${pkg.version}'))`))
      .pipe(sourcemaps.write('./sourcemaps', srcmapcfg))
      .pipe(gulp.dest(DIR.dist))
      .on('end', cont)
  })

  tasks.on('stepstarted', (step) => {
    console.log(step.number + ')', step.name)
  })

  tasks.process(true)
})

gulp.task('prereleasecheck', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ""
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      next()
    } else {
      console.log('The version has not changed (' + pkg.version + '). A new release is unnecessary. Aborting deployment with success code.')
      process.exit(0)
    }
  })
})

gulp.task('release', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ""
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      if (!mh.hasAll(process.env, 'GITHUB_TOKEN', 'GITHUB_ACCOUNT', 'GITHUB_REPO')) {
        throw new Error('Release not possible. Missing data: ' + mh.missing.join(', '))
      }

      // Check if the release already exists.
      const https = require('https')

      https.get({
        hostname: 'api.github.com',
        path: '/repos/' + process.env.GITHUB_ACCOUNT + '/' + process.env.GITHUB_REPO + '/releases',
        headers: {
          'user-agent': 'Release Checker'
        }
      }, function (res) {
        let data = ""
        res.on('data', function (chunk) {
          data += chunk
        })

        res.on('error', function (err) {
          throw err
        })

        res.on('end', function () {
          data = JSON.parse(data).filter(function (release) {
            return release.tag_name === pkg.version
          })

          if (data.length > 0) {
            console.log('Release ' + pkg.version + ' already exists. Aboting without error.')
            process.exit(0)
          }

          const assets = walk(DIR.dist).sort()

          GithubPublisher({
            token: process.env.GITHUB_TOKEN,
            owner: process.env.GITHUB_ACCOUNT,
            repo: process.env.GITHUB_REPO,
            tag: pkg.version,
            name: pkg.version,
            notes: 'Releasing v' + pkg.version,
            draft: false,
            prerelease: false,
            reuseRelease: true,
            reuseDraftOnly: true,
            assets: assets,
            // apiUrl: 'https://myGHEserver/api/v3',
            target_commitish: 'master'
          }, function (err, release) {
            if (err) {
              err.errors.forEach(function (e) {
                console.error((e.resource + ' ' + e.code).red.bold)
              })
              process.exit(1)
            }
            console.log(release)
          })
        })
      })
    }
  })
})
<|endoftext|>