<commit_before>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"      : true,
        "keijiban"     : true,
        "window"       : true,
        "baseSlice"    : true,
        "chunk"        : true,
        "buildToggler" : true,
        "require"      : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("keijiban.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

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

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<commit_msg>#21 Adding config to the build task<commit_after>// ---------- Plugins and paths ----------

var gulp = require("gulp"),
    clean = require("gulp-clean"),
    zip = require("gulp-zip"),
    concat = require("gulp-concat"),
    rename = require("gulp-rename"),
    uglify = require("gulp-uglify"),
    sass = require("gulp-sass"),
    cssnano = require("gulp-cssnano"),
    htmlreplace = require("gulp-html-replace"),
    eslint = require("gulp-eslint"),
    scsslint = require("gulp-scss-lint"),
    bump = require("gulp-bump"),
    git = require("gulp-git"),
    tag_version = require("gulp-tag-version"),
    paths = {
        // All JS files - for linting
        allscripts : ["src/app/**/*.js", "gulpfile.js"],
        // Only source JS files - for building the artefact
        appscripts : ["src/app/app.module.js", "src/app/**/*.js"],
        // All scss files
        styles     : "src/assets/styles/*.scss",
        // All image files
        images     : "src/assets/images/**/*.png",
        // The config settings for the app
        config     : "src/app/app.config.json"
    };

// ---------- Code lint and tidy up tasks ----------

// Clean /dist and remove everything
gulp.task("clean", function () {
  return gulp.src("dist/*", {read:false})
    .pipe(clean({
        force : true
    }));
});

// Check the JS code against ESLint standards
gulp.task("eslint", function() {
  return gulp.src(paths.allscripts).pipe(eslint({
    extends : "eslint:recommended",
    rules : {
        "quotes" : [1, "double"],
        "semi"   : [1, "always"]
    },
    globals : {
        "angular"      : true,
        "keijiban"     : true,
        "window"       : true,
        "baseSlice"    : true,
        "chunk"        : true,
        "buildToggler" : true,
        "require"      : true
    }
  }))
  .pipe(eslint.format())
  .pipe(eslint.failOnError()); // Fail task on lint errors
});

// Check the SCSS code against scss-lint standards
gulp.task("scsslint", function() {
  return gulp.src(paths.styles)
    .pipe(scsslint())
    .pipe(scsslint.failReporter()); // Report failures in the console
});

// Combination task which checks the .js and .scss files against coding standards
gulp.task("code-check", ["eslint", "scsslint"]);

// ---------- Production build tasks ----------

// Build an artefact and zip everything up
gulp.task("build", ["scripts", "bower_components", "styles", "html", "images", "index", "config", "misc"], function() {
  return gulp.src("dist/**/**")
    .pipe(zip("keijiban.zip"))
    .pipe(gulp.dest("dist"));
});

// Combine all the src JS, minify and then uglify
gulp.task("scripts", function() {
  return gulp.src(paths.appscripts)
    .pipe(concat("app.js"))
    .pipe(gulp.dest("dist"))
    .pipe(rename("app.min.js"))
    //.pipe(uglify()) // Causes problems loading bower.json
    .pipe(gulp.dest("dist"));
});

// Combine sccs into one file, compile into css, minify
gulp.task("styles", function() {
  return gulp.src(paths.styles)
    .pipe(sass().on("error", sass.logError)) // Log sass errors
    .pipe(concat("app.min.css"))
    .pipe(cssnano())
    .pipe(gulp.dest("dist"));
});

// Move all the html into /dist
gulp.task("html", function() {
  return gulp.src("src/app/**/*.html")
    .pipe(gulp.dest("dist/src/app"));
});

// Move the images into /dist
gulp.task("images", function() {
  return gulp.src(paths.images)
    .pipe(gulp.dest("dist/src/assets/images/"));
});

// Move the app config into /dist
gulp.task("config", function() {
  return gulp.src(paths.config)
    .pipe(gulp.dest("dist/src/app"));
});

// Move index.html into /dist and replace the filepaths as required
gulp.task("index", function() {
  return gulp.src("index.html")
    .pipe(htmlreplace({
        "css" : "app.min.css",
        "js"  : "app.min.js"
    }))
    .pipe(gulp.dest("dist"));
});

// Copy all the required bower dependencies into /dist
gulp.task("bower_components", function() {
  return gulp.src(["bower_components/angular/angular.min.js",
                   "bower_components/angular-animate/angular-animate.min.js",
                   "bower_components/angular-aria/angular-aria.min.js",
                   "bower_components/angular-material/angular-material.min.js",
                   "bower_components/angular-route/angular-route.min.js",
                   "bower_components/angular-material/angular-material.min.css",
                   "bower_components/font-awesome/**"],
                   {base : "bower_components/"})
    .pipe(gulp.dest("dist/bower_components"));
});

// Move other misc files into /dist
gulp.task("misc", function() {
  return gulp.src(["bower.json", "package.json", "README.md"])
    .pipe(gulp.dest("dist/"));
});

// ---------- Local development build tasks ----------

// Compiles scss into css without minifying so debugging is easier
gulp.task("styles-dev", function() {
  return gulp.src(paths.styles)
    .pipe(concat("app.scss"))
    .pipe(sass().on("error", sass.logError))
    .pipe(rename("app.styles.css"))
    .pipe(gulp.dest("dist"));
});

// ---------- Bump version number tasks ----------

// Pre-release update for bower and npm versions
gulp.task("bump-prerelease", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type  : "prerelease",
        preid : "SNAPSHOT"
    }))
  .pipe(gulp.dest("./"));
});

// Micro update for bower and npm versions
gulp.task("bump-patch", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "patch"
    }))
  .pipe(gulp.dest("./"));
});

// Minor update for bower and npm versions
gulp.task("bump-minor", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "minor"
    }))
  .pipe(gulp.dest("./"));
});

// Major update for bower and npm versions
gulp.task("bump-major", function() {
  gulp.src(["./bower.json", "./package.json"])
  .pipe(bump({
        type : "major"
    }))
  .pipe(gulp.dest("./"));
});

// ---------- Git tasks ----------

// Tag the git repository using the version number in the package.json
gulp.task("git-tag", function() {
  return gulp.src(["./package.json"])
    .pipe(git.commit("Releasing new version"))
    .pipe(tag_version());
});

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

// Rerun tasks when a file changes, for local development
gulp.task("watch", function() {
  gulp.watch(paths.styles, ["styles-dev"]);
});

// ---------- Release tasks ----------

// Dev release
gulp.task("dev-release",   ["code-check", "build"]);
// Check code standards, update the version numbers as
// needed, create the release artefact, tag the branch in git and commit it
gulp.task("micro-release", ["code-check", "bump-patch", "build", "git-tag"]);
gulp.task("minor-release", ["code-check", "bump-minor", "build", "git-tag"]);
gulp.task("major-release", ["code-check", "bump-major", "build", "git-tag"]);

// ---------- Default task ----------

// Compile the scss into css but don"t minify incase of debugging, watch for changes
gulp.task("default", ["code-check", "styles-dev", "watch"]);
<|endoftext|>


<commit_before>import { toC } from '../core/space-transf.js';
import { isNil } from '../core/utils.js';

const _angle = (deg) => {

	let ang = deg%360;
	if(ang > 180){
		ang -= 360;
	}

	const isVert = Math.abs(ang) > 45 && Math.abs(ang) < 135;

	const dir = isVert ? ang < 0 ? -1 : 1 : ang > -45 && ang < 45 ? 1 : -1;
	const hookDir = isVert ? Math.abs(ang) < 90 ? 1 : -1 : ang > 0 ? 1 : -1;

	return {
		rad: ang * Math.PI / 180,
		isVert,
		dir,
		hookDir
	};
};

const nat = (d,p) => {

	const ang = {
		x: {
			s: 0,
			i: 180
		},
		y: {
			s: 90,
			i: -90
		}
	};

	return {
		isVert: d === 'y',
		rad: (p[d] > 0 ? ang[d].s : ang[d].i) * Math.PI / 180,
		dir: p[d] > 0 ? 1 : -1,
		hookDir: 1
	};

};

const angle = (ang,dir,pos) => ang === 'nat' ? nat(dir,pos) : _angle(ang);

// in fct so we don't compute if
// no tag
// tag = {
//	 pin: true || false // show the line
//	 pinHook:  // horizontal line
//	 pinLength: // length to mark
//	 print: // how to print
//	 theta: // angle from mark
// }
const pin = function(get, { pos, tag, ds, motherCss, dir }) {
	// angle
	const ang = angle(tag.pinAngle,dir,pos);
	// anchor
	let anchor = {
		top:		ang.isVert && ang.dir < 0,
		bottom: ang.isVert && ang.dir > 0,
		left:  !ang.isVert && ang.dir > 0,
		right: !ang.isVert && ang.dir < 0
	};

	const css = isNil(tag.css) ? motherCss : tag.css;

		// mark
	const mpos = {
		x: toC(ds.x,pos.x),
		y: toC(ds.y,pos.y)
	};

		// pin length
	const pl = {
		x: Math.cos(ang.rad) * tag.pinLength,
		y: Math.sin(ang.rad) * tag.pinLength,
	};

		// pin hook
	const ph = {
		x: ang.isVert ? ang.hookDir * tag.pinHook : 0,
		y: ang.isVert ? 0 : ang.hookDir * tag.pinHook
	};

	if(Math.abs(ph.x) > 1e-2){
		anchor.top = false;
		anchor.bottom = false;
		if(ph.x > 0){
			anchor.left = true;
		}else{
			anchor.right = true;
		}
	}

	if(Math.abs(ph.y) > 1e-2){
		anchor.left = false;
		anchor.right = false;
		if(ph.y > 0){
			anchor.top = true;
		}else{
			anchor.bottom = true;
		}
	}

	const baseline = anchor.top ? 'hanging' : anchor.bottom ? 'text-after-edge' : 'middle';

	// position = mark + length + hook
	const lpos = {
		x: mpos.x + pl.x + ph.x,
		y: mpos.y - pl.y + ph.y
	};

		//y: lpos.y + ( anchor.top ? 0.9 * height : anchor.bottom ? - 0.25 * height : 0.25 * height )
	const lAnc = {
		x: lpos.x + ( anchor.left ? 3 : -3 ),
		y: lpos.y + ( anchor.top ? 3 : anchor.bottom ? -3 : 0 )
	};

	const path = `M ${mpos.x},${mpos.y} L ${mpos.x + pl.x},${mpos.y - pl.y} L ${lpos.x},${lpos.y}`;
	return {
    css,
		label: tag.print(pos),
		baseline,
		labelAnc: anchor.top || anchor.bottom ? 'middle' : anchor.left ? 'start' : 'end',
		labelFS: tag.fontSize,
		x: lpos.x,
		y: lpos.y,
		xL: lAnc.x,
		yL: lAnc.y,
		path: !tag.pin ? null : path,
		pinColor: tag.pinColor,
    pinWidth: tag.pinWidth,
		color: tag.color
	};
};

export let vm = {
	create: (get, { pos, tag, ds, motherCss, dir, measurer, cn }) => tag.show ? pin(get, { pos, tag, ds, motherCss, dir, measurer, cn }) : null
};
<commit_msg>bugfix natural direction for pin label<commit_after>import { toC } from '../core/space-transf.js';
import { isNil } from '../core/utils.js';

const _angle = (deg) => {

	let ang = deg%360;
	if(ang > 180){
		ang -= 360;
	}

	const isVert = Math.abs(ang) > 45 && Math.abs(ang) < 135;

	const dir = isVert ? ang < 0 ? -1 : 1 : ang > -45 && ang < 45 ? 1 : -1;
	const hookDir = isVert ? Math.abs(ang) < 90 ? 1 : -1 : ang > 0 ? 1 : -1;

	return {
		rad: ang * Math.PI / 180,
		isVert,
		dir,
		hookDir
	};
};

const nat = (d,p) => {

	const oDir = d === 'x' ? 'y' : 'x';

	const ang = {
		x: {
			o: 0,
			i: 180
		},
		y: {
			o: 90,
			i: -90
		}
	};

	return {
		isVert: d === 'x',
		rad: (p[oDir] > 0 ? ang[d].o : ang[d].i) * Math.PI / 180,
		dir: p[oDir] > 0 ? 1 : -1,
		hookDir: 1
	};

};

const angle = (ang,dir,pos) => ang === 'nat' ? nat(dir,pos) : _angle(ang);

// in fct so we don't compute if
// no tag
// tag = {
//	 pin: true || false // show the line
//	 pinHook:  // horizontal line
//	 pinLength: // length to mark
//	 print: // how to print
//	 theta: // angle from mark
// }
const pin = function(get, { pos, tag, ds, motherCss, dir }) {
	// angle
	const ang = angle(tag.pinAngle,dir,pos);
	// anchor
	let anchor = {
		top:		ang.isVert && ang.dir < 0,
		bottom: ang.isVert && ang.dir > 0,
		left:  !ang.isVert && ang.dir > 0,
		right: !ang.isVert && ang.dir < 0
	};

	const css = isNil(tag.css) ? motherCss : tag.css;

		// mark
	const mpos = {
		x: toC(ds.x,pos.x),
		y: toC(ds.y,pos.y)
	};

		// pin length
	const pl = {
		x: Math.cos(ang.rad) * tag.pinLength,
		y: Math.sin(ang.rad) * tag.pinLength,
	};

		// pin hook
	const ph = {
		x: ang.isVert ? ang.hookDir * tag.pinHook : 0,
		y: ang.isVert ? 0 : ang.hookDir * tag.pinHook
	};

	if(Math.abs(ph.x) > 1e-2){
		anchor.top = false;
		anchor.bottom = false;
		if(ph.x > 0){
			anchor.left = true;
		}else{
			anchor.right = true;
		}
	}

	if(Math.abs(ph.y) > 1e-2){
		anchor.left = false;
		anchor.right = false;
		if(ph.y > 0){
			anchor.top = true;
		}else{
			anchor.bottom = true;
		}
	}

	const baseline = anchor.top ? 'hanging' : anchor.bottom ? 'text-after-edge' : 'middle';

	// position = mark + length + hook
	const lpos = {
		x: mpos.x + pl.x + ph.x,
		y: mpos.y - pl.y + ph.y
	};

		//y: lpos.y + ( anchor.top ? 0.9 * height : anchor.bottom ? - 0.25 * height : 0.25 * height )
	const lAnc = {
		x: lpos.x + ( anchor.left ? 3 : -3 ),
		y: lpos.y + ( anchor.top ? 3 : anchor.bottom ? -3 : 0 )
	};

	const path = `M ${mpos.x},${mpos.y} L ${mpos.x + pl.x},${mpos.y - pl.y} L ${lpos.x},${lpos.y}`;
	return {
    css,
		label: tag.print(pos),
		baseline,
		labelAnc: anchor.top || anchor.bottom ? 'middle' : anchor.left ? 'start' : 'end',
		labelFS: tag.fontSize,
		x: lpos.x,
		y: lpos.y,
		xL: lAnc.x,
		yL: lAnc.y,
		path: !tag.pin ? null : path,
		pinColor: tag.pinColor,
    pinWidth: tag.pinWidth,
		color: tag.color
	};
};

export let vm = {
	create: (get, { pos, tag, ds, motherCss, dir, measurer, cn }) => tag.show ? pin(get, { pos, tag, ds, motherCss, dir, measurer, cn }) : null
};
<|endoftext|>


<commit_before>/*
* @Author: cs_victor
* @Date:   2016-07-16 17:50:31
* @Last Modified by:   cs_victor
* @Last Modified time: 2016-07-17 13:20:17
*/
var
    gulp = require('gulp'),
    rimraf = require('gulp-rimraf'),
    usemin = require('gulp-usemin'),
    uglify = require("gulp-uglify"),
    minifyHtml = require('gulp-minify-html'),
    minifycss = require("gulp-minify-css"),
    rev = require('gulp-rev'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    sequence = require('gulp-sequence'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    gutil = require('gulp-util'),
    rename = require('gulp-rename'),
    ejs = require("gulp-ejs");

var
    through = require('through2'),
    path = require('path'),
    colors = require('colors');

/**
 * 页面配置
 */
var configPages = require('./config/config-pages');
// 需要压缩的静态HTML列表
var USEMIN_HTML_LIST = [];
configPages.forEach(function(item) {
    USEMIN_HTML_LIST.push(item.page + '.html');
});
// 需要编译的EJS模板列表
var EJS_LIST = configPages.slice(0);

/**
 * 自定义部署目录
 */
var EJS_PATH = './views/';
var STATIC_PATH = './generate/';
var DEPLOY_PATH = './dist/';
var DEV_LESS_PATH = './public/stylesheets/less/';
var DEV_CSS_PATH = './public/stylesheets/';

/**
 * 清理发布目录
 */
gulp.task('clean', ['clean-static', 'clean-dist'], function() {
    console.log('static & dist both clean.'.green);
});
gulp.task('clean-static', function() {
    return gulp.src(STATIC_PATH, { read: false })
        .pipe(rimraf());
});
gulp.task('clean-dist', function() {
    return gulp.src(DEPLOY_PATH, { read: false })
        .pipe(rimraf());
});

/**
 * EJS模板编译任务列表
 *
 * 总任务名：static
 */
var staticTasks = [];
EJS_LIST.forEach(function(tpl) {
    var task = 'static-' + tpl.page + '.ejs';
    staticTasks.push(task);
    gulp.task(task, function() {
        // ejs 模板路径
        var fileName = EJS_PATH + tpl.page + '.ejs';

        // 文件相对路径
        var dir = path.dirname(tpl.page);

        // 编译ejs
        gulp.src(fileName)
            .pipe(ejs(tpl.data).on('error', gutil.log))
            .pipe(rename({
                extname: '.html'
            }))
            .pipe(gulp.dest(STATIC_PATH + dir))
    });
});
gulp.task("static", staticTasks, function() {
    // console.info('Static html finished.'.green);
});

/**
 * 静态资源拷贝
 * 与生成静态HTML一起执行
 * 排除了less
 */
gulp.task('copy-assets', function(){
    return gulp.src(['./public/**/*','!**/*less*'])
        .pipe(gulp.dest(STATIC_PATH));
});

/**
 * 压缩图片用于发布
 *与压缩静态HTML一起执行
 */
gulp.task('min-image', function() {
    return gulp.src(STATIC_PATH + 'assets/images/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }],
            use: [pngquant()]
        }))
        .pipe(gulp.dest(DEPLOY_PATH + 'assets/images/'));
});

/**
 * 静态HTML源代码压缩、合并、替换引用任务列表
 * 由于每个页面的js和css可能是共同引用的，所以不能并行处理，
 * 利用任务队列，一个一个执行。
 *
 * 总任务名：usemin
 */
USEMIN_HTML_LIST.forEach(function(htmlName) {
    var dir = path.dirname(htmlName);
    gulp.task('usemin-' + htmlName, function() {
        return gulp.src(STATIC_PATH + htmlName)
            .pipe(usemin({
                html: [function() {
                    return minifyHtml({ // 压缩html
                        empty: true,
                        conditionals: true,
                        spare: true,
                        cdata: true
                    });
                }],
                js: [uglify()], // 压缩js
                css: [minifycss()] // 压缩css
            }))
            .pipe(rev()) // md5后缀
            // .pipe(rev.manifest())
            .pipe(gulp.dest(DEPLOY_PATH + dir));
    });
});
var useminSequenceTasks = USEMIN_HTML_LIST.map(function(htmlName) {
    return "'usemin-" + htmlName + "'";
}).join(',');
var sequenceTaskString = "gulp.task('usemin', sequence(" + useminSequenceTasks + "));"
eval(sequenceTaskString);

/**
 * Less 编译
 */
gulp.task("less", function() {
    gulp.src(DEV_LESS_PATH + "*.less")
        .pipe(less())
        .pipe(autoprefixer({ cascade: false, browsers: ['> 1%', 'Firefox >= 10', 'Opera >= 10', 'ie >= 9', 'iOS >= 4', 'Chrome >= 10'] }))
        .pipe(gulp.dest(DEV_CSS_PATH));
});
/**
 * Less 编译 - 自动
 */
gulp.task("auto-less", function() {
    gulp.watch(DEV_LESS_PATH + "*.less", ["less"]);
});

/**
 * 配置默认gulp任务
 */
gulp.task('step1', ['clean-static'], function(){
    gulp.start('static');
    gulp.start('copy-assets');
});

gulp.task('step2', ['clean-dist'], function(){
    gulp.start('usemin');
    gulp.start('min-image');
});

gulp.task('default', ['step1'], function() {
    // 由于磁盘写入延迟，所以
    // 延迟1s开始 step2 任务
    setTimeout(function(){
        gulp.start('step2');
    },1000);
});<commit_msg>fix dist favicon<commit_after>/*
* @Author: cs_victor
* @Date:   2016-07-16 17:50:31
* @Last Modified by:   cs_victor
* @Last Modified time: 2016-07-17 13:20:17
*/
var
    gulp = require('gulp'),
    rimraf = require('gulp-rimraf'),
    usemin = require('gulp-usemin'),
    uglify = require("gulp-uglify"),
    minifyHtml = require('gulp-minify-html'),
    minifycss = require("gulp-minify-css"),
    rev = require('gulp-rev'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    sequence = require('gulp-sequence'),
    less = require('gulp-less'),
    autoprefixer = require('gulp-autoprefixer'),
    gutil = require('gulp-util'),
    rename = require('gulp-rename'),
    ejs = require("gulp-ejs");

var
    through = require('through2'),
    path = require('path'),
    colors = require('colors');

/**
 * 页面配置
 */
var configPages = require('./config/config-pages');
// 需要压缩的静态HTML列表
var USEMIN_HTML_LIST = [];
configPages.forEach(function(item) {
    USEMIN_HTML_LIST.push(item.page + '.html');
});
// 需要编译的EJS模板列表
var EJS_LIST = configPages.slice(0);

/**
 * 自定义部署目录
 */
var EJS_PATH = './views/';
var STATIC_PATH = './generate/';
var DEPLOY_PATH = './dist/';
var DEV_LESS_PATH = './public/stylesheets/less/';
var DEV_CSS_PATH = './public/stylesheets/';

/**
 * 清理发布目录
 */
gulp.task('clean', ['clean-static', 'clean-dist'], function() {
    console.log('static & dist both clean.'.green);
});
gulp.task('clean-static', function() {
    return gulp.src(STATIC_PATH, { read: false })
        .pipe(rimraf());
});
gulp.task('clean-dist', function() {
    return gulp.src(DEPLOY_PATH, { read: false })
        .pipe(rimraf());
});

/**
 * EJS模板编译任务列表
 *
 * 总任务名：static
 */
var staticTasks = [];
EJS_LIST.forEach(function(tpl) {
    var task = 'static-' + tpl.page + '.ejs';
    staticTasks.push(task);
    gulp.task(task, function() {
        // ejs 模板路径
        var fileName = EJS_PATH + tpl.page + '.ejs';

        // 文件相对路径
        var dir = path.dirname(tpl.page);

        // 编译ejs
        gulp.src(fileName)
            .pipe(ejs(tpl.data).on('error', gutil.log))
            .pipe(rename({
                extname: '.html'
            }))
            .pipe(gulp.dest(STATIC_PATH + dir))
    });
});
gulp.task("static", staticTasks, function() {
    // console.info('Static html finished.'.green);
});

/**
 * 静态资源拷贝
 * 与生成静态HTML一起执行
 * 排除了less
 */
gulp.task('copy-assets', function(){
    return gulp.src(['./public/**/*','!**/*less*'])
        .pipe(gulp.dest(STATIC_PATH));
});

/**
 * 在dist时候，补充favcion.ico
 */
gulp.task('copy-assets-favicon', function(){
    return gulp.src(['./public/favicon.ico'])
        .pipe(gulp.dest(DEPLOY_PATH))
});

/**
 * 压缩图片用于发布
 *与压缩静态HTML一起执行
 */
gulp.task('min-image', function() {
    return gulp.src(STATIC_PATH + 'assets/images/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{ removeViewBox: false }],
            use: [pngquant()]
        }))
        .pipe(gulp.dest(DEPLOY_PATH + 'assets/images/'));
});

/**
 * 静态HTML源代码压缩、合并、替换引用任务列表
 * 由于每个页面的js和css可能是共同引用的，所以不能并行处理，
 * 利用任务队列，一个一个执行。
 *
 * 总任务名：usemin
 */
USEMIN_HTML_LIST.forEach(function(htmlName) {
    var dir = path.dirname(htmlName);
    gulp.task('usemin-' + htmlName, function() {
        return gulp.src(STATIC_PATH + htmlName)
            .pipe(usemin({
                html: [function() {
                    return minifyHtml({ // 压缩html
                        empty: true,
                        conditionals: true,
                        spare: true,
                        cdata: true
                    });
                }],
                js: [uglify()], // 压缩js
                css: [minifycss()] // 压缩css
            }))
            .pipe(rev()) // md5后缀
            // .pipe(rev.manifest())
            .pipe(gulp.dest(DEPLOY_PATH + dir));
    });
});
var useminSequenceTasks = USEMIN_HTML_LIST.map(function(htmlName) {
    return "'usemin-" + htmlName + "'";
}).join(',');
var sequenceTaskString = "gulp.task('usemin', sequence(" + useminSequenceTasks + "));"
eval(sequenceTaskString);

/**
 * Less 编译
 */
gulp.task("less", function() {
    gulp.src(DEV_LESS_PATH + "*.less")
        .pipe(less())
        .pipe(autoprefixer({ cascade: false, browsers: ['> 1%', 'Firefox >= 10', 'Opera >= 10', 'ie >= 9', 'iOS >= 4', 'Chrome >= 10'] }))
        .pipe(gulp.dest(DEV_CSS_PATH));
});
/**
 * Less 编译 - 自动
 */
gulp.task("auto-less", function() {
    gulp.watch(DEV_LESS_PATH + "*.less", ["less"]);
});

/**
 * 配置默认gulp任务
 */
gulp.task('step1', ['clean-static'], function(){
    gulp.start('static');
    gulp.start('copy-assets');
});

gulp.task('step2', ['clean-dist'], function(){
    gulp.start('usemin');
    gulp.start('min-image');
    gulp.start('copy-assets-favicon');
});

gulp.task('default', ['step1'], function() {
    // 由于磁盘写入延迟，所以
    // 延迟1s开始 step2 任务
    setTimeout(function(){
        gulp.start('step2');
    },1000);
});<|endoftext|>


<commit_before>var React = require('react')
var ChatWebsocket = require('./ChatWebsocket')
import Username from '../User/Username'
import userAuth from '../userAuth'
import _ from 'lodash'

export default class ChatMessages extends React.Component {
    constructor() {
      super()

      this.state = {
        messages: [],
        loggedInUser: null
      }

      this.bottomOfList = true;
      window.addEventListener('focus', function(){
        document.title = document.title.indexOf("* ") == 0 ? document.title.slice(2) : document.title
      })
    }

    _onChatMessage(message) {
      this.setState({
        messages: this.state.messages.slice(0).concat([message])
      })
      if(!document.hasFocus() && this.state.loggedInUser != message.userId)
        document.title = document.title.indexOf("* ") == 0 ? document.title : "* " + document.title
    }

    _onChatScroll(event) {
      let {target} = event
      let {scrollTop, clientHeight, scrollHeight} = target

      this.bottomOfList = scrollTop + clientHeight >= scrollHeight
    }

    componentDidMount() {
      ChatWebsocket.setChatMessageCallback(this._onChatMessage.bind(this))
      userAuth.getUser()
        .then((user) => {
          this.setState({
            loggedInUser: user
          })
        })
    }

    componentDidUpdate(prevProps, prevState) {
      if (this.bottomOfList) {
        this.refs.chat.scrollTop = this.refs.chat.scrollHeight
      }
    }

    render(){
      var messages = this.state.messages.map((chat, chatIndex) => {
        var timeString = new Date(chat.time).toLocaleTimeString()
        return (

            <Username id={chat.userId} />

              {chat.message}

                <time>{timeString}</time>

        )
      })
      var scrollHandler = _.throttle(this._onChatScroll, 100).bind(this)
      return (

              {messages}

      )
    }
}
<commit_msg>rolling back and replacing with sensible line endings<commit_after>var React = require('react')
var ChatWebsocket = require('./ChatWebsocket')
import Username from '../User/Username'
import userAuth from '../userAuth'
import _ from 'lodash'

export default class ChatMessages extends React.Component {
    constructor() {
      super()

      this.state = {
        messages: [],
        loggedInUser: null
      }

      this.bottomOfList = true;
      window.addEventListener('focus', function(){
        document.title = document.title.indexOf("* ") == 0 ? document.title.slice(2) : document.title
      })
    }

    _onChatMessage(message) {
      this.setState({
        messages: this.state.messages.slice(0).concat([message])
      })
      if(!document.hasFocus() && this.state.loggedInUser.id !== message.userId)
        document.title = document.title.indexOf("* ") == 0 ? document.title : "* " + document.title
    }

    _onChatScroll(event) {
      let {target} = event
      let {scrollTop, clientHeight, scrollHeight} = target

      this.bottomOfList = scrollTop + clientHeight >= scrollHeight
    }

    componentDidMount() {
      ChatWebsocket.setChatMessageCallback(this._onChatMessage.bind(this))
      userAuth.getUser()
        .then((user) => {
          this.setState({
            loggedInUser: user
          })
        })
    }

    componentDidUpdate(prevProps, prevState) {
      if (this.bottomOfList) {
        this.refs.chat.scrollTop = this.refs.chat.scrollHeight
      }
    }

    render(){
      var messages = this.state.messages.map((chat, chatIndex) => {
        var timeString = new Date(chat.time).toLocaleTimeString()
        return (

            <Username id={chat.userId} />

              {chat.message}

                <time>{timeString}</time>

        )
      })
      var scrollHandler = _.throttle(this._onChatScroll, 100).bind(this)
      return (

              {messages}

      )
    }
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var log = require('./log');
var binary = require('./binary');
var Int64 = require('node-int64');
var Thrift = require('./thrift');
var Type = Thrift.Type;

module.exports = TBinaryProtocol;

// JavaScript supports only numeric doubles, therefore even hex values are always signed.
// The largest integer value which can be represented in JavaScript is +/-2^53.
// Bitwise operations convert numbers to 32 bit integers but perform sign extension
// upon assigning values back to variables.
var VERSION_MASK = -65536,   // 0xffff0000
    VERSION_1 = -2147418112, // 0x80010000
    TYPE_MASK = 0x000000ff;

function TBinaryProtocol(trans, strictRead, strictWrite) {
  this.trans = trans;
  this.strictRead = (strictRead !== undefined ? strictRead : false);
  this.strictWrite = (strictWrite !== undefined ? strictWrite : true);
};

TBinaryProtocol.prototype.flush = function() {
  return this.trans.flush();
};

TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
    if (this.strictWrite) {
      this.writeI32(VERSION_1 | type);
      this.writeString(name);
      this.writeI32(seqid);
    } else {
      this.writeString(name);
      this.writeByte(type);
      this.writeI32(seqid);
    }
    // Record client seqid to find callback again
    if (this._seqid) {
      log.warning('SeqId already set', { 'name': name });
    } else {
      this._seqid = seqid;
      this.trans.setCurrSeqId(seqid);
    }
};

TBinaryProtocol.prototype.writeMessageEnd = function() {
    if (this._seqid) {
        this._seqid = null;
    } else {
        log.warning('No seqid to unset');
    }
};

TBinaryProtocol.prototype.writeStructBegin = function(name) {
};

TBinaryProtocol.prototype.writeStructEnd = function() {
};

TBinaryProtocol.prototype.writeFieldBegin = function(name, type, id) {
  this.writeByte(type);
  this.writeI16(id);
};

TBinaryProtocol.prototype.writeFieldEnd = function() {
};

TBinaryProtocol.prototype.writeFieldStop = function() {
  this.writeByte(Type.STOP);
};

TBinaryProtocol.prototype.writeMapBegin = function(ktype, vtype, size) {
  this.writeByte(ktype);
  this.writeByte(vtype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeMapEnd = function() {
};

TBinaryProtocol.prototype.writeListBegin = function(etype, size) {
  this.writeByte(etype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeListEnd = function() {
};

TBinaryProtocol.prototype.writeSetBegin = function(etype, size) {
  this.writeByte(etype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeSetEnd = function() {
};

TBinaryProtocol.prototype.writeBool = function(bool) {
  if (bool) {
    this.writeByte(1);
  } else {
    this.writeByte(0);
  }
};

TBinaryProtocol.prototype.writeByte = function(b) {
  this.trans.write(new Buffer([b]));
};

TBinaryProtocol.prototype.writeI16 = function(i16) {
  this.trans.write(binary.writeI16(new Buffer(2), i16));
};

TBinaryProtocol.prototype.writeI32 = function(i32) {
  this.trans.write(binary.writeI32(new Buffer(4), i32));
};

TBinaryProtocol.prototype.writeI64 = function(i64) {
  if (i64.buffer) {
    this.trans.write(i64.buffer);
  } else {
    this.trans.write(new Int64(i64).buffer);
  }
};

TBinaryProtocol.prototype.writeDouble = function(dub) {
  this.trans.write(binary.writeDouble(new Buffer(8), dub));
};

TBinaryProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) {
  if (typeof(arg) === 'string') {
    this.writeI32(Buffer.byteLength(arg, encoding));
    this.trans.write(new Buffer(arg, encoding));
  } else if ((arg instanceof Buffer) ||
             (Object.prototype.toString.call(arg) == '[object Uint8Array]')) {
    // Buffers in Node.js under Browserify may extend UInt8Array instead of
    // defining a new object. We detect them here so we can write them
    // correctly
    this.writeI32(arg.length);
    this.trans.write(arg);
  } else {
    throw new Error(name + ' called without a string/Buffer argument: ' + arg);
  }
};

TBinaryProtocol.prototype.writeString = function(arg) {
  this.writeStringOrBinary('writeString', 'utf8', arg);
};

TBinaryProtocol.prototype.writeBinary = function(arg) {
  this.writeStringOrBinary('writeBinary', 'binary', arg);
};

TBinaryProtocol.prototype.readMessageBegin = function() {
  var sz = this.readI32();
  var type, name, seqid;

  if (sz < 0) {
    var version = sz & VERSION_MASK;
    if (version != VERSION_1) {
      throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad version in readMessageBegin: " + sz);
    }
    type = sz & TYPE_MASK;
    name = this.readString();
    seqid = this.readI32();
  } else {
    if (this.strictRead) {
      throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "No protocol version header");
    }
    name = this.trans.read(sz);
    type = this.readByte();
    seqid = this.readI32();
  }
  return {fname: name, mtype: type, rseqid: seqid};
};

TBinaryProtocol.prototype.readMessageEnd = function() {
};

TBinaryProtocol.prototype.readStructBegin = function() {
  return {fname: ''};
};

TBinaryProtocol.prototype.readStructEnd = function() {
};

TBinaryProtocol.prototype.readFieldBegin = function() {
  var type = this.readByte();
  if (type == Type.STOP) {
    return {fname: null, ftype: type, fid: 0};
  }
  var id = this.readI16();
  return {fname: null, ftype: type, fid: id};
};

TBinaryProtocol.prototype.readFieldEnd = function() {
};

TBinaryProtocol.prototype.readMapBegin = function() {
  var ktype = this.readByte();
  var vtype = this.readByte();
  var size = this.readI32();
  return {ktype: ktype, vtype: vtype, size: size};
};

TBinaryProtocol.prototype.readMapEnd = function() {
};

TBinaryProtocol.prototype.readListBegin = function() {
  var etype = this.readByte();
  var size = this.readI32();
  return {etype: etype, size: size};
};

TBinaryProtocol.prototype.readListEnd = function() {
};

TBinaryProtocol.prototype.readSetBegin = function() {
  var etype = this.readByte();
  var size = this.readI32();
  return {etype: etype, size: size};
};

TBinaryProtocol.prototype.readSetEnd = function() {
};

TBinaryProtocol.prototype.readBool = function() {
  var b = this.readByte();
  if (b === 0) {
    return false;
  }
  return true;
};

TBinaryProtocol.prototype.readByte = function() {
  return this.trans.readByte();
};

TBinaryProtocol.prototype.readI16 = function() {
  return this.trans.readI16();
};

TBinaryProtocol.prototype.readI32 = function() {
  return this.trans.readI32();
};

TBinaryProtocol.prototype.readI64 = function() {
  var buff = this.trans.read(8);
  return new Int64(buff);
};

TBinaryProtocol.prototype.readDouble = function() {
  return this.trans.readDouble();
};

TBinaryProtocol.prototype.readBinary = function() {
  var len = this.readI32();
  if (len === 0) {
    return new Buffer(0);
  }

  if (len < 0) {
    throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative binary size");
  }
  return this.trans.read(len);
};

TBinaryProtocol.prototype.readString = function() {
  var len = this.readI32();
  if (len === 0) {
    return "";
  }

  if (len < 0) {
    throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative string size");
  }
  return this.trans.readString(len);
};

TBinaryProtocol.prototype.getTransport = function() {
  return this.trans;
};

TBinaryProtocol.prototype.skip = function(type) {
  switch (type) {
    case Type.STOP:
      return;
    case Type.BOOL:
      this.readBool();
      break;
    case Type.BYTE:
      this.readByte();
      break;
    case Type.I16:
      this.readI16();
      break;
    case Type.I32:
      this.readI32();
      break;
    case Type.I64:
      this.readI64();
      break;
    case Type.DOUBLE:
      this.readDouble();
      break;
    case Type.STRING:
      this.readString();
      break;
    case Type.STRUCT:
      this.readStructBegin();
      while (true) {
        var r = this.readFieldBegin();
        if (r.ftype === Type.STOP) {
          break;
        }
        this.skip(r.ftype);
        this.readFieldEnd();
      }
      this.readStructEnd();
      break;
    case Type.MAP:
      var mapBegin = this.readMapBegin();
      for (var i = 0; i < mapBegin.size; ++i) {
        this.skip(mapBegin.ktype);
        this.skip(mapBegin.vtype);
      }
      this.readMapEnd();
      break;
    case Type.SET:
      var setBegin = this.readSetBegin();
      for (var i2 = 0; i2 < setBegin.size; ++i2) {
        this.skip(setBegin.etype);
      }
      this.readSetEnd();
      break;
    case Type.LIST:
      var listBegin = this.readListBegin();
      for (var i3 = 0; i3 < listBegin.size; ++i3) {
        this.skip(listBegin.etype);
      }
      this.readListEnd();
      break;
    default:
      throw new  Error("Invalid type: " + type);
  }
};
<commit_msg>THRIFT-4480 - Handle seqid = 0 Client: js<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var log = require('./log');
var binary = require('./binary');
var Int64 = require('node-int64');
var Thrift = require('./thrift');
var Type = Thrift.Type;

module.exports = TBinaryProtocol;

// JavaScript supports only numeric doubles, therefore even hex values are always signed.
// The largest integer value which can be represented in JavaScript is +/-2^53.
// Bitwise operations convert numbers to 32 bit integers but perform sign extension
// upon assigning values back to variables.
var VERSION_MASK = -65536,   // 0xffff0000
    VERSION_1 = -2147418112, // 0x80010000
    TYPE_MASK = 0x000000ff;

function TBinaryProtocol(trans, strictRead, strictWrite) {
  this.trans = trans;
  this.strictRead = (strictRead !== undefined ? strictRead : false);
  this.strictWrite = (strictWrite !== undefined ? strictWrite : true);
  this._seqid = null;
};

TBinaryProtocol.prototype.flush = function() {
  return this.trans.flush();
};

TBinaryProtocol.prototype.writeMessageBegin = function(name, type, seqid) {
    if (this.strictWrite) {
      this.writeI32(VERSION_1 | type);
      this.writeString(name);
      this.writeI32(seqid);
    } else {
      this.writeString(name);
      this.writeByte(type);
      this.writeI32(seqid);
    }
    // Record client seqid to find callback again
    if (this._seqid !== null) {
      log.warning('SeqId already set', { 'name': name });
    } else {
      this._seqid = seqid;
      this.trans.setCurrSeqId(seqid);
    }
};

TBinaryProtocol.prototype.writeMessageEnd = function() {
    if (this._seqid !== null) {
        this._seqid = null;
    } else {
        log.warning('No seqid to unset');
    }
};

TBinaryProtocol.prototype.writeStructBegin = function(name) {
};

TBinaryProtocol.prototype.writeStructEnd = function() {
};

TBinaryProtocol.prototype.writeFieldBegin = function(name, type, id) {
  this.writeByte(type);
  this.writeI16(id);
};

TBinaryProtocol.prototype.writeFieldEnd = function() {
};

TBinaryProtocol.prototype.writeFieldStop = function() {
  this.writeByte(Type.STOP);
};

TBinaryProtocol.prototype.writeMapBegin = function(ktype, vtype, size) {
  this.writeByte(ktype);
  this.writeByte(vtype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeMapEnd = function() {
};

TBinaryProtocol.prototype.writeListBegin = function(etype, size) {
  this.writeByte(etype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeListEnd = function() {
};

TBinaryProtocol.prototype.writeSetBegin = function(etype, size) {
  this.writeByte(etype);
  this.writeI32(size);
};

TBinaryProtocol.prototype.writeSetEnd = function() {
};

TBinaryProtocol.prototype.writeBool = function(bool) {
  if (bool) {
    this.writeByte(1);
  } else {
    this.writeByte(0);
  }
};

TBinaryProtocol.prototype.writeByte = function(b) {
  this.trans.write(new Buffer([b]));
};

TBinaryProtocol.prototype.writeI16 = function(i16) {
  this.trans.write(binary.writeI16(new Buffer(2), i16));
};

TBinaryProtocol.prototype.writeI32 = function(i32) {
  this.trans.write(binary.writeI32(new Buffer(4), i32));
};

TBinaryProtocol.prototype.writeI64 = function(i64) {
  if (i64.buffer) {
    this.trans.write(i64.buffer);
  } else {
    this.trans.write(new Int64(i64).buffer);
  }
};

TBinaryProtocol.prototype.writeDouble = function(dub) {
  this.trans.write(binary.writeDouble(new Buffer(8), dub));
};

TBinaryProtocol.prototype.writeStringOrBinary = function(name, encoding, arg) {
  if (typeof(arg) === 'string') {
    this.writeI32(Buffer.byteLength(arg, encoding));
    this.trans.write(new Buffer(arg, encoding));
  } else if ((arg instanceof Buffer) ||
             (Object.prototype.toString.call(arg) == '[object Uint8Array]')) {
    // Buffers in Node.js under Browserify may extend UInt8Array instead of
    // defining a new object. We detect them here so we can write them
    // correctly
    this.writeI32(arg.length);
    this.trans.write(arg);
  } else {
    throw new Error(name + ' called without a string/Buffer argument: ' + arg);
  }
};

TBinaryProtocol.prototype.writeString = function(arg) {
  this.writeStringOrBinary('writeString', 'utf8', arg);
};

TBinaryProtocol.prototype.writeBinary = function(arg) {
  this.writeStringOrBinary('writeBinary', 'binary', arg);
};

TBinaryProtocol.prototype.readMessageBegin = function() {
  var sz = this.readI32();
  var type, name, seqid;

  if (sz < 0) {
    var version = sz & VERSION_MASK;
    if (version != VERSION_1) {
      throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "Bad version in readMessageBegin: " + sz);
    }
    type = sz & TYPE_MASK;
    name = this.readString();
    seqid = this.readI32();
  } else {
    if (this.strictRead) {
      throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.BAD_VERSION, "No protocol version header");
    }
    name = this.trans.read(sz);
    type = this.readByte();
    seqid = this.readI32();
  }
  return {fname: name, mtype: type, rseqid: seqid};
};

TBinaryProtocol.prototype.readMessageEnd = function() {
};

TBinaryProtocol.prototype.readStructBegin = function() {
  return {fname: ''};
};

TBinaryProtocol.prototype.readStructEnd = function() {
};

TBinaryProtocol.prototype.readFieldBegin = function() {
  var type = this.readByte();
  if (type == Type.STOP) {
    return {fname: null, ftype: type, fid: 0};
  }
  var id = this.readI16();
  return {fname: null, ftype: type, fid: id};
};

TBinaryProtocol.prototype.readFieldEnd = function() {
};

TBinaryProtocol.prototype.readMapBegin = function() {
  var ktype = this.readByte();
  var vtype = this.readByte();
  var size = this.readI32();
  return {ktype: ktype, vtype: vtype, size: size};
};

TBinaryProtocol.prototype.readMapEnd = function() {
};

TBinaryProtocol.prototype.readListBegin = function() {
  var etype = this.readByte();
  var size = this.readI32();
  return {etype: etype, size: size};
};

TBinaryProtocol.prototype.readListEnd = function() {
};

TBinaryProtocol.prototype.readSetBegin = function() {
  var etype = this.readByte();
  var size = this.readI32();
  return {etype: etype, size: size};
};

TBinaryProtocol.prototype.readSetEnd = function() {
};

TBinaryProtocol.prototype.readBool = function() {
  var b = this.readByte();
  if (b === 0) {
    return false;
  }
  return true;
};

TBinaryProtocol.prototype.readByte = function() {
  return this.trans.readByte();
};

TBinaryProtocol.prototype.readI16 = function() {
  return this.trans.readI16();
};

TBinaryProtocol.prototype.readI32 = function() {
  return this.trans.readI32();
};

TBinaryProtocol.prototype.readI64 = function() {
  var buff = this.trans.read(8);
  return new Int64(buff);
};

TBinaryProtocol.prototype.readDouble = function() {
  return this.trans.readDouble();
};

TBinaryProtocol.prototype.readBinary = function() {
  var len = this.readI32();
  if (len === 0) {
    return new Buffer(0);
  }

  if (len < 0) {
    throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative binary size");
  }
  return this.trans.read(len);
};

TBinaryProtocol.prototype.readString = function() {
  var len = this.readI32();
  if (len === 0) {
    return "";
  }

  if (len < 0) {
    throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.NEGATIVE_SIZE, "Negative string size");
  }
  return this.trans.readString(len);
};

TBinaryProtocol.prototype.getTransport = function() {
  return this.trans;
};

TBinaryProtocol.prototype.skip = function(type) {
  switch (type) {
    case Type.STOP:
      return;
    case Type.BOOL:
      this.readBool();
      break;
    case Type.BYTE:
      this.readByte();
      break;
    case Type.I16:
      this.readI16();
      break;
    case Type.I32:
      this.readI32();
      break;
    case Type.I64:
      this.readI64();
      break;
    case Type.DOUBLE:
      this.readDouble();
      break;
    case Type.STRING:
      this.readString();
      break;
    case Type.STRUCT:
      this.readStructBegin();
      while (true) {
        var r = this.readFieldBegin();
        if (r.ftype === Type.STOP) {
          break;
        }
        this.skip(r.ftype);
        this.readFieldEnd();
      }
      this.readStructEnd();
      break;
    case Type.MAP:
      var mapBegin = this.readMapBegin();
      for (var i = 0; i < mapBegin.size; ++i) {
        this.skip(mapBegin.ktype);
        this.skip(mapBegin.vtype);
      }
      this.readMapEnd();
      break;
    case Type.SET:
      var setBegin = this.readSetBegin();
      for (var i2 = 0; i2 < setBegin.size; ++i2) {
        this.skip(setBegin.etype);
      }
      this.readSetEnd();
      break;
    case Type.LIST:
      var listBegin = this.readListBegin();
      for (var i3 = 0; i3 < listBegin.size; ++i3) {
        this.skip(listBegin.etype);
      }
      this.readListEnd();
      break;
    default:
      throw new  Error("Invalid type: " + type);
  }
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var clean = require('gulp-clean');
var coveralls = require('gulp-coveralls');
var tsc = require('gulp-typescript');
var karma = require('karma').server;

var paths = {
    source: ['src/*.ts']
};

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

gulp.task('tscAMD', ['clean'], function() {
    var tsResult = gulp.src(paths.source)
        .pipe(tsc({
            module: 'amd',
            target: 'ES5',
            declarationFiles: true
        }));

    tsResult.dts.pipe(gulp.dest('dist/amd'));

    return tsResult.js.pipe(gulp.dest('dist/amd'));
});

gulp.task('tscCommonJS', ['clean'], function() {
    var tsResult = gulp.src(paths.source)
        .pipe(tsc({
            module: 'commonjs',
            target: 'ES5',
            declarationFiles: true
        }));

    tsResult.dts.pipe(gulp.dest('dist/commonjs'));

    return tsResult.js.pipe(gulp.dest('dist/commonjs'));
});

gulp.task('cleanTest', function() {
    return gulp.src(['bin'])
        .pipe(clean());
});

gulp.task('copyDist', ['tscCommonJS'], function() {
    return gulp.src('dist/commonjs/*.js')
        .pipe(gulp.dest('bin/src'));
});

gulp.task('tscTest', ['cleanTest', 'copyDist'], function() {
    var tsResult = gulp.src('test/*.ts')
        .pipe(tsc({
            module: 'commonjs',
            target: 'ES5'
        }));

    return tsResult.js.pipe(gulp.dest('bin/test'));
});

gulp.task('test', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done);
});

gulp.task('tdd', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js'
  }, done);
});

gulp.task('ciTest', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma-ci.conf.js'
  }, done);
});

gulp.task('covertest', ['ciTest'], function() {
    return gulp.src('bin/coverage/**/lcov.info')
        .pipe(coveralls());
});

// karma blocks gulp from exiting without this
gulp.doneCallback = function(err) {
    process.exit(err? 1: 0);
}

gulp.task('default', ['tscAMD', 'tscCommonJS']);

gulp.task('watch', ['default'], function() {
    return gulp.watch('src/**/*', ['default']);
});
<commit_msg>Fix a regression in `gulp watch`<commit_after>var gulp = require('gulp');
var mocha = require('gulp-mocha');
var clean = require('gulp-clean');
var coveralls = require('gulp-coveralls');
var tsc = require('gulp-typescript');
var karma = require('karma').server;

var paths = {
    source: ['src/*.ts']
};

var shouldExit = true;

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

gulp.task('tscAMD', ['clean'], function() {
    var tsResult = gulp.src(paths.source)
        .pipe(tsc({
            module: 'amd',
            target: 'ES5',
            declarationFiles: true
        }));

    tsResult.dts.pipe(gulp.dest('dist/amd'));

    return tsResult.js.pipe(gulp.dest('dist/amd'));
});

gulp.task('tscCommonJS', ['clean'], function() {
    var tsResult = gulp.src(paths.source)
        .pipe(tsc({
            module: 'commonjs',
            target: 'ES5',
            declarationFiles: true
        }));

    tsResult.dts.pipe(gulp.dest('dist/commonjs'));

    return tsResult.js.pipe(gulp.dest('dist/commonjs'));
});

gulp.task('cleanTest', function() {
    return gulp.src(['bin'])
        .pipe(clean());
});

gulp.task('copyDist', ['tscCommonJS'], function() {
    return gulp.src('dist/commonjs/*.js')
        .pipe(gulp.dest('bin/src'));
});

gulp.task('tscTest', ['cleanTest', 'copyDist'], function() {
    var tsResult = gulp.src('test/*.ts')
        .pipe(tsc({
            module: 'commonjs',
            target: 'ES5'
        }));

    return tsResult.js.pipe(gulp.dest('bin/test'));
});

gulp.task('test', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done);
});

gulp.task('tdd', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js'
  }, done);
});

gulp.task('ciTest', ['tscTest'], function (done) {
  karma.start({
    configFile: __dirname + '/karma-ci.conf.js'
  }, done);
});

gulp.task('covertest', ['ciTest'], function() {
    return gulp.src('bin/coverage/**/lcov.info')
        .pipe(coveralls());
});

// karma blocks gulp from exiting without this
gulp.doneCallback = function(err) {
    if(shouldExit) {
        process.exit(err? 1: 0);
    }
}

gulp.task('default', ['tscAMD', 'tscCommonJS']);

gulp.task('watch', ['default'], function() {
    shouldExit = false;
    return gulp.watch('src/**/*', ['default']);
});
<|endoftext|>


<commit_before>//= require_tree ./templates

var App = Ember.Application.create({
  rootElement: '#builds-application'
});

App.Router.map(function() {
  this.route('release');
  this.route('beta');
  this.route('canary');
  this.route('tagged');
});

App.Router.reopen({
  notifyGoogleAnalytics: function() {
    var url = this.get('url');

    // Add a slash if neccesary
    if (!/^\//.test(url)){ url = '/' + url; }

    _gaq.push(['_trackPageview', '/builds' + url]);
  }.on('didTransition')
});

App.CopyClipboardComponent = Ember.Component.extend({
  tagName: 'span',
  hasFlash: ZeroClipboard.detectFlashSupport(),

  didInsertElement: function () {
    var clip = new ZeroClipboard(this.$('button'), {
      // This would normally be a relative path
      moviePath: "/images/ZeroClipboard.swf",

      trustedDomains: ["*"],
      allowScriptAccess: "always"
    });

    clip.on('mousedown', function(client, e) {
      Em.run.later(this, function() {
        $(this).removeClass('loading');
        $(this).removeAttr('disabled');
      }, 1000);
      Em.run.next(this, function() {
        $(this).addClass('loading');
        $(this).attr('disabled', 'disabled');
      });
    });

    this.$('input').on('click', function() {
      $(this).select();
    });
  }
});

App.S3Bucket = Ember.Object.extend({
  files: [],
  isLoading: false,

  // Setup these as default values.
  // They can be overridden on create.
  queryUseSSL: true,
  objectUseSSL: false,
  delimiter: '/',
  bucket: 'builds.emberjs.com',
  endpoint: 's3.amazonaws.com',

  delimiterParameter: function(){
    var delimiter = this.getWithDefault('delimiter','').toString();
    return (delimiter) ? 'delimiter=' + delimiter : '';
  }.property('delimiter'),

  markerParameter: function(){
    return 'marker=' + this.getWithDefault('marker','').toString();
  }.property('marker'),

  maxKeysParameter: function(){
    return 'max-keys=' + this.getWithDefault('maxKeys','').toString();
  }.property('maxKeys'),

  prefixParameter: function(){
    return 'prefix=' + this.getWithDefault('prefix','').toString();
  }.property('prefix'),

  queryProtocol: function() {
    return this.get('queryUseSSL') ? 'https://' : 'http://';
  }.property('queryUseSSL'),

  queryBaseUrl: function(){
    return this.get('queryProtocol') + this.get('endpoint') + '/' + this.get('bucket')
  }.property('queryProtocol', 'endpoint', 'bucket'),

  objectProtocol: function() {
    return this.get('objectUseSSL') ? 'https://' : 'http://';
  }.property('objectUseSSL'),

  objectBaseUrl: function(){
    return this.get('objectProtocol') + this.get('bucket');
  }.property('objectProtocol', 'bucket'),

  queryParams: function(){
    return this.get('delimiterParameter')  + '&' +
      this.get('markerParameter')     + '&' +
      this.get('maxKeysParameter')    + '&' +
      this.get('prefixParameter');
  }.property('delimiterParameter','markerParameter','maxKeysParameter','prefixParameter'),

  queryUrl: function(){
    return this.get('queryBaseUrl') + '?' + this.get('queryParams');
  }.property('queryBaseUrl','queryParams'),

  filesPresent: function(){
    return this.get('files').length;
  }.property('files.@each'),

  filterFiles: function(filter, ignoreFiles){
    var files = this.get('files');
    var ignoreFiles = Ember.A(ignoreFiles);

    return files.filter(function(e) {
      var name = e.get('name');
      var ignored = ignoreFiles.any(function(f) { return name.indexOf(f) >= 0; });
      var selected = name.indexOf(filter + '.') >= 0;

      return !ignored && selected;
    });
  },

  load: function(){
    var self = this,
    baseUrl = this.get('objectBaseUrl');

    this.set('isLoading', true);
    Ember.$.get(this.get('queryUrl'), function(data){
      self.set('isLoading', false);
      self.set('response', data);

      var contents = data.getElementsByTagName('Contents'),
      length   = contents.length,
      files    = [];

      for(var i = 0; i < length; i++) {
        var size = contents[i].getElementsByTagName('Size')[0].firstChild.data,
        name = contents[i].getElementsByTagName('Key')[0].firstChild.data,
        lastModified = new Date(contents[i].getElementsByTagName('LastModified')[0].firstChild.data);

        files.push(
          App.S3File.create({
          name: name,
          size: size,
          lastModified: lastModified,
          relativePath: name,
          baseUrl: baseUrl
        })
        );
      }

      self.set('files', files.sort(function(a,b){
        return b.lastModified - a.lastModified;
      }));
    });
  }.observes('queryUrl').on('init')
});

App.S3File = Ember.Object.extend({
  scriptTag: function(){
    var escapedURL = Ember.Handlebars.Utils.escapeExpression(this.get('url'));

    return new Ember.Handlebars.SafeString('<script src="' + escapedURL + '"></script>').toString();
  }.property('url'),

  url: function(){
    return this.get('baseUrl') + '/' + this.get('relativePath');
  }.property('baseUrl', 'relativePath')
});

App.Project = Ember.Object.extend();

App.Project.reopenClass({
  FIXTURES:
    [ {
      projectName: 'Ember',
      projectFilter: 'ember',
      projectRepo: 'emberjs/ember.js',
      channel: "tagged"
    }, {
      projectName: 'Ember Data',
      projectFilter: 'ember-data',
      projectRepo: 'emberjs/data',
      channel: "tagged"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      initialVersion: "1.10.0",
      initialReleaseDate: "2015-02-07",
      lastRelease: "1.10.0",
      futureVersion: "1.10.1",
      channel: "release",
      date: "2015-02-07",
      changelogPath: "CHANGELOG.md",
      enableTestURL: true,
      debugFileName: ".debug.js"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      lastRelease: "1.11.0-beta.1",
      futureVersion: "1.11.0-beta.2",
      finalVersion: '1.11.0',
      channel: "beta",
      cycleEstimatedFinishDate: '2015-03-20',
      date: "2015-02-07",
      nextDate: "2015-02-14",
      changelogPath: "CHANGELOG.md",
      enableTestURL: true,
      debugFileName: ".debug.js",
      ignoreFiles: ['ember.js']
    }, {
      projectName: "Ember Data",
      projectFilter: "ember-data",
      projectRepo: 'emberjs/data',
      lastRelease: "1.0.0-beta.14.1",
      futureVersion: "1.0.0-beta.15",
      channel: "beta",
      date: "2014-12-31",
      changelogPath: "CHANGELOG.md",
      debugFileName: ".js"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      channel: "canary",
      enableTestURL: true,
      debugFileName: ".debug.js",
      ignoreFiles: ['ember.js']
    }, {
      projectName: "Ember Data",
      projectFilter: "ember-data",
      projectRepo: 'emberjs/data',
      channel: "canary",
      debugFileName: ".js"
    }],

  all: function(channel){
    var projects;

    if (channel)
      projects = this.FIXTURES.filterBy('channel', channel);
    else
      projects = this.FIXTURES;

    return projects.map(function(obj) {
      return App.Project.create(obj);
    });
  },

  find: function(channel, name) {
    var allProjects = this.all(channel);

    if (!name)
      return allProjects;
    else
      return allProjects.filterBy('projectName', name);
  }
});

App.BuildCategoryMixin = Ember.Mixin.create({
  renderTemplate: function() {
    this.render('build-list');
  }
});

App.ApplicationController = Ember.ObjectController.extend({
  isIndexActive: function(){
    return this.isActiveChannel('index');
  }.property('currentRouteName'),

  isTaggedActive: function(){
    return this.isActiveChannel('tagged');
  }.property('currentRouteName'),

  isChannelsActive: function(){
    var self = this;
    return !['index','tagged'].some(function(name){ return name === self.get('currentRouteName'); })
  }.property('currentRouteName'),

  isReleaseActive: function(){
    return this.isActiveChannel('release');
  }.property('currentRouteName'),

  isBetaActive: function(){
    return this.isActiveChannel('beta');
  }.property('currentRouteName'),

  isCanaryActive: function(){
    return this.isActiveChannel('canary');
  }.property('currentRouteName'),

  isActiveChannel: function(channel){
    return this.get('currentRouteName').indexOf(channel) !== -1;
  }
});

App.ProjectsMixin = Ember.Mixin.create({
  projects: function(){
    var projects = App.Project.find(this.get('channel')),
        bucket   = this.get('model'),
        self = this;

    projects.forEach(function(project){
      if (project.channel === 'beta'){
        project.isEmberBeta = project.projectName === 'Ember';

        [1,2,3,4,5].forEach(function(increment){
          var versionParts = project.lastRelease.split('.');
          var currentBetaNumber = parseInt(versionParts[versionParts.length - 1], 10);
          project['beta' + increment + 'Completed'] = increment <= currentBetaNumber;
          project['isBeta' + increment] = increment === currentBetaNumber;
        });

        var release = App.Project.find('release', project.projectName)[0];

        // no releases exist for ember-data (yet)
        if (release) {
          project.lastStableVersion = release.initialVersion;
          project.lastStableDate = release.initialReleaseDate;
        }
      }

      project.files = bucket.filterFiles(project.projectFilter, project.ignoreFiles);
      project.description = self.description(project);
      project.lastReleaseDebugUrl = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, project.debugFileName);
      project.lastReleaseProdUrl  = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '.prod.js');
      project.lastReleaseMinUrl   = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '.min.js');

      if (project.enableTestURL) {
        project.lastReleaseTestUrl  = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '-tests-index.html');
      }

      if (project.channel === 'canary') {
        project.lastRelease = 'latest';
      } else if (project.changelog !== 'false') {
        project.lastReleaseChangelogUrl   = 'https://github.com/' + project.projectRepo + '/blob/v' + project.lastRelease + '/' + project.changelogPath;
      }
    });

    return projects;
  }.property('channel', 'model'),

  description: function(project){
    var lastRelease = project.lastRelease,
        futureVersion = project.futureVersion,
        value;

    if (this.get('channel') === 'tagged') {
      value = '';
    } else if (lastRelease) {
      value = 'The builds listed below are incremental improvements made since ' + lastRelease + ' and may become ' + futureVersion + '.'
    } else if (futureVersion) {
      value = 'The builds listed below are not based on a tagged release. Upon the next release cycle they will become ' + futureVersion + '.';
    } else {
      value = 'The builds listed below are based on the most recent development.';
    }

    return new Ember.Handlebars.SafeString(value);
  },

  lastReleaseUrl: function(project, channel, lastRelease, extension){
    if (channel === 'canary')
      return 'http://builds.emberjs.com/canary/' + project + extension;
    else
      return 'http://builds.emberjs.com/tags/v' + lastRelease + '/' + project + extension;
  }

});

App.CanaryRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Canary Builds', prefix: 'canary/' });
  }
});

App.CanaryController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'canary'
});

App.BetaRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Beta Builds', prefix: 'beta/'});
  }
});

App.BetaController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'beta'
});

App.ReleaseRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Release Builds', prefix: 'release/'});
  }
});

App.ReleaseController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'release'
});

App.TaggedRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    var bucket = App.S3Bucket.create({
      title: 'Tagged Release Builds',
      prefix: 'tags/',
      delimiter: '',
    });
    return bucket;
  }
});

App.TaggedController = Ember.ObjectController.extend(App.ProjectsMixin, {
  channel: 'tagged'
});
/*
 * Handlebars Helpers
 */
Ember.Handlebars.helper('format-date-time', function(date, format, options) {
  if (!options) {
    options = format;
    format = null;
  }

  if (format){
    return moment(date).format(format);
  } else {
    return moment(date).fromNow();
  }
});
<commit_msg>Add 1.11.0-beta.2 to builds fixtures.<commit_after>//= require_tree ./templates

var App = Ember.Application.create({
  rootElement: '#builds-application'
});

App.Router.map(function() {
  this.route('release');
  this.route('beta');
  this.route('canary');
  this.route('tagged');
});

App.Router.reopen({
  notifyGoogleAnalytics: function() {
    var url = this.get('url');

    // Add a slash if neccesary
    if (!/^\//.test(url)){ url = '/' + url; }

    _gaq.push(['_trackPageview', '/builds' + url]);
  }.on('didTransition')
});

App.CopyClipboardComponent = Ember.Component.extend({
  tagName: 'span',
  hasFlash: ZeroClipboard.detectFlashSupport(),

  didInsertElement: function () {
    var clip = new ZeroClipboard(this.$('button'), {
      // This would normally be a relative path
      moviePath: "/images/ZeroClipboard.swf",

      trustedDomains: ["*"],
      allowScriptAccess: "always"
    });

    clip.on('mousedown', function(client, e) {
      Em.run.later(this, function() {
        $(this).removeClass('loading');
        $(this).removeAttr('disabled');
      }, 1000);
      Em.run.next(this, function() {
        $(this).addClass('loading');
        $(this).attr('disabled', 'disabled');
      });
    });

    this.$('input').on('click', function() {
      $(this).select();
    });
  }
});

App.S3Bucket = Ember.Object.extend({
  files: [],
  isLoading: false,

  // Setup these as default values.
  // They can be overridden on create.
  queryUseSSL: true,
  objectUseSSL: false,
  delimiter: '/',
  bucket: 'builds.emberjs.com',
  endpoint: 's3.amazonaws.com',

  delimiterParameter: function(){
    var delimiter = this.getWithDefault('delimiter','').toString();
    return (delimiter) ? 'delimiter=' + delimiter : '';
  }.property('delimiter'),

  markerParameter: function(){
    return 'marker=' + this.getWithDefault('marker','').toString();
  }.property('marker'),

  maxKeysParameter: function(){
    return 'max-keys=' + this.getWithDefault('maxKeys','').toString();
  }.property('maxKeys'),

  prefixParameter: function(){
    return 'prefix=' + this.getWithDefault('prefix','').toString();
  }.property('prefix'),

  queryProtocol: function() {
    return this.get('queryUseSSL') ? 'https://' : 'http://';
  }.property('queryUseSSL'),

  queryBaseUrl: function(){
    return this.get('queryProtocol') + this.get('endpoint') + '/' + this.get('bucket')
  }.property('queryProtocol', 'endpoint', 'bucket'),

  objectProtocol: function() {
    return this.get('objectUseSSL') ? 'https://' : 'http://';
  }.property('objectUseSSL'),

  objectBaseUrl: function(){
    return this.get('objectProtocol') + this.get('bucket');
  }.property('objectProtocol', 'bucket'),

  queryParams: function(){
    return this.get('delimiterParameter')  + '&' +
      this.get('markerParameter')     + '&' +
      this.get('maxKeysParameter')    + '&' +
      this.get('prefixParameter');
  }.property('delimiterParameter','markerParameter','maxKeysParameter','prefixParameter'),

  queryUrl: function(){
    return this.get('queryBaseUrl') + '?' + this.get('queryParams');
  }.property('queryBaseUrl','queryParams'),

  filesPresent: function(){
    return this.get('files').length;
  }.property('files.@each'),

  filterFiles: function(filter, ignoreFiles){
    var files = this.get('files');
    var ignoreFiles = Ember.A(ignoreFiles);

    return files.filter(function(e) {
      var name = e.get('name');
      var ignored = ignoreFiles.any(function(f) { return name.indexOf(f) >= 0; });
      var selected = name.indexOf(filter + '.') >= 0;

      return !ignored && selected;
    });
  },

  load: function(){
    var self = this,
    baseUrl = this.get('objectBaseUrl');

    this.set('isLoading', true);
    Ember.$.get(this.get('queryUrl'), function(data){
      self.set('isLoading', false);
      self.set('response', data);

      var contents = data.getElementsByTagName('Contents'),
      length   = contents.length,
      files    = [];

      for(var i = 0; i < length; i++) {
        var size = contents[i].getElementsByTagName('Size')[0].firstChild.data,
        name = contents[i].getElementsByTagName('Key')[0].firstChild.data,
        lastModified = new Date(contents[i].getElementsByTagName('LastModified')[0].firstChild.data);

        files.push(
          App.S3File.create({
          name: name,
          size: size,
          lastModified: lastModified,
          relativePath: name,
          baseUrl: baseUrl
        })
        );
      }

      self.set('files', files.sort(function(a,b){
        return b.lastModified - a.lastModified;
      }));
    });
  }.observes('queryUrl').on('init')
});

App.S3File = Ember.Object.extend({
  scriptTag: function(){
    var escapedURL = Ember.Handlebars.Utils.escapeExpression(this.get('url'));

    return new Ember.Handlebars.SafeString('<script src="' + escapedURL + '"></script>').toString();
  }.property('url'),

  url: function(){
    return this.get('baseUrl') + '/' + this.get('relativePath');
  }.property('baseUrl', 'relativePath')
});

App.Project = Ember.Object.extend();

App.Project.reopenClass({
  FIXTURES:
    [ {
      projectName: 'Ember',
      projectFilter: 'ember',
      projectRepo: 'emberjs/ember.js',
      channel: "tagged"
    }, {
      projectName: 'Ember Data',
      projectFilter: 'ember-data',
      projectRepo: 'emberjs/data',
      channel: "tagged"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      initialVersion: "1.10.0",
      initialReleaseDate: "2015-02-07",
      lastRelease: "1.10.0",
      futureVersion: "1.10.1",
      channel: "release",
      date: "2015-02-07",
      changelogPath: "CHANGELOG.md",
      enableTestURL: true,
      debugFileName: ".debug.js"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      lastRelease: "1.11.0-beta.2",
      futureVersion: "1.11.0-beta.3",
      finalVersion: '1.11.0',
      channel: "beta",
      cycleEstimatedFinishDate: '2015-03-20',
      date: "2015-02-15",
      nextDate: "2015-02-21",
      changelogPath: "CHANGELOG.md",
      enableTestURL: true,
      debugFileName: ".debug.js",
      ignoreFiles: ['ember.js']
    }, {
      projectName: "Ember Data",
      projectFilter: "ember-data",
      projectRepo: 'emberjs/data',
      lastRelease: "1.0.0-beta.14.1",
      futureVersion: "1.0.0-beta.15",
      channel: "beta",
      date: "2014-12-31",
      changelogPath: "CHANGELOG.md",
      debugFileName: ".js"
    }, {
      projectName: "Ember",
      projectFilter: "ember",
      projectRepo: 'emberjs/ember.js',
      channel: "canary",
      enableTestURL: true,
      debugFileName: ".debug.js",
      ignoreFiles: ['ember.js']
    }, {
      projectName: "Ember Data",
      projectFilter: "ember-data",
      projectRepo: 'emberjs/data',
      channel: "canary",
      debugFileName: ".js"
    }],

  all: function(channel){
    var projects;

    if (channel)
      projects = this.FIXTURES.filterBy('channel', channel);
    else
      projects = this.FIXTURES;

    return projects.map(function(obj) {
      return App.Project.create(obj);
    });
  },

  find: function(channel, name) {
    var allProjects = this.all(channel);

    if (!name)
      return allProjects;
    else
      return allProjects.filterBy('projectName', name);
  }
});

App.BuildCategoryMixin = Ember.Mixin.create({
  renderTemplate: function() {
    this.render('build-list');
  }
});

App.ApplicationController = Ember.ObjectController.extend({
  isIndexActive: function(){
    return this.isActiveChannel('index');
  }.property('currentRouteName'),

  isTaggedActive: function(){
    return this.isActiveChannel('tagged');
  }.property('currentRouteName'),

  isChannelsActive: function(){
    var self = this;
    return !['index','tagged'].some(function(name){ return name === self.get('currentRouteName'); })
  }.property('currentRouteName'),

  isReleaseActive: function(){
    return this.isActiveChannel('release');
  }.property('currentRouteName'),

  isBetaActive: function(){
    return this.isActiveChannel('beta');
  }.property('currentRouteName'),

  isCanaryActive: function(){
    return this.isActiveChannel('canary');
  }.property('currentRouteName'),

  isActiveChannel: function(channel){
    return this.get('currentRouteName').indexOf(channel) !== -1;
  }
});

App.ProjectsMixin = Ember.Mixin.create({
  projects: function(){
    var projects = App.Project.find(this.get('channel')),
        bucket   = this.get('model'),
        self = this;

    projects.forEach(function(project){
      if (project.channel === 'beta'){
        project.isEmberBeta = project.projectName === 'Ember';

        [1,2,3,4,5].forEach(function(increment){
          var versionParts = project.lastRelease.split('.');
          var currentBetaNumber = parseInt(versionParts[versionParts.length - 1], 10);
          project['beta' + increment + 'Completed'] = increment <= currentBetaNumber;
          project['isBeta' + increment] = increment === currentBetaNumber;
        });

        var release = App.Project.find('release', project.projectName)[0];

        // no releases exist for ember-data (yet)
        if (release) {
          project.lastStableVersion = release.initialVersion;
          project.lastStableDate = release.initialReleaseDate;
        }
      }

      project.files = bucket.filterFiles(project.projectFilter, project.ignoreFiles);
      project.description = self.description(project);
      project.lastReleaseDebugUrl = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, project.debugFileName);
      project.lastReleaseProdUrl  = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '.prod.js');
      project.lastReleaseMinUrl   = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '.min.js');

      if (project.enableTestURL) {
        project.lastReleaseTestUrl  = self.lastReleaseUrl(project.projectFilter, project.channel, project.lastRelease, '-tests-index.html');
      }

      if (project.channel === 'canary') {
        project.lastRelease = 'latest';
      } else if (project.changelog !== 'false') {
        project.lastReleaseChangelogUrl   = 'https://github.com/' + project.projectRepo + '/blob/v' + project.lastRelease + '/' + project.changelogPath;
      }
    });

    return projects;
  }.property('channel', 'model'),

  description: function(project){
    var lastRelease = project.lastRelease,
        futureVersion = project.futureVersion,
        value;

    if (this.get('channel') === 'tagged') {
      value = '';
    } else if (lastRelease) {
      value = 'The builds listed below are incremental improvements made since ' + lastRelease + ' and may become ' + futureVersion + '.'
    } else if (futureVersion) {
      value = 'The builds listed below are not based on a tagged release. Upon the next release cycle they will become ' + futureVersion + '.';
    } else {
      value = 'The builds listed below are based on the most recent development.';
    }

    return new Ember.Handlebars.SafeString(value);
  },

  lastReleaseUrl: function(project, channel, lastRelease, extension){
    if (channel === 'canary')
      return 'http://builds.emberjs.com/canary/' + project + extension;
    else
      return 'http://builds.emberjs.com/tags/v' + lastRelease + '/' + project + extension;
  }

});

App.CanaryRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Canary Builds', prefix: 'canary/' });
  }
});

App.CanaryController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'canary'
});

App.BetaRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Beta Builds', prefix: 'beta/'});
  }
});

App.BetaController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'beta'
});

App.ReleaseRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    return App.S3Bucket.create({title: 'Release Builds', prefix: 'release/'});
  }
});

App.ReleaseController = Ember.ObjectController.extend(App.ProjectsMixin, {
  templateName: 'buildList',
  channel: 'release'
});

App.TaggedRoute = Ember.Route.extend(App.BuildCategoryMixin, {
  model: function() {
    var bucket = App.S3Bucket.create({
      title: 'Tagged Release Builds',
      prefix: 'tags/',
      delimiter: '',
    });
    return bucket;
  }
});

App.TaggedController = Ember.ObjectController.extend(App.ProjectsMixin, {
  channel: 'tagged'
});
/*
 * Handlebars Helpers
 */
Ember.Handlebars.helper('format-date-time', function(date, format, options) {
  if (!options) {
    options = format;
    format = null;
  }

  if (format){
    return moment(date).format(format);
  } else {
    return moment(date).fromNow();
  }
});
<|endoftext|>


<commit_before>'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:SettingCtrl
 * @description
 * # SettingCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
.controller('RoleCtrl', function($scope, $cookies, Helper, Options) {
    var appConfig = JSON.parse($cookies.get('appConfig'));

    $scope.optionTypes = [
        {text: 'text', value: 'text' },
        {text: 'checkbox', value: 'checkbox' },
        {text: 'textarea', value: 'textarea' },
        {text: 'select', value: 'select' },
    ];
    $scope.roles = Helper.getOptionValueByKey('roles', appConfig);
    $scope.roles.optionValue = JSON.parse($scope.roles.optionValue);

    // Starting to delete a field
    $scope.startDelete = function(key){
        $scope.deleteKey = key;
    };

    // update a capacity
    $scope.updateRole = function(){
        var optionData = {
            id: $scope.roles.id,
            optionKey: 'roles',
            optionValue: $scope.roles.optionValue
        };
        Options.update(optionData).then(function(data){
            console.log(data);
        });
    };

    // delete a role
    $scope.deleteRole = function(key){
        $scope.roles.optionValue.splice(key, 1);
        $scope.updateRole();
    };

    // add a new role
    $scope.addRole = function(){
        var optionValue = {
            name: null,
            label: null,
            description: null
        };
        $scope.roles.optionValue.push(optionValue);
    };

    $scope.capacities = Helper.getOptionValueByKey('capacities', appConfig);
    $scope.capacities.optionValue = JSON.parse($scope.capacities.optionValue);

    // update a capacity
    $scope.updateCapacity = function(){
        var optionData = {
            id: $scope.capacities.id,
            optionKey: 'capacities',
            optionValue: $scope.capacities.optionValue
        };
        Options.update(optionData).then(function(data){
            console.log(data);
        });
    };

    // delete a capacities
    $scope.deleteCapacity = function(key){
        $scope.capacities.optionValue.splice(key, 1);
        $scope.updateCapacity();
    };

    // add a new capacity
    $scope.addCapacity = function(){
        var optionValue = {
            name: null,
            description: null
        };
        $scope.capacities.optionValue.push(optionValue);
    };

    $scope.forUnitTest = true;
})
.controller('ViewRoleCtrl', function($scope, $stateParams, $cookies, Helper, Options) {
    var appConfig = JSON.parse($cookies.get('appConfig'));
    $scope.roleId = $stateParams.id;
    $scope.capacities = Helper.getOptionValueByKey('capacities', appConfig);
    $scope.capacities.optionValue = JSON.parse($scope.capacities.optionValue);
    $scope.caps = [];

    var role = Helper.getOptionValueByKey('role_' + $scope.roleId, appConfig);
    $scope.caps = JSON.parse(role.optionValue);

    $scope.addCapacity = function() {
        $scope.caps.push($scope.capacityData.name);
        var data = {
            optionKey: 'role_' + $scope.roleId,
            optionValue: JSON.stringify($scope.caps)
        };
        Options.create(data).then(function(res){
            console.log(res);
        });
    }
    $scope.deleteCapacity = function(k) {
        $scope.caps.splice(k, 1);
        var data = {
            optionKey: 'role_' + $scope.roleId,
            optionValue: JSON.stringify($scope.caps)
        };
        Options.update(data).then(function(res){
            console.log(res);
        });
    }

    $scope.forUnitTest = true;
});
<commit_msg>check null<commit_after>'use strict';
/**
 * @ngdoc function
 * @name sbAdminApp.controller:SettingCtrl
 * @description
 * # SettingCtrl
 * Controller of the sbAdminApp
 */
angular.module('sbAdminApp')
.controller('RoleCtrl', function($scope, $cookies, Helper, Options) {
    var appConfig = JSON.parse($cookies.get('appConfig'));

    $scope.optionTypes = [
        {text: 'text', value: 'text' },
        {text: 'checkbox', value: 'checkbox' },
        {text: 'textarea', value: 'textarea' },
        {text: 'select', value: 'select' },
    ];
    $scope.roles = Helper.getOptionValueByKey('roles', appConfig);
    $scope.roles.optionValue = JSON.parse($scope.roles.optionValue);

    // Starting to delete a field
    $scope.startDelete = function(key){
        $scope.deleteKey = key;
    };

    // update a capacity
    $scope.updateRole = function(){
        var optionData = {
            id: $scope.roles.id,
            optionKey: 'roles',
            optionValue: $scope.roles.optionValue
        };
        Options.update(optionData).then(function(data){
            console.log(data);
        });
    };

    // delete a role
    $scope.deleteRole = function(key){
        $scope.roles.optionValue.splice(key, 1);
        $scope.updateRole();
    };

    // add a new role
    $scope.addRole = function(){
        var optionValue = {
            name: null,
            label: null,
            description: null
        };
        $scope.roles.optionValue.push(optionValue);
    };

    $scope.capacities = Helper.getOptionValueByKey('capacities', appConfig);
    $scope.capacities.optionValue = JSON.parse($scope.capacities.optionValue);

    // update a capacity
    $scope.updateCapacity = function(){
        var optionData = {
            id: $scope.capacities.id,
            optionKey: 'capacities',
            optionValue: $scope.capacities.optionValue
        };
        Options.update(optionData).then(function(data){
            console.log(data);
        });
    };

    // delete a capacities
    $scope.deleteCapacity = function(key){
        $scope.capacities.optionValue.splice(key, 1);
        $scope.updateCapacity();
    };

    // add a new capacity
    $scope.addCapacity = function(){
        var optionValue = {
            name: null,
            description: null
        };
        $scope.capacities.optionValue.push(optionValue);
    };

    $scope.forUnitTest = true;
})
.controller('ViewRoleCtrl', function($scope, $stateParams, $cookies, Helper, Options) {
    var appConfig = JSON.parse($cookies.get('appConfig'));
    $scope.roleId = $stateParams.id;
    $scope.capacities = Helper.getOptionValueByKey('capacities', appConfig);
    $scope.capacities.optionValue = JSON.parse($scope.capacities.optionValue);
    $scope.caps = [];

    var role = Helper.getOptionValueByKey('role_' + $scope.roleId, appConfig);
    if (role !== undefined) {
        $scope.caps = JSON.parse(role.optionValue);
    }

    $scope.addCapacity = function() {
        console.log($scope.capacityData);
        $scope.caps.push($scope.capacityData.name);
        var data = {
            optionKey: 'role_' + $scope.roleId,
            optionValue: JSON.stringify($scope.caps)
        };
        Options.create(data).then(function(res){
            console.log(res);
        });
    }
    $scope.deleteCapacity = function(k) {
        $scope.caps.splice(k, 1);
        var data = {
            optionKey: 'role_' + $scope.roleId,
            optionValue: JSON.stringify($scope.caps)
        };
        Options.update(data).then(function(res){
            console.log(res);
        });
    }

    $scope.forUnitTest = true;
});
<|endoftext|>


<commit_before>// Tutorial: http://tagtree.tv/gulp
// Best practices: http://blog.rangle.io/angular-gulp-bestpractices/
// Recipes: https://github.com/gulpjs/gulp/tree/master/docs/recipes
/* TODO:
 controlling CORS?
 middleware for proxy, CORS, connect.json, and connect.urlencoded
 setting up reading package.json
 copying viewer to dist/viewer
 autoprefixer
 cssmin
 setting up backend (production server and proxy)
*/
var gulp = require('gulp');
var gutil = require('gulp-util');
var rename = require('gulp-rename');

var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');

var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');

var connect = require('gulp-connect');
var realConnect = require('connect');
//var Proxy = require('gulp-connect-proxy');
var proxypage = require('proxypage');
var bodyParser = require('body-parser');

// var source = require('vinyl-source-stream');
// var browserify = require('gulp-browserify');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');

var config = {
  srcCss : 'viewer/css/**/*.css',
  distCss : 'dist/viewer/css',
  srcHtml : 'viewer/*.html',
  distHtml : 'dist/viewer',
  srcJs : 'viewer/js/**/*.js',
  distJs : 'dist/viewer/js/'
};

// Copies html, builds javascript and css, runs jshint, watches for changes and runs a web server and opens default browser to preview.
// TODO: Separate file copying for development and production
gulp.task('default', ['copy-html', 'copy-js', 'watch', 'jshint', 'build-js', 'build-css', 'proxy'], function() {
  // launch web server
  connect.server({
    port: 3000,
    root: 'viewer',
    livereload: true
  });
});

gulp.task('proxy', function () {
  var app = realConnect();
  var port = 3002;
  app.use(bodyParser.text({ type: 'text/html' }));
  app.use(bodyParser.json({ type: 'application/*+json' }));

  app.use('/proxy', proxypage.proxy);

  app.listen(port, function() {
    console.log('Connect server listening on port ' + port);
  });
});

gulp.task('copy-html', function () {
  // copy any html files in viewer to dist/viewer
  gulp.src(config.srcHtml)
    .pipe(gulp.dest(config.distHtml));
});

gulp.task('copy-js', function () {
  //copy any javascript files in viewer to dist/viewer
  gulp.src(config.srcJs)
    .pipe(gulp.dest(config.distJs));
});

gulp.task('build-css', function () {
  gulp.src(config.srcCss)
    .pipe(autoprefixer())
    // output non-minified CSS file
    .pipe(gulp.dest(config.distCss))
    // output minified CSS file
    .pipe(gutil.env.type == 'production' ? minifyCss() : gutil.noop())
    .pipe(gutil.env.type == 'production' ? rename({ extname: '.min.css' }) : gutil.noop())
    .pipe(gutil.env.type == 'production' ? gulp.dest(config.distCss) : gutil.noop());
});

gulp.task('watch', function() {
  // do we need to be this specific?
  gulp.watch(config.srcJs, ['jshint', 'build-js']);
  gulp.watch(config.srcCss, ['build-css']);
  gulp.watch(config.srcHtml, ['copy-html']);
});

gulp.task('jshint', function() {
  return gulp.src(config.srcJs)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('build-js', function() {
  return gulp.src(config.srcJs)
    .pipe(sourcemaps.init())
    .pipe(concat('bundle.js'))
    // only uglify if gulp is run with '--type production'
    .pipe(gutil.env.type == 'production' ? uglify() : gutil.noop())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(config.distJs));
});

 // 'test': 'Tests the project'
gulp.task('mocha', function() {
  return gulp.src(['test/*.js'], { read: false })
    .pipe(mocha({ reporter: 'list' }))
    .on('error', gutil.log);
});

gulp.task('watch-mocha', function() {
  gulp.watch(['lib/**', 'test/**'], ['mocha']);
});

// 'build': 'Compiles all of the assets and copies the files to the build directory.', ['clean', 'copy', 'scripts', 'stylesheets', 'compress:build']

// 'build-view': 'Compiles all of the assets and copies the files to the build directory starts a web server and opens browser to preview app.', ['clean', 'copy', 'scripts', 'stylesheets', 'compress:build', 'connect:build', 'open:build_browser', 'watch:build']

// 'scripts': 'Compiles the JavaScript files.', ['jshint', 'uglify']
gulp.task('js', function() {
  browserify('./viewer/js/**/*.js')
    .bundle()
    .on('error', function(error) {
      gutil.log(error);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./viewer/js/dist'))
});

// 'stylesheets': 'Auto prefixes css and compiles the stylesheets.', ['autoprefixer', 'cssmin']

// 'jshint': 'Run simple jshint.', ['jshint']
<commit_msg>Clean up gulpfile.js<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var rename = require('gulp-rename');

var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');

var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');

var gulpConnect = require('gulp-connect');
var connect = require('connect');
var proxypage = require('proxypage');
var bodyParser = require('body-parser');

// var source = require('vinyl-source-stream');
// var browserify = require('gulp-browserify');
var uglify = require('gulp-uglify');
var mocha = require('gulp-mocha');

var config = {
  srcCss : 'viewer/css/**/*.css',
  distCss : 'dist/viewer/css',
  srcHtml : 'viewer/*.html',
  distHtml : 'dist/viewer',
  srcJs : 'viewer/js/**/*.js',
  distJs : 'dist/viewer/js/'
};

// Copies html, builds javascript and css, runs jshint, watches for changes and runs a web server and opens default browser to preview.
gulp.task('default', ['copy-html',
                      'copy-js',
                      'watch',
                      'jshint',
                      'build-js',
                      'build-css',
                      'proxy'], function() {
  // launch web server
  gulpConnect.server({
    port: 3000,
    root: 'viewer',
    livereload: true
  });
});

gulp.task('proxy', function () {
  var proxy = connect();
  var port = 3002;
  proxy.use(bodyParser.text({ type: 'text/html' }));
  proxy.use(bodyParser.json({ type: 'application/*+json' }));

  proxy.use('/proxy', proxypage.proxy);

  proxy.listen(port, function() {
    console.log('Connect server listening on port ' + port);
  });
});

gulp.task('copy-html', function () {
  gulp.src(config.srcHtml)
    .pipe(gulp.dest(config.distHtml));
});

gulp.task('copy-js', function () {
  gulp.src(config.srcJs)
    .pipe(gulp.dest(config.distJs));
});

gulp.task('build-css', function () {
  gulp.src(config.srcCss)
    .pipe(autoprefixer())
    // output non-minified CSS file
    .pipe(gulp.dest(config.distCss))
    // output minified CSS file
    .pipe(gutil.env.type == 'production' ? minifyCss() : gutil.noop())
    .pipe(gutil.env.type == 'production' ? rename({ extname: '.min.css' }) : gutil.noop())
    .pipe(gutil.env.type == 'production' ? gulp.dest(config.distCss) : gutil.noop());
});

gulp.task('watch', function() {
  gulp.watch(config.srcJs, ['jshint', 'build-js']);
  gulp.watch(config.srcCss, ['build-css']);
  gulp.watch(config.srcHtml, ['copy-html']);
});

gulp.task('jshint', function() {
  return gulp.src(config.srcJs)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('build-js', function() {
  return gulp.src(config.srcJs)
    .pipe(sourcemaps.init())
    .pipe(concat('bundle.js'))
    // only uglify if gulp is run with '--type production'
    .pipe(gutil.env.type == 'production' ? uglify() : gutil.noop())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(config.distJs));
});

gulp.task('mocha', function() {
  return gulp.src(['test/*.js'], { read: false })
    .pipe(mocha({ reporter: 'list' }))
    .on('error', gutil.log);
});

gulp.task('watch-mocha', function() {
  gulp.watch(['lib/**', 'test/**'], ['mocha']);
});

// bundles javascript for browserify -not currently used
gulp.task('bundle-js', function() {
  browserify('./viewer/js/**/*.js')
    .bundle()
    .on('error', function(error) {
      gutil.log(error);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./viewer/js/dist'))
});
<|endoftext|>