<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
/*jslint nomen:true, vars:true, regexp:true*/
/*global window, console, define, brackets, $, PathUtils*/

define(function (require, exports, module) {
    "use strict";

    // Load commonly used modules from Brackets
    var _                   = brackets.getModule("thirdparty/lodash"),
        CodeInspection      = brackets.getModule("language/CodeInspection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        FileSystem          = brackets.getModule("filesystem/FileSystem"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager"),
        NodeDomain          = brackets.getModule("utils/NodeDomain");

    // Boilerplate to load NodeDomain
    var _domainPath = ExtensionUtils.getModulePath(module, "node/SASSDomain"),
        _nodeDomain = new NodeDomain("sass", _domainPath);

    var RE_FILE_EXT     = /\.(sass|scss)$/,
        PREF_ENABLED    = "enabled",
        PREF_OPTIONS    = "options";

    var extensionPrefs = PreferencesManager.getExtensionPrefs("sass"),
        scannedFileMap = {},
        partialErrorMap = {};

    function _fixSourceMapText(mapText, prefs) {
        var json = JSON.parse(mapText),
            inputFile = prefs.inputFile,
            cssFilePath = prefs.outputCSSFile.fullPath,
            sourceMapFilePath = prefs.outputSourceMapFile.fullPath;

        // Output CSS file should be relative to the source map
        json.file = PathUtils.makePathRelative(cssFilePath, sourceMapFilePath);

        // For some reason, sources are output relative to the CWD
        // Add a sourceRoot to fix
        json.sourceRoot = PathUtils.makePathRelative(inputFile.parentPath, sourceMapFilePath);

        // TODO read tab/space preference?
        return JSON.stringify(json, null, "  ");
    }

    function _makeSourceMapRelativeToOutput(prefs) {
        var sourceMapPath = prefs.outputSourceMapFile.fullPath,
            cssFilePath = prefs.outputCSSFile.fullPath;

        // sourceMap should be relative to the output file
        // This is only used when generating sourceMappingURL
        return PathUtils.makePathRelative(sourceMapPath, cssFilePath);
    }

    function _render(path, prefs) {
        var deferred = new $.Deferred(),
            options = prefs.options,
            sourceMap = _makeSourceMapRelativeToOutput(prefs);

        var renderPromise = _nodeDomain.exec("render",
                 path,
                 options.includePaths,
                 options.imagePath,
                 options.outputStyle,
                 options.sourceComments,
                 sourceMap);

        renderPromise.then(function (response) {
            deferred.resolve(response.css, _fixSourceMapText(response.map, prefs));
        }, deferred.reject);

        return deferred.promise();
    }

    function _getPreferencesForFile(file) {
        var prefs = extensionPrefs,
            enabled = prefs.get(PREF_ENABLED, file.fullPath),
            options = prefs.get(PREF_OPTIONS, file.fullPath),
            outputName = (options && options.output) || file.name.replace(RE_FILE_EXT, ".css"),
            outputDir = (options && options.outputDir),
            parentPath = file.parentPath,
            outputFile;

        if (outputDir) {
            if (outputDir.charAt(outputDir.length - 1) !== "/") {
                outputDir = outputDir + "/";
            }

            if (FileSystem.isAbsolutePath(outputDir)) {
                parentPath = outputDir;
            } else {
                parentPath = FileSystem.getDirectoryForPath(parentPath + outputDir).fullPath;
            }
        }

        outputFile = FileSystem.getFileForPath(parentPath + outputName);

        options = _.defaults(options || {}, {
            outputStyle: "nested",
            sourceComments: "map",
            sourceMap: outputFile.name + ".map"
        });

        // Initialize sourceMap with full path
        options.sourceMap = outputFile.parentPath + options.sourceMap;

        return {
            enabled: enabled,
            options: options,
            inputFile: file,
            outputCSSFile: outputFile,
            outputSourceMapFile: FileSystem.getFileForPath(options.sourceMap)
        };
    }

    function _deferredForScannedPath(path, doAbort) {
        var deferred = scannedFileMap[path];

        if (deferred && doAbort) {
            // Abort current scan
            deferred.resolve({
                errors: [],
                aborted: true
            });

            deferred = null;
        }

        if (!deferred) {
            deferred = new $.Deferred();
            scannedFileMap[path] = deferred;
        }

        return deferred;
    }

    function getErrors(path) {
        return _deferredForScannedPath(path, true).promise();
    }

    function _getInMemoryFiles(docs) {
        var map = {};

        _.each(docs, function (doc) {
            map[doc.file.fullPath] = doc.getText();
        });

        return map;
    }

    function _finishScan(file, errors) {
        var path = file.fullPath,
            sassFileExtension = FileUtils.getFileExtension(path),
            scanDeferred = _deferredForScannedPath(path);

        // Clear cached errors
        partialErrorMap = {};

        var result = {
            errors: [],
            aborted: false
        };

        errors = errors || [];
        errors = Array.isArray(errors) ? errors : [errors];

        _.each(errors, function (err) {
            // Can't report errors on files other than the current document, see CodeInspection
            if (path !== err.path) {
                // Clone error
                var clonedError = _.clone(err);
                clonedError.pos = _.clone(err.pos);

                // FIXME determine when to add underscore prefix to partials
                // HACK libsass errors on partials don't include the file extension!
                clonedError.path += sassFileExtension;

                partialErrorMap[clonedError.path] = partialErrorMap[clonedError.path] || [];
                partialErrorMap[clonedError.path].push(clonedError);

                // Omit position if the file path doesn't match
                err.pos.line = undefined;

                // HACK Add path to error message
                err.message = err.path + " - " + err.message;
            }

            err.type = CodeInspection.Type.ERROR;
            result.errors.push(err);
        });

        scanDeferred.resolve(result);

        // Resolve promises for partials
        _.each(partialErrorMap, function (partialErrors, partialPath) {
            _deferredForScannedPath(partialPath).resolve({
                errors: partialErrors,
                aborted: false
            });
        });
    }

    function _mkdirp(path) {
        return _nodeDomain.exec("mkdirp", path);
    }

    function compile(sassFile) {
        var prefs = _getPreferencesForFile(sassFile);

        if (!prefs.enabled) {
            return new $.Deferred().reject().promise();
        }

        var cssFile = prefs.outputCSSFile,
            options = prefs.options,
            hasSourceMap = options.sourceComments === "map",
            mapFile = prefs.outputSourceMapFile,
            renderPromise;

        renderPromise = _render(sassFile.fullPath, prefs);

        return renderPromise.then(function (css, map) {
            var eventData = {
                    css: {
                        file: cssFile,
                        contents: css
                    }
                };

            _mkdirp(cssFile.parentPath).done(function () {
                FileUtils.writeText(cssFile, css, true);
            });

            if (map) {
                _mkdirp(mapFile.parentPath).done(function () {
                    // TODO relative paths in sourceMap?
                    FileUtils.writeText(mapFile, map, true);

                    eventData.sourceMap = {
                        file: mapFile,
                        contents: map
                    };
                });
            }

            _finishScan(sassFile);
        }, function (errors) {
            _finishScan(sassFile, errors);
        });
    }

    function preview(sassFile, docs) {
        var deferred = new $.Deferred(),
            prefs = _getPreferencesForFile(sassFile),
            cssFile = prefs.outputCSSFile,
            mapFile = prefs.outputSourceMapFile,
            sourceMap = _makeSourceMapRelativeToOutput(prefs),
            options = prefs.options,
            previewPromise,
            inMemoryFiles = _getInMemoryFiles(docs);

        $(exports).triggerHandler("sourceMapPreviewStart", [sassFile, cssFile]);

        previewPromise = _nodeDomain.exec("preview",
            sassFile.fullPath,
            inMemoryFiles,
            options.includePaths,
            options.imagePath,
            options.outputStyle,
            "map",
            sourceMap);

        previewPromise.then(function (response) {
            var eventData = {
                css: {
                    file: cssFile,
                    contents: response.css
                },
                sourceMap: {
                    file: mapFile,
                    contents: _fixSourceMapText(response.map, prefs)
                }
            };

            $(exports).triggerHandler("sourceMapPreviewEnd", [sassFile, eventData]);
            _finishScan(sassFile);

            deferred.resolve(response.css, response.map);
        }, function (errors) {
            $(exports).triggerHandler("sourceMapPreviewError", [sassFile, cssFile, errors]);
            _finishScan(sassFile, errors);

            deferred.reject(errors);
        });

        return deferred.promise();
    }

    function deleteTempFiles() {
        return _nodeDomain.exec("deleteTempFiles");
    }

    function _prefChangeHandler(event) {
        // TODO compile all files?
        // _compileWithPreferences();
    }

    // Register preferences
    extensionPrefs.definePreference(PREF_ENABLED, "boolean", true)
        .on("change", _prefChangeHandler);

    extensionPrefs.definePreference(PREF_OPTIONS, "object")
        .on("change", _prefChangeHandler);

    // Public API
    exports.compile = compile;
    exports.preview = preview;
    exports.deleteTempFiles = deleteTempFiles;
    exports.getErrors = getErrors;
});<commit_msg>change SASSDomain node path<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
/*jslint nomen:true, vars:true, regexp:true*/
/*global window, console, define, brackets, $, PathUtils*/

define(function (require, exports, module) {
    "use strict";

    // Load commonly used modules from Brackets
    var _                   = brackets.getModule("thirdparty/lodash"),
        CodeInspection      = brackets.getModule("language/CodeInspection"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        FileSystem          = brackets.getModule("filesystem/FileSystem"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager"),
        NodeDomain          = brackets.getModule("utils/NodeDomain");

    // Boilerplate to load NodeDomain
    var _domainPath = ExtensionUtils.getModulePath(module, "node/1.1.4/SASSDomain"),
        _nodeDomain = new NodeDomain("sass", _domainPath);

    var RE_FILE_EXT     = /\.(sass|scss)$/,
        PREF_ENABLED    = "enabled",
        PREF_OPTIONS    = "options";

    var extensionPrefs = PreferencesManager.getExtensionPrefs("sass"),
        scannedFileMap = {},
        partialErrorMap = {};

    function _fixSourceMapText(mapText, prefs) {
        var json = JSON.parse(mapText),
            inputFile = prefs.inputFile,
            cssFilePath = prefs.outputCSSFile.fullPath,
            sourceMapFilePath = prefs.outputSourceMapFile.fullPath;

        // Output CSS file should be relative to the source map
        json.file = PathUtils.makePathRelative(cssFilePath, sourceMapFilePath);

        // For some reason, sources are output relative to the CWD
        // Add a sourceRoot to fix
        json.sourceRoot = PathUtils.makePathRelative(inputFile.parentPath, sourceMapFilePath);

        // TODO read tab/space preference?
        return JSON.stringify(json, null, "  ");
    }

    function _makeSourceMapRelativeToOutput(prefs) {
        var sourceMapPath = prefs.outputSourceMapFile.fullPath,
            cssFilePath = prefs.outputCSSFile.fullPath;

        // sourceMap should be relative to the output file
        // This is only used when generating sourceMappingURL
        return PathUtils.makePathRelative(sourceMapPath, cssFilePath);
    }

    function _render(path, prefs) {
        var deferred = new $.Deferred(),
            options = prefs.options,
            sourceMap = _makeSourceMapRelativeToOutput(prefs);

        var renderPromise = _nodeDomain.exec("render",
                 path,
                 options.includePaths,
                 options.imagePath,
                 options.outputStyle,
                 options.sourceComments,
                 sourceMap);

        renderPromise.then(function (response) {
            deferred.resolve(response.css, _fixSourceMapText(response.map, prefs));
        }, deferred.reject);

        return deferred.promise();
    }

    function _getPreferencesForFile(file) {
        var prefs = extensionPrefs,
            enabled = prefs.get(PREF_ENABLED, file.fullPath),
            options = prefs.get(PREF_OPTIONS, file.fullPath),
            outputName = (options && options.output) || file.name.replace(RE_FILE_EXT, ".css"),
            outputDir = (options && options.outputDir),
            parentPath = file.parentPath,
            outputFile;

        if (outputDir) {
            if (outputDir.charAt(outputDir.length - 1) !== "/") {
                outputDir = outputDir + "/";
            }

            if (FileSystem.isAbsolutePath(outputDir)) {
                parentPath = outputDir;
            } else {
                parentPath = FileSystem.getDirectoryForPath(parentPath + outputDir).fullPath;
            }
        }

        outputFile = FileSystem.getFileForPath(parentPath + outputName);

        options = _.defaults(options || {}, {
            outputStyle: "nested",
            sourceComments: "map",
            sourceMap: outputFile.name + ".map"
        });

        // Initialize sourceMap with full path
        options.sourceMap = outputFile.parentPath + options.sourceMap;

        return {
            enabled: enabled,
            options: options,
            inputFile: file,
            outputCSSFile: outputFile,
            outputSourceMapFile: FileSystem.getFileForPath(options.sourceMap)
        };
    }

    function _deferredForScannedPath(path, doAbort) {
        var deferred = scannedFileMap[path];

        if (deferred && doAbort) {
            // Abort current scan
            deferred.resolve({
                errors: [],
                aborted: true
            });

            deferred = null;
        }

        if (!deferred) {
            deferred = new $.Deferred();
            scannedFileMap[path] = deferred;
        }

        return deferred;
    }

    function getErrors(path) {
        return _deferredForScannedPath(path, true).promise();
    }

    function _getInMemoryFiles(docs) {
        var map = {};

        _.each(docs, function (doc) {
            map[doc.file.fullPath] = doc.getText();
        });

        return map;
    }

    function _finishScan(file, errors) {
        var path = file.fullPath,
            sassFileExtension = FileUtils.getFileExtension(path),
            scanDeferred = _deferredForScannedPath(path);

        // Clear cached errors
        partialErrorMap = {};

        var result = {
            errors: [],
            aborted: false
        };

        errors = errors || [];
        errors = Array.isArray(errors) ? errors : [errors];

        _.each(errors, function (err) {
            // Can't report errors on files other than the current document, see CodeInspection
            if (path !== err.path) {
                // Clone error
                var clonedError = _.clone(err);
                clonedError.pos = _.clone(err.pos);

                // FIXME determine when to add underscore prefix to partials
                // HACK libsass errors on partials don't include the file extension!
                clonedError.path += sassFileExtension;

                partialErrorMap[clonedError.path] = partialErrorMap[clonedError.path] || [];
                partialErrorMap[clonedError.path].push(clonedError);

                // Omit position if the file path doesn't match
                err.pos.line = undefined;

                // HACK Add path to error message
                err.message = err.path + " - " + err.message;
            }

            err.type = CodeInspection.Type.ERROR;
            result.errors.push(err);
        });

        scanDeferred.resolve(result);

        // Resolve promises for partials
        _.each(partialErrorMap, function (partialErrors, partialPath) {
            _deferredForScannedPath(partialPath).resolve({
                errors: partialErrors,
                aborted: false
            });
        });
    }

    function _mkdirp(path) {
        return _nodeDomain.exec("mkdirp", path);
    }

    function compile(sassFile) {
        var prefs = _getPreferencesForFile(sassFile);

        if (!prefs.enabled) {
            return new $.Deferred().reject().promise();
        }

        var cssFile = prefs.outputCSSFile,
            options = prefs.options,
            hasSourceMap = options.sourceComments === "map",
            mapFile = prefs.outputSourceMapFile,
            renderPromise;

        renderPromise = _render(sassFile.fullPath, prefs);

        return renderPromise.then(function (css, map) {
            var eventData = {
                    css: {
                        file: cssFile,
                        contents: css
                    }
                };

            _mkdirp(cssFile.parentPath).done(function () {
                FileUtils.writeText(cssFile, css, true);
            });

            if (map) {
                _mkdirp(mapFile.parentPath).done(function () {
                    // TODO relative paths in sourceMap?
                    FileUtils.writeText(mapFile, map, true);

                    eventData.sourceMap = {
                        file: mapFile,
                        contents: map
                    };
                });
            }

            _finishScan(sassFile);
        }, function (errors) {
            _finishScan(sassFile, errors);
        });
    }

    function preview(sassFile, docs) {
        var deferred = new $.Deferred(),
            prefs = _getPreferencesForFile(sassFile),
            cssFile = prefs.outputCSSFile,
            mapFile = prefs.outputSourceMapFile,
            sourceMap = _makeSourceMapRelativeToOutput(prefs),
            options = prefs.options,
            previewPromise,
            inMemoryFiles = _getInMemoryFiles(docs);

        $(exports).triggerHandler("sourceMapPreviewStart", [sassFile, cssFile]);

        previewPromise = _nodeDomain.exec("preview",
            sassFile.fullPath,
            inMemoryFiles,
            options.includePaths,
            options.imagePath,
            options.outputStyle,
            "map",
            sourceMap);

        previewPromise.then(function (response) {
            var eventData = {
                css: {
                    file: cssFile,
                    contents: response.css
                },
                sourceMap: {
                    file: mapFile,
                    contents: _fixSourceMapText(response.map, prefs)
                }
            };

            $(exports).triggerHandler("sourceMapPreviewEnd", [sassFile, eventData]);
            _finishScan(sassFile);

            deferred.resolve(response.css, response.map);
        }, function (errors) {
            $(exports).triggerHandler("sourceMapPreviewError", [sassFile, cssFile, errors]);
            _finishScan(sassFile, errors);

            deferred.reject(errors);
        });

        return deferred.promise();
    }

    function deleteTempFiles() {
        return _nodeDomain.exec("deleteTempFiles");
    }

    function _prefChangeHandler(event) {
        // TODO compile all files?
        // _compileWithPreferences();
    }

    // Register preferences
    extensionPrefs.definePreference(PREF_ENABLED, "boolean", true)
        .on("change", _prefChangeHandler);

    extensionPrefs.definePreference(PREF_OPTIONS, "object")
        .on("change", _prefChangeHandler);

    // Public API
    exports.compile = compile;
    exports.preview = preview;
    exports.deleteTempFiles = deleteTempFiles;
    exports.getErrors = getErrors;
});<|endoftext|>


<commit_before>'use strict';

var assign = require('object-assign'),
	React = require('react'),
	DaysView = require('./src/DaysView'),
	MonthsView = require('./src/MonthsView'),
	YearsView = require('./src/YearsView'),
	TimeView = require('./src/TimeView'),
	moment = require('moment')
;

var TYPES = React.PropTypes;
var Datetime = React.createClass({
	mixins: [
		require('react-onclickoutside')
	],
	viewComponents: {
		days: DaysView,
		months: MonthsView,
		years: YearsView,
		time: TimeView
	},
	propTypes: {
		date: TYPES.object,
		onBlur: TYPES.func,
		onChange: TYPES.func,
		locale: TYPES.string,
		input: TYPES.bool,
		// enableDate: TYPES.string,
		// enableTime: TYPES.string,
		inputProps: TYPES.object,
		viewMode: TYPES.oneOf(['years', 'months', 'days', 'time']),
		minDate: TYPES.object,
		maxDate: TYPES.object
	},
	getDefaultProps: function() {

		return {
			date: new Date(),
			viewMode: 'days',
			inputProps: {},
			input: true,
			enableTime: true,
			enableDate: true,
			onBlur: function () {},
			onChange: function (x) {
				console.log(x);
			}
		};
	},
	getInitialState: function() {
		var formats = this.getFormats( this.props ),
			date = this.props.date,
			currentView = this.props.viewMode
		;

		if( !formats.date )
			currentView = 'time';

		return {
			currentView: currentView,
			open: !this.props.input,
			inputFormat: formats.datetime,
			viewDate: this.localMoment(date).startOf("month"),
			selectedDate: this.localMoment(date),
			inputValue: this.localMoment(date).format( formats.datetime )
		};
	},

	getFormats: function( props ){
		var formats = {
				date: props.enableDate || '',
				time: props.enableTime || ''
			},
			locale = this.localMoment( props.date ).localeData()
		;

		if( formats.date === true ){
			formats.date = locale.longDateFormat('L');
		}
		if( formats.time === true ){
			formats.time = locale.longDateFormat('LT');
		}

		formats.datetime = formats.date + ' ' + formats.time;

		return formats;
	},

	componentWillReceiveProps: function(nextProps) {
		var formats = this.getFormats( nextProps );
		if ( formats.datetime !== this.getFormats(this.props).datetime ) {
			return this.setState({
				inputFormat: nextProps.inputFormat
			});
		}
	},

	onChange: function(event) {
		var value = event.target == null ? event : event.target.value,
			localMoment = this.localMoment( date )
		;

		if (localMoment.isValid()) {
			this.setState({
				selectedDate: localMoment,
				viewDate: localMoment.clone().startOf("month")
			});
		}

		return this.setState({
			inputValue: value
		}, function() {
			return this.props.onChange( localMoment.toDate() );
		});
	},

	showView: function( view ){
		var me = this;
		return function( e ){
			me.setState({ currentView: view });
		};
	},

	setDate: function( type ){
		var me = this,
			nextViews = {
				month: 'days',
				year: 'months'
			}
		;
		return function( e ){
			me.setState({
				viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.dataset.value) ).startOf( type ),
				currentView: nextViews[ type ]
			});
		};
	},

	addTime: function( amount, type, toSelected ){
		return this.updateTime( 'add', amount, type, toSelected );
	},

	subtractTime: function( amount, type, toSelected ){
		return this.updateTime( 'subtract', amount, type, toSelected );
	},

	updateTime: function( op, amount, type, toSelected ){
		var me = this;

		return function(){
			var update = {},
				date = toSelected ? 'selectedDate' : 'viewDate'
			;

			update[ date ] = me.state[ date ].clone()[ op ]( amount, type );

			me.setState( update );
		};
	},

	allowedSetTime: ['hours','minutes','seconds', 'milliseconds'],
	setTime: function( type, value ){
		var index = this.allowedSetTime.indexOf( type ) + 1,
			date = this.state.selectedDate.clone(),
			nextType
		;

		// It is needed to set all the time properties
		// to not to reset the time
		date[ type ]( value );
		for (; index < this.allowedSetTime.length; index++) {
			nextType = this.allowedSetTime[index];
			date[ nextType ]( date[nextType]() );
		}

		this.setState({
			selectedDate: date,
			inputValue: date.format( this.state.inputFormat )
		}, this.callOnChange );
	},

	callOnChange: function(){
		this.props.onChange(this.state.selectedDate.format( this.state.inputFormat ));
	},

	updateDate: function( e ) {
		var target = e.target,
			modifier = 0,
			currentDate = this.state.selectedDate,
			date
		;

		if(target.className.indexOf("new") != -1)
			modifier = 1;
		else if(target.className.indexOf("old") != -1)
			modifier = -1;

		date = this.state.viewDate.clone()
			.month( this.state.viewDate.month() + modifier )
			.date( parseInt( target.dataset.value ) )
			.hours( currentDate.hours() )
			.minutes( currentDate.minutes() )
			.seconds( currentDate.seconds() )
			.milliseconds( currentDate.milliseconds() )
		;

		this.setState({
			selectedDate: date,
			viewDate: date.clone().startOf('month'),
			inputValue: date.format( this.state.inputFormat )
		}, this.callOnChange );
	},

	openCalendar: function() {
		this.setState({ open: true });
	},

	handleClickOutside: function(){
		this.props.onBlur(this.state.inputValue);
		if( this.props.input && this.state.open )
			this.setState({ open: false });
	},

	localMoment: function( date ){
		var m = moment( date );
		if( this.props.locale )
			m.locale( this.props.locale );
		return m;
	},

	componentProps: {
		fromProps: ['viewMode', 'minDate', 'maxDate', 'renderDay', 'renderMonth', 'renderYear'],
		fromState: ['viewDate', 'selectedDate' ],
		fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateDate', 'localMoment']
	},

	getComponentProps: function(){
		var me = this,
			formats = this.getFormats( this.props ),
			props = {dateFormat: formats.date, timeFormat: formats.time}
		;

		this.componentProps.fromProps.forEach( function( name ){
			props[ name ] = me.props[ name ];
		});
		this.componentProps.fromState.forEach( function( name ){
			props[ name ] = me.state[ name ];
		});
		this.componentProps.fromThis.forEach( function( name ){
			props[ name ] = me[ name ];
		});

		return props;
	},

	render: function() {
		var Component = this.viewComponents[ this.state.currentView ],
			DOM = React.DOM,
			className = 'rdt',
			children = []
		;

		if( this.props.input ){
			children = [ DOM.input( assign({
				key: 'i',
				type:'text',
				className:'form-control',
				onFocus: this.openCalendar,
				onChange: this.onChange,
				value: this.state.inputValue
			}, this.props.inputProps ))];
		}
		else {
			className += ' rdtStatic';
		}

		if( this.state.open )
			className += ' rdtOpen';

		return DOM.div({className: className}, children.concat(
			DOM.div(
				{ key: 'dt', className: 'rdtPicker' },
				React.createElement( Component, this.getComponentProps())
			)
		));
	}
});

module.exports = Datetime;
<commit_msg>Renamed enableTime/Date props to time/dateFormat<commit_after>'use strict';

var assign = require('object-assign'),
	React = require('react'),
	DaysView = require('./src/DaysView'),
	MonthsView = require('./src/MonthsView'),
	YearsView = require('./src/YearsView'),
	TimeView = require('./src/TimeView'),
	moment = require('moment')
;

var TYPES = React.PropTypes;
var Datetime = React.createClass({
	mixins: [
		require('react-onclickoutside')
	],
	viewComponents: {
		days: DaysView,
		months: MonthsView,
		years: YearsView,
		time: TimeView
	},
	propTypes: {
		date: TYPES.object,
		onBlur: TYPES.func,
		onChange: TYPES.func,
		locale: TYPES.string,
		input: TYPES.bool,
		// dateFormat: TYPES.string,
		// timeFormat: TYPES.string,
		inputProps: TYPES.object,
		viewMode: TYPES.oneOf(['years', 'months', 'days', 'time']),
		minDate: TYPES.object,
		maxDate: TYPES.object
	},
	getDefaultProps: function() {

		return {
			date: new Date(),
			viewMode: 'days',
			inputProps: {},
			input: true,
			timeFormat: true,
			dateFormat: true,
			onBlur: function () {},
			onChange: function (x) {
				console.log(x);
			}
		};
	},
	getInitialState: function() {
		var formats = this.getFormats( this.props ),
			date = this.props.date,
			currentView = this.props.viewMode
		;

		if( !formats.date )
			currentView = 'time';

		return {
			currentView: currentView,
			open: !this.props.input,
			inputFormat: formats.datetime,
			viewDate: this.localMoment(date).startOf("month"),
			selectedDate: this.localMoment(date),
			inputValue: this.localMoment(date).format( formats.datetime )
		};
	},

	getFormats: function( props ){
		var formats = {
				date: props.dateFormat || '',
				time: props.timeFormat || ''
			},
			locale = this.localMoment( props.date ).localeData()
		;

		if( formats.date === true ){
			formats.date = locale.longDateFormat('L');
		}
		if( formats.time === true ){
			formats.time = locale.longDateFormat('LT');
		}

		formats.datetime = formats.date + ' ' + formats.time;

		return formats;
	},

	componentWillReceiveProps: function(nextProps) {
		var formats = this.getFormats( nextProps );
		if ( formats.datetime !== this.getFormats(this.props).datetime ) {
			return this.setState({
				inputFormat: nextProps.inputFormat
			});
		}
	},

	onChange: function(event) {
		var value = event.target == null ? event : event.target.value,
			localMoment = this.localMoment( date )
		;

		if (localMoment.isValid()) {
			this.setState({
				selectedDate: localMoment,
				viewDate: localMoment.clone().startOf("month")
			});
		}

		return this.setState({
			inputValue: value
		}, function() {
			return this.props.onChange( localMoment.toDate() );
		});
	},

	showView: function( view ){
		var me = this;
		return function( e ){
			me.setState({ currentView: view });
		};
	},

	setDate: function( type ){
		var me = this,
			nextViews = {
				month: 'days',
				year: 'months'
			}
		;
		return function( e ){
			me.setState({
				viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.dataset.value) ).startOf( type ),
				currentView: nextViews[ type ]
			});
		};
	},

	addTime: function( amount, type, toSelected ){
		return this.updateTime( 'add', amount, type, toSelected );
	},

	subtractTime: function( amount, type, toSelected ){
		return this.updateTime( 'subtract', amount, type, toSelected );
	},

	updateTime: function( op, amount, type, toSelected ){
		var me = this;

		return function(){
			var update = {},
				date = toSelected ? 'selectedDate' : 'viewDate'
			;

			update[ date ] = me.state[ date ].clone()[ op ]( amount, type );

			me.setState( update );
		};
	},

	allowedSetTime: ['hours','minutes','seconds', 'milliseconds'],
	setTime: function( type, value ){
		var index = this.allowedSetTime.indexOf( type ) + 1,
			date = this.state.selectedDate.clone(),
			nextType
		;

		// It is needed to set all the time properties
		// to not to reset the time
		date[ type ]( value );
		for (; index < this.allowedSetTime.length; index++) {
			nextType = this.allowedSetTime[index];
			date[ nextType ]( date[nextType]() );
		}

		this.setState({
			selectedDate: date,
			inputValue: date.format( this.state.inputFormat )
		}, this.callOnChange );
	},

	callOnChange: function(){
		this.props.onChange(this.state.selectedDate.format( this.state.inputFormat ));
	},

	updateDate: function( e ) {
		var target = e.target,
			modifier = 0,
			currentDate = this.state.selectedDate,
			date
		;

		if(target.className.indexOf("new") != -1)
			modifier = 1;
		else if(target.className.indexOf("old") != -1)
			modifier = -1;

		date = this.state.viewDate.clone()
			.month( this.state.viewDate.month() + modifier )
			.date( parseInt( target.dataset.value ) )
			.hours( currentDate.hours() )
			.minutes( currentDate.minutes() )
			.seconds( currentDate.seconds() )
			.milliseconds( currentDate.milliseconds() )
		;

		this.setState({
			selectedDate: date,
			viewDate: date.clone().startOf('month'),
			inputValue: date.format( this.state.inputFormat )
		}, this.callOnChange );
	},

	openCalendar: function() {
		this.setState({ open: true });
	},

	handleClickOutside: function(){
		this.props.onBlur(this.state.inputValue);
		if( this.props.input && this.state.open )
			this.setState({ open: false });
	},

	localMoment: function( date ){
		var m = moment( date );
		if( this.props.locale )
			m.locale( this.props.locale );
		return m;
	},

	componentProps: {
		fromProps: ['viewMode', 'minDate', 'maxDate', 'renderDay', 'renderMonth', 'renderYear'],
		fromState: ['viewDate', 'selectedDate' ],
		fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateDate', 'localMoment']
	},

	getComponentProps: function(){
		var me = this,
			formats = this.getFormats( this.props ),
			props = {dateFormat: formats.date, timeFormat: formats.time}
		;

		this.componentProps.fromProps.forEach( function( name ){
			props[ name ] = me.props[ name ];
		});
		this.componentProps.fromState.forEach( function( name ){
			props[ name ] = me.state[ name ];
		});
		this.componentProps.fromThis.forEach( function( name ){
			props[ name ] = me[ name ];
		});

		return props;
	},

	render: function() {
		var Component = this.viewComponents[ this.state.currentView ],
			DOM = React.DOM,
			className = 'rdt',
			children = []
		;

		if( this.props.input ){
			children = [ DOM.input( assign({
				key: 'i',
				type:'text',
				className:'form-control',
				onFocus: this.openCalendar,
				onChange: this.onChange,
				value: this.state.inputValue
			}, this.props.inputProps ))];
		}
		else {
			className += ' rdtStatic';
		}

		if( this.state.open )
			className += ' rdtOpen';

		return DOM.div({className: className}, children.concat(
			DOM.div(
				{ key: 'dt', className: 'rdtPicker' },
				React.createElement( Component, this.getComponentProps())
			)
		));
	}
});

module.exports = Datetime;
<|endoftext|>


<commit_before>//getting time of day for initial greeting

var d = new Date();
var hour = d.getHours();
var watchTime = d.toLocaleTimeString();

//setting greeting based on time of day received
var greeting;
var heyHoney = function() {
  if (hour < 12 && hour >= 0) {
    greeting = "Good morning" ;
  }
  else if (hour <= 18) {
    greeting = "Good afternoon";
  }
  else {
    greeting = "Good evening";
  }
return greeting + ", honey! The time is " + watchTime + ".";
};

//setting a countdown to Friday to keep the spirits of the basic bitches up
var dayOfWeek = d.getDay();
var TGIFMessage;
if (dayOfWeek === 0 || dayOfWeek === 6) {
  TGIFMessage = "What the good-God-damn are you doing out of bed on the weekend?!";
}
else if (dayOfWeek >= 1 || dayOfWeek <= 3) {
  TGIFMessage = "Only " + (5 - dayOfWeek) + "more days until Friday!";
}
else if (dayOfWeek === 4) {
  TGIFMessage = "Tomorrow's Friday! You're almost there...";
}
else {
  TGIFMessage = "TGIF, BITCHES.";
}

console.log(heyHoney());
console.log(TGIFMessage);<commit_msg>minor changes as I get sleepier and more violent<commit_after>//getting time of day for initial greeting

var d = new Date();
var hour = d.getHours();
var watchTime = d.toLocaleTimeString();

//setting greeting based on time of day received
var greeting;
var heyHoney = function() {
  if (hour < 12 && hour >= 0) {
    greeting = "Good morning" ;
  }
  else if (hour <= 18) {
    greeting = "Good afternoon";
  }
  else {
    greeting = "Good evening";
  }
return greeting + ", honey! The time is " + watchTime + ".";
};

//setting a countdown to Friday to keep the spirits of the basic bitches up
var dayOfWeek = d.getDay();
var TGIFMessage;
if (dayOfWeek === 0 || dayOfWeek === 6) {
  TGIFMessage = "What the good-God-damn are you doing \nOUT\nOF\nBED\non the weekend?!";
}
else if (dayOfWeek >= 1 || dayOfWeek <= 3) {
  TGIFMessage = "Only " + (5 - dayOfWeek) + "more days until Friday!\nYour hair looks great today, by the way.";
}
else if (dayOfWeek === 4) {
  TGIFMessage = "Tomorrow's Friday! You're almost there...";
}
else {
  TGIFMessage = "TGIF, BITCHES.\nYou deserve a drank.";
}
//console.logging until I figure out fucking HTML goddamnit shit fuck
console.log(heyHoney());
console.log(TGIFMessage);<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var replace = require('gulp-replace');
var header = require('gulp-header');
var debug = require('gulp-debug');
var inject = require('gulp-inject');
var tsc = require('gulp-typescript');
var tslint = require('gulp-tslint');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var copy = require('gulp-copy');
var coveralls = require('gulp-coveralls');
var umd = require('gulp-umd');
var path = require('path');

var gulpKarma = require('./tools/gulp/gulp-karma.js');

var Config = require('./gulp.config.js');
var config = new Config();

gulp.task('default', ['compile-app']);

gulp.task('watch', function () {
    gulp.watch([config.allTypeScript], ['compile-app']);
});

gulp.task('release', ['compile-app', 'test-app-dependent', /*'distribute-test-results',*/ 'compile-performance-tests', 'compile-samples', 'distribute']);

/** lint TypeScript files to ensure high quality code. */
gulp.task('ts-lint', function () {
    var tsFiles = [config.allAppTsFiles, config.allSampleTsFiles];
    return gulp
        .src(tsFiles)
        .pipe(tslint({ formatter: 'verbose' }))
        .pipe(tslint.report());
});

/** compile TypeScript and include references to library and app .d.ts files. */
gulp.task('compile-app', ['ts-lint'], function () {
    var tscProject = tsc.createProject('tsconfig.json'/*, {
        outDir: config.bundleFolder,
        outFile: config.appBundleName
    }*/);
    var tsResult = gulp.src([config.allAppTsFiles])
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.appJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.appJsOutputFolder));
});

/** compile TypeScript sample files. */
gulp.task('compile-samples', ['distribute'], function () {
    var sampleTsFiles = [
        config.allSampleTsFiles//,              // path to typescript files
        //config.libraryTypeScriptDefinitions   // reference to library .d.ts files
    ];

    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src(sampleTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.samplesJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.samplesJsOutputFolder));
});

/** compile TypeScript sample files. */
gulp.task('compile-performance-tests', ['distribute'], function () {
    var performanceTestTsFiles = [
        config.allPerformanceTestTsFiles
    ];

    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src(performanceTestTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.performanceTestsJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.performanceTestsJsOutputFolder));
});

/** compile TypeScript test files. */
function compileTest() {
    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src([config.allTestTsFiles]).pipe(tscProject());
    tsResult.dts.pipe(gulp.dest(config.testJsOutputFolder));
    return tsResult.js.pipe(gulp.dest(config.testJsOutputFolder));
}

/** compile TypeScript test files (dependency to compile-app). */
gulp.task('compile-test-app-dependent', ['compile-app'], compileTest);

/** compile TypeScript test files. */
gulp.task('compile-test', compileTest);

gulp.task('copy-test-output-coverage-app-dependent',
    ['compile-test-app-dependent'], function () {
        return gulp.src(config.appJsOutputFolder + '**/*.*')
            .pipe(copy(config.testCoverageOutputFolder, { prefix: 2 }));
    });

gulp.task('copy-test-output-coverage',
    ['compile-test'], function () {
        return gulp.src(config.appJsOutputFolder + '**/*.*')
            .pipe(copy(config.testCoverageOutputFolder, { prefix: 2 }));
    });

/** distribute JS output files. */
gulp.task('distribute', ['bundle-app', 'bundle-app-uglify', 'distribute-app-definitions', 'bundle-app-definitions', 'distribute-app-sync-version']);

/** bundle app JS output files. */
gulp.task('bundle-app', ['compile-app'], function () {
    // concat source scripts
    gulp.src(config.allAppJsFiles)
        .pipe(sourcemaps.init())
        .pipe(concat(config.appBundleName))
        .pipe(umd({
            exports: function (file) {
                return path.basename(file.path, path.extname(file.path));
            }
        }))
        .pipe(header(config.libraryHeaderTemplate, {
            organization: config.libraryOrganization,
            url: config.libraryUrl,
            license: config.libraryLicense,
            version: config.libraryVersion,
            currentDate: config.currentDate.toISOString()
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.bundleFolder));
});

/** bundle and uglify app JS output files. */
gulp.task('bundle-app-uglify', ['compile-app'], function () {
    // concat and uglify source scripts
    gulp.src(config.allAppJsFiles)
        .pipe(sourcemaps.init())
        .pipe(concat(config.appBundleNameMinified))
        .pipe(uglify())
        .pipe(header(config.libraryHeaderTemplate, {
            organization: config.libraryOrganization,
            url: config.libraryUrl,
            license: config.libraryLicense,
            version: config.libraryVersion,
            currentDate: config.currentDate.toISOString()
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.bundleFolder));
});

/** distribute app TypeScript definition files. */
gulp.task('distribute-app-definitions', function () {
    gulp.src(config.allAppDefinitionFiles)
        .pipe(replace('__RemoveForDistribution__', ''))
        .pipe(replace('${libraryVersion}', config.libraryVersion))
        .pipe(gulp.dest(config.bundleFolder));
});

/** bundle app JS output files. */
gulp.task('bundle-app-definitions', ['distribute-app-definitions'], function () {
    // concat source scripts
    gulp.src(config.allAppDefinitionFiles)
        .pipe(replace('__RemoveForDistribution__', ''))
        .pipe(replace('${libraryVersion}', config.libraryVersion))
        .pipe(replace(/\/\/ \[bundle remove start\][^]*?\/\/ \[bundle remove end\]\r?\n?/gmi, ''))
        .pipe(concat(config.appDefinitionBundleName))
        .pipe(gulp.dest(config.bundleFolder));
});

/** syng app version numbers. */
gulp.task('distribute-app-sync-version', function () {
    var appVersionFiles = [
        config.baseFolder + 'bower.json',
        config.baseFolder + 'package.json'
    ];

    gulp.src(appVersionFiles)
        .pipe(replace(/((?:"|')version(?:"|')\s?:\s?(?:"|'))[0-9]{1}\.[0-9]{1}\.[0-9]{1}((?:"|'))/, '$1' + config.libraryVersion + '$2'))
        .pipe(gulp.dest(config.baseFolder));
});

function test() {
    var karmaConfig = {
        configFile: config.testFolder + 'karma.conf.js',
        preprocessors: {},
        singleRun: true,
        autoWatch: false
    };
    karmaConfig.preprocessors[config.testCoverageOutputFolder + '**/*.js'] = ['coverage'];

    return gulp
        .src(config.allTestFiles)
        .pipe(gulpKarma(karmaConfig));
}
/** execute test files (dependency to compile-test). */
gulp.task('test', ['compile-test', 'copy-test-output-coverage'], test);

/** execute test files (dependency to compile-test-app-dependent). */
gulp.task('test-app-dependent', ['compile-test-app-dependent', 'copy-test-output-coverage-app-dependent'], test);

/** watch app and test test files (dependency to compile-test). */
gulp.task('test-watch', ['compile-test', 'copy-test-output-coverage'], function () {
    var karmaConfig = {
        configFile: config.testFolder + 'karma.conf.js',
        //preprocessors: {},
        singleRun: false,
        autoWatch: true
    };
    //karmaConfig.preprocessors[config.testCoverageOutputFolder + '**/*.js'] = ['coverage'];

    gulp.watch([config.allAppTsFiles, config.libraryTypeScriptDefinitions], ['compile-test-app-dependent']);
    gulp.watch([config.allTestTsFiles], ['compile-test', 'copy-test-output-coverage']);

    gulp.src(config.allTestFiles)
        .pipe(gulpKarma(karmaConfig));
});

gulp.task('coveralls', function () {
    return gulp
        .src(config.testFolder + 'coverage/**/lcov.info')
        .pipe(coveralls());
});<commit_msg>Update gulp-umd Configuration to Export AutoMapperJs Namespace (#47)<commit_after>'use strict';

var gulp = require('gulp');
var replace = require('gulp-replace');
var header = require('gulp-header');
var debug = require('gulp-debug');
var inject = require('gulp-inject');
var tsc = require('gulp-typescript');
var tslint = require('gulp-tslint');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var copy = require('gulp-copy');
var coveralls = require('gulp-coveralls');
var umd = require('gulp-umd');
var path = require('path');

var gulpKarma = require('./tools/gulp/gulp-karma.js');

var Config = require('./gulp.config.js');
var config = new Config();

gulp.task('default', ['compile-app']);

gulp.task('watch', function () {
    gulp.watch([config.allTypeScript], ['compile-app']);
});

gulp.task('release', ['compile-app', 'test-app-dependent', /*'distribute-test-results',*/ 'compile-performance-tests', 'compile-samples', 'distribute']);

/** lint TypeScript files to ensure high quality code. */
gulp.task('ts-lint', function () {
    var tsFiles = [config.allAppTsFiles, config.allSampleTsFiles];
    return gulp
        .src(tsFiles)
        .pipe(tslint({ formatter: 'verbose' }))
        .pipe(tslint.report());
});

/** compile TypeScript and include references to library and app .d.ts files. */
gulp.task('compile-app', ['ts-lint'], function () {
    var tscProject = tsc.createProject('tsconfig.json'/*, {
        outDir: config.bundleFolder,
        outFile: config.appBundleName
    }*/);
    var tsResult = gulp.src([config.allAppTsFiles])
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.appJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.appJsOutputFolder));
});

/** compile TypeScript sample files. */
gulp.task('compile-samples', ['distribute'], function () {
    var sampleTsFiles = [
        config.allSampleTsFiles//,              // path to typescript files
        //config.libraryTypeScriptDefinitions   // reference to library .d.ts files
    ];

    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src(sampleTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.samplesJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.samplesJsOutputFolder));
});

/** compile TypeScript sample files. */
gulp.task('compile-performance-tests', ['distribute'], function () {
    var performanceTestTsFiles = [
        config.allPerformanceTestTsFiles
    ];

    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src(performanceTestTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tscProject());

    tsResult.dts.pipe(gulp.dest(config.performanceTestsJsOutputFolder));
    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.performanceTestsJsOutputFolder));
});

/** compile TypeScript test files. */
function compileTest() {
    var tscProject = tsc.createProject('tsconfig.json');
    var tsResult = gulp.src([config.allTestTsFiles]).pipe(tscProject());
    tsResult.dts.pipe(gulp.dest(config.testJsOutputFolder));
    return tsResult.js.pipe(gulp.dest(config.testJsOutputFolder));
}

/** compile TypeScript test files (dependency to compile-app). */
gulp.task('compile-test-app-dependent', ['compile-app'], compileTest);

/** compile TypeScript test files. */
gulp.task('compile-test', compileTest);

gulp.task('copy-test-output-coverage-app-dependent',
    ['compile-test-app-dependent'], function () {
        return gulp.src(config.appJsOutputFolder + '**/*.*')
            .pipe(copy(config.testCoverageOutputFolder, { prefix: 2 }));
    });

gulp.task('copy-test-output-coverage',
    ['compile-test'], function () {
        return gulp.src(config.appJsOutputFolder + '**/*.*')
            .pipe(copy(config.testCoverageOutputFolder, { prefix: 2 }));
    });

/** distribute JS output files. */
gulp.task('distribute', ['bundle-app', 'bundle-app-uglify', 'distribute-app-definitions', 'bundle-app-definitions', 'distribute-app-sync-version']);

/** bundle app JS output files. */
gulp.task('bundle-app', ['compile-app'], function () {
    // concat source scripts
    gulp.src(config.allAppJsFiles)
        .pipe(sourcemaps.init())
        .pipe(concat(config.appBundleName))
        .pipe(umd({
            exports: function () {
                return 'AutoMapperJs';
            },
            namespace: function () {
                return 'AutoMapperJs';
            }
        }))
        .pipe(header(config.libraryHeaderTemplate, {
            organization: config.libraryOrganization,
            url: config.libraryUrl,
            license: config.libraryLicense,
            version: config.libraryVersion,
            currentDate: config.currentDate.toISOString()
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.bundleFolder));
});

/** bundle and uglify app JS output files. */
gulp.task('bundle-app-uglify', ['compile-app'], function () {
    // concat and uglify source scripts
    gulp.src(config.allAppJsFiles)
        .pipe(sourcemaps.init())
        .pipe(concat(config.appBundleNameMinified))
        .pipe(uglify())
        .pipe(header(config.libraryHeaderTemplate, {
            organization: config.libraryOrganization,
            url: config.libraryUrl,
            license: config.libraryLicense,
            version: config.libraryVersion,
            currentDate: config.currentDate.toISOString()
        }))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.bundleFolder));
});

/** distribute app TypeScript definition files. */
gulp.task('distribute-app-definitions', function () {
    gulp.src(config.allAppDefinitionFiles)
        .pipe(replace('__RemoveForDistribution__', ''))
        .pipe(replace('${libraryVersion}', config.libraryVersion))
        .pipe(gulp.dest(config.bundleFolder));
});

/** bundle app JS output files. */
gulp.task('bundle-app-definitions', ['distribute-app-definitions'], function () {
    // concat source scripts
    gulp.src(config.allAppDefinitionFiles)
        .pipe(replace('__RemoveForDistribution__', ''))
        .pipe(replace('${libraryVersion}', config.libraryVersion))
        .pipe(replace(/\/\/ \[bundle remove start\][^]*?\/\/ \[bundle remove end\]\r?\n?/gmi, ''))
        .pipe(concat(config.appDefinitionBundleName))
        .pipe(gulp.dest(config.bundleFolder));
});

/** syng app version numbers. */
gulp.task('distribute-app-sync-version', function () {
    var appVersionFiles = [
        config.baseFolder + 'bower.json',
        config.baseFolder + 'package.json'
    ];

    gulp.src(appVersionFiles)
        .pipe(replace(/((?:"|')version(?:"|')\s?:\s?(?:"|'))[0-9]{1}\.[0-9]{1}\.[0-9]{1}((?:"|'))/, '$1' + config.libraryVersion + '$2'))
        .pipe(gulp.dest(config.baseFolder));
});

function test() {
    var karmaConfig = {
        configFile: config.testFolder + 'karma.conf.js',
        preprocessors: {},
        singleRun: true,
        autoWatch: false
    };
    karmaConfig.preprocessors[config.testCoverageOutputFolder + '**/*.js'] = ['coverage'];

    return gulp
        .src(config.allTestFiles)
        .pipe(gulpKarma(karmaConfig));
}
/** execute test files (dependency to compile-test). */
gulp.task('test', ['compile-test', 'copy-test-output-coverage'], test);

/** execute test files (dependency to compile-test-app-dependent). */
gulp.task('test-app-dependent', ['compile-test-app-dependent', 'copy-test-output-coverage-app-dependent'], test);

/** watch app and test test files (dependency to compile-test). */
gulp.task('test-watch', ['compile-test', 'copy-test-output-coverage'], function () {
    var karmaConfig = {
        configFile: config.testFolder + 'karma.conf.js',
        //preprocessors: {},
        singleRun: false,
        autoWatch: true
    };
    //karmaConfig.preprocessors[config.testCoverageOutputFolder + '**/*.js'] = ['coverage'];

    gulp.watch([config.allAppTsFiles, config.libraryTypeScriptDefinitions], ['compile-test-app-dependent']);
    gulp.watch([config.allTestTsFiles], ['compile-test', 'copy-test-output-coverage']);

    gulp.src(config.allTestFiles)
        .pipe(gulpKarma(karmaConfig));
});

gulp.task('coveralls', function () {
    return gulp
        .src(config.testFolder + 'coverage/**/lcov.info')
        .pipe(coveralls());
});<|endoftext|>


<commit_before>const assert = require('assert');
const clean  = require('gulp-clean');
const coffee = require('gulp-coffee');
const exec   = require('gulp-exec');
const File   = require('fs');
const gulp   = require('gulp');
const gutil  = require('gulp-util');
const notify = require('gulp-notify');

// gulp -> gulp watch
gulp.task('default', ['watch']);

// gulp build -> compile coffee script
gulp.task('build', ['clean'], function() {
  const compile = coffee({ bare: true })
    .on('error', function(error) {
      notify({
        title:    'Fail!',
        message:  error.toString()
      }).write(error);
    });
  gulp.src('src/**/*.coffee')
    .pipe(compile)
    .pipe( notify({
      title:    'Success!',
      message:  'Compiled Zombie.js',
      onLast:   true
    }) )
    .pipe( gulp.dest('lib/') );
});

// gulp clean -> clean generated files
gulp.task('clean', function() {
  return gulp
    .src('lib', { read: false })
    .pipe( clean() );
});

// gulp watch -> watch for changes and compile
gulp.task('watch', ['build'], function() {
  return gulp.watch('src/**/*.coffee', ['clean', 'build']);
});

// gulp tag -> Tag this release
gulp.task('tag', ['changes'], function() {
  const version = require('./package.json').version;
  const tag     = 'v' + version;

  gutil.log('Tagging this release', tag);
  return gulp.src('.changes')
    .pipe( exec('git tag ' + tag + ' --file .changes') )
    .pipe( exec('git push origin ' + tag) )
    .pipe( exec('git push origin master') );
});

// Generate a change log summary for this release
// git tag uses the generated .changes file
gulp.task('changes', function() {
  const version   = require('./package.json').version;
  const changelog = File.readFileSync('CHANGELOG.md', 'utf-8');
  const match     = changelog.match(/^## Version (.*) .*\n([\S\s]+?)\n##/m);

  assert(match, 'CHANGELOG.md missing entry: ## Version ' + version);
  assert.equal(match[1], version, 'CHANGELOG.md missing entry for version ' + version);

  const changes   = match[2].trim();
  assert(changes, 'CHANGELOG.md empty entry for version ' + version);
  File.writeFileSync('.changes', changes);
});

<commit_msg>ADDED include version commit message<commit_after>const assert = require('assert');
const clean  = require('gulp-clean');
const coffee = require('gulp-coffee');
const exec   = require('gulp-exec');
const File   = require('fs');
const gulp   = require('gulp');
const gutil  = require('gulp-util');
const notify = require('gulp-notify');

// gulp -> gulp watch
gulp.task('default', ['watch']);

// gulp build -> compile coffee script
gulp.task('build', ['clean'], function() {
  const compile = coffee({ bare: true })
    .on('error', function(error) {
      notify({
        title:    'Fail!',
        message:  error.toString()
      }).write(error);
    });
  gulp.src('src/**/*.coffee')
    .pipe(compile)
    .pipe( notify({
      title:    'Success!',
      message:  'Compiled Zombie.js',
      onLast:   true
    }) )
    .pipe( gulp.dest('lib/') );
});

// gulp clean -> clean generated files
gulp.task('clean', function() {
  return gulp
    .src('lib', { read: false })
    .pipe( clean() );
});

// gulp watch -> watch for changes and compile
gulp.task('watch', ['build'], function() {
  return gulp.watch('src/**/*.coffee', ['clean', 'build']);
});

// gulp tag -> Tag this release
gulp.task('tag', ['changes'], function() {
  const version = require('./package.json').version;
  const tag     = 'v' + version;

  gutil.log('Tagging this release', tag);
  return gulp.src('.changes')
    .pipe( exec('git add package.json CHANGELOG.md') )
    .pipe( exec('git commit --allow-empty -m "Version ' + version + '"') )
    .pipe( exec('git tag ' + tag + ' --file .changes') )
    .pipe( exec('git push origin ' + tag) )
    .pipe( exec('git push origin master') );
});

// Generate a change log summary for this release
// git tag uses the generated .changes file
gulp.task('changes', function() {
  const version   = require('./package.json').version;
  const changelog = File.readFileSync('CHANGELOG.md', 'utf-8');
  const match     = changelog.match(/^## Version (.*) .*\n([\S\s]+?)\n##/m);

  assert(match, 'CHANGELOG.md missing entry: ## Version ' + version);
  assert.equal(match[1], version, 'CHANGELOG.md missing entry for version ' + version);

  const changes   = match[2].trim();
  assert(changes, 'CHANGELOG.md empty entry for version ' + version);
  File.writeFileSync('.changes', changes);
});

<|endoftext|>


<commit_before>var gulp      = require('gulp'),
    gutil     = require('gulp-util'),
    rimraf    = require('gulp-rimraf');
    source    = require('vinyl-source-stream'),
    streamify = require('gulp-streamify');

// cleaning tasks
gulp.task('cleanjs', function () {
    gulp.src('./dist/js')
        .pipe(rimraf());
});

gulp.task('cleancss', function () {
    gulp.src('./dist/css')
        .pipe(rimraf());
});

gulp.task('stylus', ['cleancss'], function () {
    var stylus = require('gulp-stylus'),
        prefix = require('gulp-autoprefixer');

    gulp.src('./styl/main.styl')
        .pipe(stylus({linenos: true}))
        .pipe(prefix())
        .pipe(gulp.dest('./dist/css'));
});

gulp.task('hint', function () {
    var cached  = require('gulp-cached'),
        jshint  = require('gulp-jshint'),
        stylish = require('jshint-stylish');

    return gulp.src('./js/**/*.js')
        .pipe(cached('hinting'))
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});

gulp.task('js', ['cleanjs', 'hint'], function () {
    var browserify = require('browserify'),
        uglify     = require('gulp-uglify');

    return browserify('./js/main.js', {
            transform: ['hbsfy'],
            debug: true
        })
        .bundle()
        .pipe(source('main.js'))
        .pipe(streamify(uglify()))
        .pipe(gulp.dest('./dist/js'));
});

// a task responsible for all compilation
gulp.task('build', ['stylus', 'js']);

gulp.task('watch', ['stylus'], function () {
    var watchify   = require('watchify'),
        browserify = require('browserify'),
        bundler    = watchify(browserify('./js/main.js', {
            cache: {},
            packageCache: {},
            fullPaths: true,
            transform: ['hbsfy'],
            debug: true
        }));

    function rebundle() {
        var t = Date.now();
        gutil.log('Starting Watchify rebundle');
        return bundler.bundle()
            .pipe(source('main.js'))
            .pipe(gulp.dest('./dist'))
            .on('end', function () {
                gutil.log('Finished bundling after:', gutil.colors.magenta(Date.now() - t + ' ms'));
            });
    }
    bundler.on('update', rebundle);
    gulp.watch('./js/**/*.js', ['hint']);
    gulp.watch('./styl/**/*.styl', ['stylus']);

    return rebundle();
});

gulp.task('default', ['build']);
<commit_msg>Add production flag and task<commit_after>var gulp      = require('gulp'),
    gutil     = require('gulp-util'),
    rimraf    = require('gulp-rimraf');
    source    = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    sequence  = require('run-sequence'),

    // check to see if a `--prod` flag was passed to gulp
    prod      = gulp.env.prod;

// toggle the production flag without passing an argument
gulp.task('setProduction', function () {
    // set the prod variable that we added above
    prod = true;
});

// cleaning tasks
gulp.task('cleanjs', function () {
    gulp.src('./dist/js')
        .pipe(rimraf());
});

gulp.task('cleancss', function () {
    gulp.src('./dist/css')
        .pipe(rimraf());
});

gulp.task('stylus', ['cleancss'], function () {
    var stylus = require('gulp-stylus'),
        prefix = require('gulp-autoprefixer'),
        minify = require('gulp-minify-css');

    gulp.src('./styl/main.styl')
        .pipe(stylus({linenos: !prod}))
        .pipe(prefix())
        .pipe(prod ? minify() : gutil.noop())
        .pipe(gulp.dest('./dist/css'));
});

gulp.task('hint', function () {
    var cached  = require('gulp-cached'),
        jshint  = require('gulp-jshint'),
        stylish = require('jshint-stylish');

    return gulp.src('./js/**/*.js')
        .pipe(cached('hinting'))
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});

gulp.task('js', ['cleanjs', 'hint'], function () {
    var browserify = require('browserify'),
        uglify     = require('gulp-uglify');

    return browserify('./js/main.js', {
            transform: ['hbsfy'],
            debug: !prod
        })
        .bundle()
        .pipe(source('main.js'))
        .pipe(prod ? streamify(uglify()) : gutil.noop())
        .pipe(gulp.dest('./dist/js'));
});

// a task responsible for all compilation
gulp.task('build', ['stylus', 'js']);

// add a task that always runs `build` in production mode
gulp.task('prod', function () {
    // use the run-sequence module to make sure
    // `setProduction` happens before other tasks
    sequence('setProduction', ['stylus', 'js'])
});

gulp.task('watch', ['stylus'], function () {
    var watchify   = require('watchify'),
        browserify = require('browserify'),
        bundler    = watchify(browserify('./js/main.js', {
            cache: {},
            packageCache: {},
            fullPaths: true,
            transform: ['hbsfy'],
            debug: true
        }));

    function rebundle() {
        var t = Date.now();
        gutil.log('Starting Watchify rebundle');
        return bundler.bundle()
            .pipe(source('main.js'))
            .pipe(gulp.dest('./dist'))
            .on('end', function () {
                gutil.log('Finished bundling after:', gutil.colors.magenta(Date.now() - t + ' ms'));
            });
    }
    bundler.on('update', rebundle);
    gulp.watch('./js/**/*.js', ['hint']);
    gulp.watch('./styl/**/*.styl', ['stylus']);

    return rebundle();
});

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


<commit_before>(function() {
  'use strict';

  var fs       = require('fs');
  var git      = require('git-rev');
  var gulp     = require('gulp');
  var less     = require('gulp-less');
  var mincss   = require('gulp-minify-css');
  var nodemon  = require('gulp-nodemon');
  var overtake = require('overtake');
  var rename   = require('gulp-rename');
  var rimraf   = require('gulp-rimraf');
  var rjs      = require('requirejs');

  var minified = { suffix: '.min' };

  /**
   * Clean existing build files
   */
  gulp.task('clean', function() {
    return gulp.src([
      './build.json',
      './public/css',
      './public/js',
      './frame/css/*.min.css'
    ], { read: false })
    .pipe(rimraf());
  });

  /**
   * Optimize scripts from AMD modules and build a single compressed JS file
   */
  gulp.task('js', function(done) {
    rjs.optimize({
      baseUrl: './public/src/js',
      mainConfigFile: './public/src/js/require.config.js',

      name: 'main',
      out: './public/js/debuggerio.min.js',

      pragmas: { bustCache: true },
      findNestedDependencies: true,
      preserveLicenseComments: true,
      useStrict: true,

      exclude: ['promise']
    },
    function() { done(); },
    function(err) {
      console.error(err);
      done();
    });
  });

  /**
   * Build LESS files for each theme into a single compressed CSS file
   */
  gulp.task('less', function(done) {
    return gulp.src('./public/src/less/debuggerio.*.less')
      .pipe(less())
      .on('error', function(err) {
        console.error(err.message);
        done();
      })
      .pipe(mincss())
      .pipe(rename(minified))
      .pipe(gulp.dest('./public/css'));
  });

  /**
   * Compress static CSS files
   */
  gulp.task('css', function() {
    return gulp.src(['./frame/css/*.css', '!./**/*.min.css'])
      .pipe(mincss())
      .pipe(rename(minified))
      .pipe(gulp.dest('./frame/css'));
  });

  /**
   * Write a `build.json` file with build information
   */
  gulp.task('rev', function(done) {
    git.short(function(rev) {
      fs.writeFile('./build.json', JSON.stringify({
        date: (new Date()).toISOString(),
        rev: rev
      }, null, 2) + '\n', function() { done(); });
    });
  });

  /**
   * Watch for changes in JS and LESS files
   */
  gulp.task('watch', ['default'], function() {
    gulp.watch('./public/src/js/*.js', ['js']);
    gulp.watch('./public/src/less/*.less', ['less']);
  });

  /**
   * Keep watching and restart
   */
  gulp.task('dev', ['watch'], function(done) {
    nodemon({ script: 'debuggerio.js', ext: 'js json less' }).on('quit', done);
  });

  /**
   * Check for CDN updates
   */
  gulp.task('cdn', function(done) {
    var filenames = [];

    gulp.src([
      '!node_modules/**',
      '!./**/*.min.*',
      './**/*.js',
      './**/*.less',
      './**/*.html'
    ], { read: false })
    .on('data', function(file) {
      filenames.push(file.path.replace(new RegExp('^' + file.base), ''));
    }).on('end', function() {
      overtake.check_files(filenames, true).done(function() {
        done();
      });
    });
  });

  /**
   * Default task
   */
  gulp.task('default', ['clean'], function() {
    return gulp.start('js', 'less', 'css', 'rev');
  });

})();
<commit_msg>Exclude objmap from build<commit_after>(function() {
  'use strict';

  var fs       = require('fs');
  var git      = require('git-rev');
  var gulp     = require('gulp');
  var less     = require('gulp-less');
  var mincss   = require('gulp-minify-css');
  var nodemon  = require('gulp-nodemon');
  var overtake = require('overtake');
  var rename   = require('gulp-rename');
  var rimraf   = require('gulp-rimraf');
  var rjs      = require('requirejs');

  var minified = { suffix: '.min' };

  /**
   * Clean existing build files
   */
  gulp.task('clean', function() {
    return gulp.src([
      './build.json',
      './public/css',
      './public/js',
      './frame/css/*.min.css'
    ], { read: false })
    .pipe(rimraf());
  });

  /**
   * Optimize scripts from AMD modules and build a single compressed JS file
   */
  gulp.task('js', function(done) {
    rjs.optimize({
      baseUrl: './public/src/js',
      mainConfigFile: './public/src/js/require.config.js',

      name: 'main',
      out: './public/js/debuggerio.min.js',

      pragmas: { bustCache: true },
      findNestedDependencies: true,
      preserveLicenseComments: true,
      useStrict: true,

      // local files with individual licenses
      exclude: ['promise', 'objmap']
    },
    function() { done(); },
    function(err) {
      console.error(err);
      done();
    });
  });

  /**
   * Build LESS files for each theme into a single compressed CSS file
   */
  gulp.task('less', function(done) {
    return gulp.src('./public/src/less/debuggerio.*.less')
      .pipe(less())
      .on('error', function(err) {
        console.error(err.message);
        done();
      })
      .pipe(mincss())
      .pipe(rename(minified))
      .pipe(gulp.dest('./public/css'));
  });

  /**
   * Compress static CSS files
   */
  gulp.task('css', function() {
    return gulp.src(['./frame/css/*.css', '!./**/*.min.css'])
      .pipe(mincss())
      .pipe(rename(minified))
      .pipe(gulp.dest('./frame/css'));
  });

  /**
   * Write a `build.json` file with build information
   */
  gulp.task('rev', function(done) {
    git.short(function(rev) {
      fs.writeFile('./build.json', JSON.stringify({
        date: (new Date()).toISOString(),
        rev: rev
      }, null, 2) + '\n', function() { done(); });
    });
  });

  /**
   * Watch for changes in JS and LESS files
   */
  gulp.task('watch', ['default'], function() {
    gulp.watch('./public/src/js/*.js', ['js']);
    gulp.watch('./public/src/less/*.less', ['less']);
  });

  /**
   * Keep watching and restart
   */
  gulp.task('dev', ['watch'], function(done) {
    nodemon({ script: 'debuggerio.js', ext: 'js json less' }).on('quit', done);
  });

  /**
   * Check for CDN updates
   */
  gulp.task('cdn', function(done) {
    var filenames = [];

    gulp.src([
      '!node_modules/**',
      '!./**/*.min.*',
      './**/*.js',
      './**/*.less',
      './**/*.html'
    ], { read: false })
    .on('data', function(file) {
      filenames.push(file.path.replace(new RegExp('^' + file.base), ''));
    }).on('end', function() {
      overtake.check_files(filenames, true).done(function() {
        done();
      });
    });
  });

  /**
   * Default task
   */
  gulp.task('default', ['clean'], function() {
    return gulp.start('js', 'less', 'css', 'rev');
  });

})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jasmine = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var shell = require('gulp-shell');
var selenium = require('selenium-standalone');
var gutil = require('gulp-util');
var argv = require('yargs').argv;
var Q = require('q');

function express() {
  var deferred = Q.defer();
  var app = require('./app.js');
  app.set('port', process.env.PORT || 3000);

  var server = app.listen(app.get('port'), function () {
    gutil.log('Express server listening on port ' + server.address().port);
    deferred.resolve(server);
  });

  return deferred.promise;

}

function vagrant() {
  var deferred = Q.defer();
  var task = shell.task('cd postgres; vagrant up')();
  task.on('end', deferred.resolve);
  task.on('error', deferred.reject);

  return deferred.promise;
}

function createdb() {
  if (argv.ci) {
    gutil.log('Adding -e ci');
    return shell.task('./node_modules/db-migrate/bin/db-migrate -e ci up')();
  } else {
    return shell.task('./node_modules/db-migrate/bin/db-migrate up')();
  }
}

function testFunctional() {
  var deferred = Q.defer();
  var stream = gulp.src('spec/**/*Journey.js').pipe(jasmine({verbose: true}));

  stream.on('data', function () {
  });

  stream.on('error', deferred.reject);
  stream.on('end', deferred.resolve);
  return deferred.promise;
}

function startSelenium() {
  var deferred = Q.defer();
  selenium.start(function (err, child) {
    if (err) {
      deferred.reject(err);
    } else {
      selenium.child = child;
      deferred.resolve(selenium.child);
    }
  });

  return deferred.promise;
}

gulp.task('express', express);

gulp.task('test', function () {
  return gulp.src(['spec/**/*.js', '!spec/**/*IT*.js', '!spec/**/*Journey.js']).pipe(jasmine());
});

gulp.task('test-integration', function () {
  return gulp.src('spec/**/*IT*.js').pipe(jasmine());
});

gulp.task('selenium-install', function (done) {
  selenium.install({
    logger: function (message) {
      gutil.log(message);
    }
  }, function (err) {
    if (err) gutil.log(err);
    done();
  })
});

gulp.task('test-functional', function () {
  var deferred = Q.defer();

  deferred.promise.then(function () {
    process.exit(0);
  }).fail(function () {
    process.exit(1);
  });

  function cleanUp(selenium, server, done) {
    gutil.log('Clean-up: ', gutil.colors.magenta('selenium'), gutil.colors.magenta('express'));
    selenium.kill();
    server.close(done);
  }

  express().then(function (server) {
    startSelenium().then(function (selenium) {
      testFunctional().then(function () {
        cleanUp(selenium, server, deferred.resolve);
      }).fail(function () {
        cleanUp(selenium, server, deferred.reject);
      });
    })
  });
});

gulp.task('create-db', createdb);

gulp.task('lint', function () {
  return gulp.src(['app.js', './spec/**/*.js', './service/*.js', './routes/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default', {verbose: true}));
});

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

gulp.task('database', function () {
  var deferred = Q.defer();
  vagrant().then(function () {
    var task = createdb();
    task.on('end', deferred.resolve);
    task.on('error', deferred.reject);
  }).fail(deferred.reject);

  return deferred.promise;
});

gulp.task('dev-setup', ['database', 'selenium-install']);
<commit_msg>When running tests we see the test cases etc.<commit_after>var gulp = require('gulp');
var jasmine = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var shell = require('gulp-shell');
var selenium = require('selenium-standalone');
var gutil = require('gulp-util');
var argv = require('yargs').argv;
var Q = require('q');

function express() {
  var deferred = Q.defer();
  var app = require('./app.js');
  app.set('port', process.env.PORT || 3000);

  var server = app.listen(app.get('port'), function () {
    gutil.log('Express server listening on port ' + server.address().port);
    deferred.resolve(server);
  });

  return deferred.promise;

}

function vagrant() {
  var deferred = Q.defer();
  var task = shell.task('cd postgres; vagrant up')();
  task.on('end', deferred.resolve);
  task.on('error', deferred.reject);

  return deferred.promise;
}

function createdb() {
  if (argv.ci) {
    gutil.log('Adding -e ci');
    return shell.task('./node_modules/db-migrate/bin/db-migrate -e ci up')();
  } else {
    return shell.task('./node_modules/db-migrate/bin/db-migrate up')();
  }
}

function testFunctional() {
  var deferred = Q.defer();
  var stream = gulp.src('spec/**/*Journey.js').pipe(jasmine({verbose: true}));

  stream.on('data', function () {
  });

  stream.on('error', deferred.reject);
  stream.on('end', deferred.resolve);
  return deferred.promise;
}

function startSelenium() {
  var deferred = Q.defer();
  selenium.start(function (err, child) {
    if (err) {
      deferred.reject(err);
    } else {
      selenium.child = child;
      deferred.resolve(selenium.child);
    }
  });

  return deferred.promise;
}

gulp.task('express', express);

gulp.task('test', function () {
  return gulp.src(['spec/**/*.js', '!spec/**/*IT*.js', '!spec/**/*Journey.js']).pipe(jasmine({verbose: true}));
});

gulp.task('test-integration', function () {
  return gulp.src('spec/**/*IT*.js').pipe(jasmine({verbose: true}));
});

gulp.task('selenium-install', function (done) {
  selenium.install({
    logger: function (message) {
      gutil.log(message);
    }
  }, function (err) {
    if (err) gutil.log(err);
    done();
  })
});

gulp.task('test-functional', function () {
  var deferred = Q.defer();

  deferred.promise.then(function () {
    process.exit(0);
  }).fail(function () {
    process.exit(1);
  });

  function cleanUp(selenium, server, done) {
    gutil.log('Clean-up: ', gutil.colors.magenta('selenium'), gutil.colors.magenta('express'));
    selenium.kill();
    server.close(done);
  }

  express().then(function (server) {
    startSelenium().then(function (selenium) {
      testFunctional().then(function () {
        cleanUp(selenium, server, deferred.resolve);
      }).fail(function () {
        cleanUp(selenium, server, deferred.reject);
      });
    })
  });
});

gulp.task('create-db', createdb);

gulp.task('lint', function () {
  return gulp.src(['app.js', './spec/**/*.js', './service/*.js', './routes/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default', {verbose: true}));
});

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

gulp.task('database', function () {
  var deferred = Q.defer();
  vagrant().then(function () {
    var task = createdb();
    task.on('end', deferred.resolve);
    task.on('error', deferred.reject);
  }).fail(deferred.reject);

  return deferred.promise;
});

gulp.task('dev-setup', ['database', 'selenium-install']);
<|endoftext|>