<commit_before>/*global define */

var selectedMapType = 'arcgis',
    currentMapType = 'arcgis',
    previousMapType = 'arcgis';

(function () {
    "use strict";

    console.debug('bootstrap setup method');
    define([
        'angular',
        'controllers/AppController',
        'controllers/MasherCtrl',
        'controllers/TabsCtrl',
        'lib/MLConfig',
        'controllers/ShareCtrl',
        'controllers/SPACtrl',
        'controllers/TopRowCtrl',
        'controllers/LeftColCtrl',
        'controllers/MapColCtrl',
        'controllers/RightColCtrl',
        'controllers/MapCtrl',
        'controllers/MapLinkrPluginCtrl',
        'controllers/MapLinkrMgrCtrl',
        'lib/GeoCoder',
        'lib/MapHosterLeaflet',
        'lib/MapHosterGoogle',
        'lib/MapHosterArcGIS'

    ], function (angular, AppController, MasherCtrl, TabsCtrl, MLConfig,
            ShareCtrl, SpaCtrl, TopRowCtrl, LeftColCtrl, MapColCtrl, RightColCtrl, MapCtrl,
            MapLinkrPluginCtrl, MapLinkrMgrCtrl, GeoCoder, MapHosterLeaflet, MapHosterGoogle, MapHosterArcGIS) {
        console.debug('bootstrap define fn');

        function init(portalForSearch) {
            // var App = angular.module('app', ['ui.bootstrap']);
            console.debug('bootstrap init method');

            // var App = angular.module("app", ['ngRoute', 'ngGrid', 'ui.bootstrap',
            //    'ui.bootstrap.transition', 'ui.bootstrap.collapse', 'ui.bootstrap.accordion', 'ui.bootstrap.modal'])

            var eventDct = {
                'client-MapXtntEvent' : null,
                'client-MapClickEvent' : null,
                'client-NewMapPosition' : null
            },

                mapRestUrlToType = {
                    'Leaflet': 'leaflet',
                    'GoogleMap' : 'google',
                    'ArcGIS' : 'arcgis'
                },

                isNewAgoWindow,
                maphost,
                $inj,
                serv,
                gmquery,
                searchService,

                googleQueryDct = {'query' : null, 'rootScope': null},

                App = angular.module("app", ['ngRoute', 'ui.bootstrap', 'ngTouch', 'ui.grid', 'ui.grid.expandable',
                    'ui.grid.selection', 'ui.grid.pinning', 'ui.router', 'ngAnimate'])

                .config(['$routeProvider', '$locationProvider', '$urlRouterProvider', '$stateProvider',
                        function ($routeProvider, $locationProvider, $urlRouterProvider, $stateProvider) {
                        console.debug('App module route provider');

                        $routeProvider.
                            when('/', {
                                templateUrl : 'partials/SystemSelector.jade',
                                // templateUrl: '/',
                                controller : App.MasherCtrl,
                                reloadOnSearch: true
                            }).
                            when('/views/partials/:id',  {
                                templateUrl: function (params) {
                                    console.log("when string is " + '/views/partials/:id');
                                    console.log(" params.id : " +  params.id);
                                    console.log("prepare to return " + '/partials/' + params.id);
                                    return '/partials/' + params.id;
                                },
                                controller: App.MapCtrl,
                                reloadOnSearch: true,
                                disableCache: true
                            }).
                            when('/templates/:id',  {
                                templateUrl: function (params) {
                                    console.log("when string is " + '/templates/:id');
                                    console.log(" params.id : " +  params.id);
                                    console.log("prepare to return " + '/templates/' + params.id);
                                    return '/templates/' + params.id;
                                },
                                controller: App.DestWndSetupCtrl,
                                reloadOnSearch: true
                            }).
                            when('/contact', {
                                controller: ShareCtrl
                            }).
                            otherwise({
                                redirectTo: '/'
                            });

                        $locationProvider.html5Mode(true);
                        console.debug('Here we are at the end of routeProvider logic');

                    }
                    ]).

                factory("CurrentWebMapIdService", function () {
                    var currentWebMapId = "fooWebMapId";
                    return {
                        setCurrentWebMapId : function (newId) { currentWebMapId = newId; },
                        getCurrentWebMapId : function () { return currentWebMapId; }
                    };
                }).
                factory("CurrentMapTypeService", function () {
                    var mapTypes = {
                        'leaflet': MapHosterLeaflet,
                        'google' : MapHosterGoogle,
                        'arcgis' : MapHosterArcGIS
                    },

                        mapRestUrl = {
                            'leaflet': 'Leaflet',
                            'google' : 'GoogleMap',
                            'arcgis' : 'ArcGIS'
                        },

                        getMapTypes = function () {
                            var values = Object.keys(mapTypes).map(function (key) {
                                return {'type' : key, 'mph' : mapTypes[key]};
                            });
                            return values;

                            // var mapTypeValues = [];
                            // for (var key in mapTypes){
                                // mapTypeValues.push(mapTypes[key]);
                            // return mapTypes;
                        },
                        getSpecificMapType = function (key) {
                            return mapTypes[key];
                        },
                        getMapType = function () {
                            return mapTypes[currentMapType];
                        },
                        getMapTypeKey = function () {
                            return selectedMapType;
                        },
                        getMapRestUrl = function () {
                            return mapRestUrl[selectedMapType];
                        },
                        setMapType = function (mpt) {
                            previousMapType = currentMapType;
                            selectedMapType = mpt;
                            currentMapType = mpt;
                            console.log("selectedMapType set to " + selectedMapType);
                            MapCtrl.invalidateCurrentMapTypeConfigured();
                        },
                        getPreviousMapType = function () {
                            return mapTypes[previousMapType];
                        },
                        getSelectedMapType = function () {
                            console.log("getSelectedMapType : " + selectedMapType);
                            return mapTypes[selectedMapType];
                        };
                    return {
                        getMapTypes: getMapTypes,
                        getCurrentMapType : getMapType,
                        setCurrentMapType : setMapType,
                        getPreviousMapType : getPreviousMapType,
                        getSelectedMapType : getSelectedMapType,
                        getMapTypeKey : getMapTypeKey,
                        getMapRestUrl : getMapRestUrl,
                        getSpecificMapType : getSpecificMapType
                    };
                }).

                factory("StompEventHandlerService", function () {
                    var getEventDct = function () {
                        return eventDct;
                    },

                        addEvent = function (evt, handler) {
                            eventDct[evt] = handler;
                        },

                        getHandler = function (evt) {
                            return eventDct[evt];
                        };
                    return {
                        getEventDct : getEventDct,
                        addEvent : addEvent,
                        getHandler : getHandler
                    };
                }).

                factory("GoogleQueryService", function ($rootScope) {
                    googleQueryDct.rootScope = $rootScope;
                    var getRootScope = function () {
                        return googleQueryDct.rootScope;
                    },
                        getQueryDestinationDialogScope = function (mapsys) {
                            var elemID = 'DestWndDialogNode',
                                e = document.getElementById(elemID),
                                scope = angular.element(e).scope();
                            return scope;
                        },

                        getPusherDialogScope = function () {
                            var elemID = 'PusherChannelDialog',
                                e = document.getElementById(elemID),
                                scope = angular.element(e).scope();
                            return scope;
                        },

                        setDialogVisibility = function (tf) {
                            var e = document.getElementById('Verbage'),
                                scope = angular.element(e).scope(),
                                previousVisibility = scope.VerbVis;
                            scope.VerbVis = tf ? 'flex' : 'none';
                            if (tf === false) {
                                angular.element(e).css({'display' : 'none'});
                            }
                            return previousVisibility;
                        },

                        getQueryDct = function () {
                            return googleQueryDct;
                        },
                        setQuery = function (q) {
                            // alert('setQuery' + q);
                            googleQueryDct.query = q;
                        };
                    return {
                        getQueryDct: getQueryDct,
                        setQuery : setQuery,
                        getQueryDestinationDialogScope : getQueryDestinationDialogScope,
                        getPusherDialogScope : getPusherDialogScope,
                        setDialogVisibility : setDialogVisibility,
                        getRootScope : getRootScope
                    };
                }).

                value('linkrScopes', {
                    scopes : [],
                    addScope : function (s) {
                        this.scopes.push(s);
                    },
                    getScopes : function () {
                        return this.scopes;
                    }
                }).

                factory("LinkrService", ['$rootScope', 'linkrScopes', function ($rootScope, linkrScopes) {
                    var hideLinkr,
                        showLinkr,
                        addScope;

                    addScope = function (scope) {
                        linkrScopes.addScope(scope);
                    };
                    hideLinkr = function () {
                        var data = {'visibility' : 'none'},
                            scp = linkrScopes.getScopes()[0];
                        if (scp) {
                            scp.$broadcast('displayLinkerEvent', data);
                        }
                    };
                    showLinkr = function () {
                        var data = {'visibility' : 'block'},
                            scp;
                        angular.forEach(linkrScopes.getScopes(), function(scp){
                            if (scp) {
                                scp.$broadcast('displayLinkerEvent', data);
                            }
                        });
                    };

                    return {addScope : addScope, hideLinkr: hideLinkr, showLinkr: showLinkr};
                }]).

                factory("MapControllerService", function ($rootScope) {
                    var getController = function () {
                        return MapCtrl;
                    };

                    return {getController: getController};
                });

            App.directive('autoFocus', function ($timeout) {
                return {
                    restrict: 'AC',
                    link: function (locscope, locelement) {
                        console.log("directive autoFocus");
                        $timeout(function () {
                            locelement[0].focus();
                        }, 0);
                    }
                };
            });
            App.directive('ngEnter', function () {
                return function (scope, element, attrs) {
                    element.bind("keydown keypress", function (event) {
                        if (event.which === 13) {
                            scope.$apply(function () {
                                scope.$eval(attrs.ngEnter);
                            });

                            event.preventDefault();
                        }
                    });
                };
            });

            AppController.start(App, portalForSearch);
            // need to bootstrap angular since we wait for dojo/DOM to load
            angular.bootstrap(document.body, ['app']);

            console.log("url is " + location.search);
            isNewAgoWindow = MLConfig.testUrlArgs();
            MLConfig.setDestinationPreference('New Pop-up Window');
            if (isNewAgoWindow) {
                maphost = MLConfig.maphost();
                console.log('maphost : ' + maphost);

                $inj = angular.injector(['app']);
                serv = $inj.get('CurrentMapTypeService');
                serv.setCurrentMapType(mapRestUrlToType[maphost]);
                console.log('maptype' + mapRestUrlToType[maphost]);

                if (maphost === 'GoogleMap') {
                    gmquery = MLConfig.getQueryFromUrl();
                    searchService = $inj.get('GoogleQueryService');
                    searchService.setQuery(gmquery);
                }

                MasherCtrl.startMapSystem();
                TabsCtrl.forceMapSystem(maphost);
                MLConfig.setHideWebSiteOnStartup(true);
                // MasherCtrl.startMapSystem();
                // SpaCtrl.hideWebsite();
            }
            return App;
        }

        return { start: init };

    });

}());

// }).call(this);
<commit_msg>Attempts to use defer/promise<commit_after>/*global define */

var selectedMapType = 'arcgis',
    currentMapType = 'arcgis',
    previousMapType = 'arcgis';

(function () {
    "use strict";

    console.debug('bootstrap setup method');
    define([
        'angular',
        'controllers/AppController',
        'controllers/MasherCtrl',
        'controllers/TabsCtrl',
        'lib/MLConfig',
        'controllers/ShareCtrl',
        'controllers/SPACtrl',
        'controllers/TopRowCtrl',
        'controllers/LeftColCtrl',
        'controllers/MapColCtrl',
        'controllers/RightColCtrl',
        'controllers/MapCtrl',
        'controllers/MapLinkrPluginCtrl',
        'controllers/MapLinkrMgrCtrl',
        'lib/GeoCoder',
        'lib/MapHosterLeaflet',
        'lib/MapHosterGoogle',
        'lib/MapHosterArcGIS'

    ], function (angular, AppController, MasherCtrl, TabsCtrl, MLConfig,
            ShareCtrl, SpaCtrl, TopRowCtrl, LeftColCtrl, MapColCtrl, RightColCtrl, MapCtrl,
            MapLinkrPluginCtrl, MapLinkrMgrCtrl, GeoCoder, MapHosterLeaflet, MapHosterGoogle, MapHosterArcGIS) {
        console.debug('bootstrap define fn');

        function init(portalForSearch) {
            // var App = angular.module('app', ['ui.bootstrap']);
            console.debug('bootstrap init method');

            // var App = angular.module("app", ['ngRoute', 'ngGrid', 'ui.bootstrap',
            //    'ui.bootstrap.transition', 'ui.bootstrap.collapse', 'ui.bootstrap.accordion', 'ui.bootstrap.modal'])

            var eventDct = {
                'client-MapXtntEvent' : null,
                'client-MapClickEvent' : null,
                'client-NewMapPosition' : null
            },

                mapRestUrlToType = {
                    'Leaflet': 'leaflet',
                    'GoogleMap' : 'google',
                    'ArcGIS' : 'arcgis'
                },

                isNewAgoWindow,
                maphost,
                $inj,
                serv,
                gmquery,
                searchService,
                deferred,
                promise,

                googleQueryDct = {'query' : null, 'rootScope': null},

                App = angular.module("app", ['ngRoute', 'ui.bootstrap', 'ngTouch', 'ui.grid', 'ui.grid.expandable',
                    'ui.grid.selection', 'ui.grid.pinning', 'ui.router', 'ngAnimate'])

                .config(['$routeProvider', '$locationProvider', '$urlRouterProvider', '$stateProvider',
                        function ($routeProvider, $locationProvider, $urlRouterProvider, $stateProvider) {
                        console.debug('App module route provider');

                        $routeProvider.
                            when('/', {
                                templateUrl : 'partials/SystemSelector.jade',
                                // templateUrl: '/',
                                controller : App.MasherCtrl,
                                reloadOnSearch: true
                            }).
                            when('/views/partials/:id',  {
                                templateUrl: function (params) {
                                    console.log("when string is " + '/views/partials/:id');
                                    console.log(" params.id : " +  params.id);
                                    console.log("prepare to return " + '/partials/' + params.id);
                                    return '/partials/' + params.id;
                                },
                                controller: App.MapCtrl,
                                reloadOnSearch: true,
                                disableCache: true
                            }).
                            when('/templates/:id',  {
                                templateUrl: function (params) {
                                    console.log("when string is " + '/templates/:id');
                                    console.log(" params.id : " +  params.id);
                                    console.log("prepare to return " + '/templates/' + params.id);
                                    return '/templates/' + params.id;
                                },
                                controller: App.DestWndSetupCtrl,
                                reloadOnSearch: true
                            }).
                            when('/contact', {
                                controller: ShareCtrl
                            }).
                            otherwise({
                                redirectTo: '/'
                            });

                        $locationProvider.html5Mode(true);
                        console.debug('Here we are at the end of routeProvider logic');

                    }
                    ]).

                factory("CurrentWebMapIdService", function () {
                    var currentWebMapId = "fooWebMapId";
                    return {
                        setCurrentWebMapId : function (newId) { currentWebMapId = newId; },
                        getCurrentWebMapId : function () { return currentWebMapId; }
                    };
                }).
                factory("CurrentMapTypeService", function () {
                    var mapTypes = {
                        'leaflet': MapHosterLeaflet,
                        'google' : MapHosterGoogle,
                        'arcgis' : MapHosterArcGIS
                    },

                        mapRestUrl = {
                            'leaflet': 'Leaflet',
                            'google' : 'GoogleMap',
                            'arcgis' : 'ArcGIS'
                        },

                        getMapTypes = function () {
                            var values = Object.keys(mapTypes).map(function (key) {
                                return {'type' : key, 'mph' : mapTypes[key]};
                            });
                            return values;

                            // var mapTypeValues = [];
                            // for (var key in mapTypes){
                                // mapTypeValues.push(mapTypes[key]);
                            // return mapTypes;
                        },
                        getSpecificMapType = function (key) {
                            return mapTypes[key];
                        },
                        getMapType = function () {
                            return mapTypes[currentMapType];
                        },
                        getMapTypeKey = function () {
                            return selectedMapType;
                        },
                        getMapRestUrl = function () {
                            return mapRestUrl[selectedMapType];
                        },
                        setMapType = function (mpt) {
                            previousMapType = currentMapType;
                            selectedMapType = mpt;
                            currentMapType = mpt;
                            console.log("selectedMapType set to " + selectedMapType);
                            MapCtrl.invalidateCurrentMapTypeConfigured();
                        },
                        getPreviousMapType = function () {
                            return mapTypes[previousMapType];
                        },
                        getSelectedMapType = function () {
                            console.log("getSelectedMapType : " + selectedMapType);
                            return mapTypes[selectedMapType];
                        };
                    return {
                        getMapTypes: getMapTypes,
                        getCurrentMapType : getMapType,
                        setCurrentMapType : setMapType,
                        getPreviousMapType : getPreviousMapType,
                        getSelectedMapType : getSelectedMapType,
                        getMapTypeKey : getMapTypeKey,
                        getMapRestUrl : getMapRestUrl,
                        getSpecificMapType : getSpecificMapType
                    };
                }).

                factory("StompEventHandlerService", function () {
                    var getEventDct = function () {
                        return eventDct;
                    },

                        addEvent = function (evt, handler) {
                            eventDct[evt] = handler;
                        },

                        getHandler = function (evt) {
                            return eventDct[evt];
                        };
                    return {
                        getEventDct : getEventDct,
                        addEvent : addEvent,
                        getHandler : getHandler
                    };
                }).

                factory("GoogleQueryService", function ($rootScope) {
                    googleQueryDct.rootScope = $rootScope;
                    var getRootScope = function () {
                        return googleQueryDct.rootScope;
                    },
                        getQueryDestinationDialogScope = function (mapsys) {
                            var elemID = 'DestWndDialogNode',
                                e = document.getElementById(elemID),
                                scope = angular.element(e).scope();
                            return scope;
                        },

                        getPusherDialogScope = function () {
                            var elemID = 'PusherChannelDialog',
                                e = document.getElementById(elemID),
                                scope = angular.element(e).scope();
                            return scope;
                        },

                        setDialogVisibility = function (tf) {
                            var e = document.getElementById('Verbage'),
                                scope = angular.element(e).scope(),
                                previousVisibility = scope.VerbVis;
                            scope.VerbVis = tf ? 'flex' : 'none';
                            if (tf === false) {
                                angular.element(e).css({'display' : 'none'});
                            }
                            return previousVisibility;
                        },

                        getQueryDct = function () {
                            return googleQueryDct;
                        },
                        setQuery = function (q) {
                            // alert('setQuery' + q);
                            googleQueryDct.query = q;
                        };
                    return {
                        getQueryDct: getQueryDct,
                        setQuery : setQuery,
                        getQueryDestinationDialogScope : getQueryDestinationDialogScope,
                        getPusherDialogScope : getPusherDialogScope,
                        setDialogVisibility : setDialogVisibility,
                        getRootScope : getRootScope
                    };
                }).

                value('linkrScopes', {
                    scopes : [],
                    addScope : function (s) {
                        this.scopes.push(s);
                    },
                    getScopes : function () {
                        return this.scopes;
                    }
                }).

                factory("LinkrService", ['$rootScope', 'linkrScopes', function ($rootScope, linkrScopes) {
                    var hideLinkr,
                        showLinkr,
                        addScope;

                    addScope = function (scope) {
                        linkrScopes.addScope(scope);
                    };
                    hideLinkr = function () {
                        var data = {'visibility' : 'none'},
                            scp = linkrScopes.getScopes()[0];
                        if (scp) {
                            scp.$broadcast('displayLinkerEvent', data);
                        }
                    };
                    showLinkr = function () {
                        var data = {'visibility' : 'block'},
                            scp;
                        angular.forEach(linkrScopes.getScopes(), function(scp){
                            if (scp) {
                                scp.$broadcast('displayLinkerEvent', data);
                            }
                        });
                    };

                    return {addScope : addScope, hideLinkr: hideLinkr, showLinkr: showLinkr};
                }]).

                factory("MapControllerService", function ($rootScope) {
                    var getController = function () {
                        return MapCtrl;
                    };

                    return {getController: getController};
                });

            App.directive('autoFocus', function ($timeout) {
                return {
                    restrict: 'AC',
                    link: function (locscope, locelement) {
                        console.log("directive autoFocus");
                        $timeout(function () {
                            locelement[0].focus();
                        }, 0);
                    }
                };
            });
            App.directive('ngEnter', function () {
                return function (scope, element, attrs) {
                    element.bind("keydown keypress", function (event) {
                        if (event.which === 13) {
                            scope.$apply(function () {
                                scope.$eval(attrs.ngEnter);
                            });

                            event.preventDefault();
                        }
                    });
                };
            });

            function startAllControllers() {
                var $inj = angular.injector(['app']),
                    $q = $inj.get('$q');
                deferred = $q.defer();
                AppController.start(App, portalForSearch);
                return deferred.promise;
            }
            promise = startAllControllers()
                .then(function () {

                    // need to bootstrap angular since we wait for dojo/DOM to load
                    angular.bootstrap(document.body, ['app']);

                    console.log("url is " + location.search);
                    isNewAgoWindow = MLConfig.testUrlArgs();
                    MLConfig.setDestinationPreference('New Pop-up Window');
                    if (isNewAgoWindow) {
                        maphost = MLConfig.maphost();
                        console.log('maphost : ' + maphost);

                        $inj = angular.injector(['app']);
                        serv = $inj.get('CurrentMapTypeService');
                        serv.setCurrentMapType(mapRestUrlToType[maphost]);
                        console.log('maptype' + mapRestUrlToType[maphost]);

                        if (maphost === 'GoogleMap') {
                            gmquery = MLConfig.getQueryFromUrl();
                            searchService = $inj.get('GoogleQueryService');
                            searchService.setQuery(gmquery);
                        }

                        MasherCtrl.startMapSystem();
                        TabsCtrl.forceMapSystem(maphost);
                        MLConfig.setHideWebSiteOnStartup(true);
                        // MasherCtrl.startMapSystem();
                        // SpaCtrl.hideWebsite();
                    }
                });
            return App;
        }

        return { start: init };

    });

}());

// }).call(this);
<|endoftext|>


<commit_before>import { resolve } from 'path';
import relative from 'require-relative';
import handleError from './handleError';
import SOURCEMAPPING_URL from './sourceMappingUrl.js';

const rollup = require( '../dist/rollup.js' ); // TODO make this an import, somehow

import { install as installSourcemapSupport } from 'source-map-support';
installSourcemapSupport();

// stderr to stderr to keep `rollup main.js > bundle.js` from breaking
const stderr = console.error.bind( console ); // eslint-disable-line no-console

export default function runRollup ( command ) {
	if ( command._.length > 1 ) {
		handleError({ code: 'ONE_AT_A_TIME' });
	}

	if ( command._.length === 1 ) {
		if ( command.input ) {
			handleError({ code: 'DUPLICATE_IMPORT_OPTIONS' });
		}

		command.input = command._[0];
	}

	if ( command.environment ) {
		command.environment.split( ',' ).forEach( pair => {
			const index = pair.indexOf( ':' );
			if ( ~index ) {
				process.env[ pair.slice( 0, index ) ] = pair.slice( index + 1 );
			} else {
				process.env[ pair ] = true;
			}
		});
	}

	let config = command.config === true ? 'rollup.config.js' : command.config;

	if ( config ) {
		config = resolve( config );

		rollup.rollup({
			entry: config,
			onwarn: message => {
				if ( /Treating .+ as external dependency/.test( message ) ) return;
				stderr( message );
			}
		}).then( bundle => {
			const { code } = bundle.generate({
				format: 'cjs'
			});

			// temporarily override require
			var defaultLoader = require.extensions[ '.js' ];
			require.extensions[ '.js' ] = ( m, filename ) => {
				if ( filename === config ) {
					m._compile( code, filename );
				} else {
					defaultLoader( m, filename );
				}
			};

			try {
				const options = require( resolve( config ) );
				if ( Object.keys( options ).length === 0 ) {
					handleError({ code: 'MISSING_CONFIG' });
				}
				execute( options, command );
				require.extensions[ '.js' ] = defaultLoader;
			} catch ( err ) {
				handleError( err );
			}
		})
		.catch( stderr );
	} else {
		execute( {}, command );
	}
}

const equivalents = {
	banner: 'banner',
	footer: 'footer',
	format: 'format',
	globals: 'globals',
	id: 'moduleId',
	indent: 'indent',
	input: 'entry',
	intro: 'intro',
	name: 'moduleName',
	output: 'dest',
	outro: 'outro',
	sourcemap: 'sourceMap',
	treeshake: 'treeshake'
};

function execute ( options, command ) {
	let external = ( options.external || [] )
		.concat( command.external ? command.external.split( ',' ) : []  );

	if ( command.globals ) {
		let globals = Object.create( null );

		command.globals.split( ',' ).forEach( str => {
			const names = str.split( ':' );
			globals[ names[0] ] = names[1];

			// Add missing Module IDs to external.
			if ( external.indexOf( names[0] ) === -1 ) {
				external.push( names[0] );
			}
		});

		command.globals = globals;
	}

	options.onwarn = options.onwarn || stderr;

	options.external = external;

	options.noConflict = command.conflict === false;
	delete command.conflict;

	// Use any options passed through the CLI as overrides.
	Object.keys( equivalents ).forEach( cliOption => {
		if ( command.hasOwnProperty( cliOption ) ) {
			options[ equivalents[ cliOption ] ] = command[ cliOption ];
		}
	});

	try {
		if ( command.watch ) {
			if ( !options.entry || ( !options.dest && !options.targets ) ) {
				handleError({ code: 'WATCHER_MISSING_INPUT_OR_OUTPUT' });
			}

			try {
				const watch = relative( 'rollup-watch', process.cwd() );
				const watcher = watch( rollup, options );

				watcher.on( 'event', event => {
					switch ( event.code ) {
						case 'STARTING':
							stderr( 'checking rollup-watch version...' );
							break;

						case 'BUILD_START':
							stderr( 'bundling...' );
							break;

						case 'BUILD_END':
							stderr( 'bundled in ' + event.duration + 'ms. Watching for changes...' );
							break;

						case 'ERROR':
							handleError( event.error, true );
							break;

						default:
							stderr( 'unknown event', event );
					}
				});
			} catch ( err ) {
				if ( err.code === 'MODULE_NOT_FOUND' ) {
					err.code = 'ROLLUP_WATCH_NOT_INSTALLED';
				}

				handleError( err );
			}
		} else {
			bundle( options ).catch( handleError );
		}
	} catch ( err ) {
		handleError( err );
	}
}

function clone ( object ) {
	return assign( {}, object );
}

function assign ( target, source ) {
	Object.keys( source ).forEach( key => {
		target[ key ] = source[ key ];
	});
	return target;
}

function bundle ( options ) {
	if ( !options.entry ) {
		handleError({ code: 'MISSING_INPUT_OPTION' });
	}

	return rollup.rollup( options ).then( bundle => {
		if ( options.dest ) {
			return bundle.write( options );
		}

		if ( options.targets ) {
			let result = null;

			options.targets.forEach( target => {
				result = bundle.write( assign( clone( options ), target ) );
			});

			return result;
		}

		if ( options.sourceMap && options.sourceMap !== 'inline' ) {
			handleError({ code: 'MISSING_OUTPUT_OPTION' });
		}

		let { code, map } = bundle.generate( options );

		if ( options.sourceMap === 'inline' ) {
			code += `\n//# ${SOURCEMAPPING_URL}=${map.toUrl()}`;
		}

		process.stdout.write( code );
	});
}
<commit_msg>Handle options.external is a function.<commit_after>import { resolve } from 'path';
import relative from 'require-relative';
import handleError from './handleError';
import SOURCEMAPPING_URL from './sourceMappingUrl.js';

const rollup = require( '../dist/rollup.js' ); // TODO make this an import, somehow

import { install as installSourcemapSupport } from 'source-map-support';
installSourcemapSupport();

// stderr to stderr to keep `rollup main.js > bundle.js` from breaking
const stderr = console.error.bind( console ); // eslint-disable-line no-console

export default function runRollup ( command ) {
	if ( command._.length > 1 ) {
		handleError({ code: 'ONE_AT_A_TIME' });
	}

	if ( command._.length === 1 ) {
		if ( command.input ) {
			handleError({ code: 'DUPLICATE_IMPORT_OPTIONS' });
		}

		command.input = command._[0];
	}

	if ( command.environment ) {
		command.environment.split( ',' ).forEach( pair => {
			const index = pair.indexOf( ':' );
			if ( ~index ) {
				process.env[ pair.slice( 0, index ) ] = pair.slice( index + 1 );
			} else {
				process.env[ pair ] = true;
			}
		});
	}

	let config = command.config === true ? 'rollup.config.js' : command.config;

	if ( config ) {
		config = resolve( config );

		rollup.rollup({
			entry: config,
			onwarn: message => {
				if ( /Treating .+ as external dependency/.test( message ) ) return;
				stderr( message );
			}
		}).then( bundle => {
			const { code } = bundle.generate({
				format: 'cjs'
			});

			// temporarily override require
			var defaultLoader = require.extensions[ '.js' ];
			require.extensions[ '.js' ] = ( m, filename ) => {
				if ( filename === config ) {
					m._compile( code, filename );
				} else {
					defaultLoader( m, filename );
				}
			};

			try {
				const options = require( resolve( config ) );
				if ( Object.keys( options ).length === 0 ) {
					handleError({ code: 'MISSING_CONFIG' });
				}
				execute( options, command );
				require.extensions[ '.js' ] = defaultLoader;
			} catch ( err ) {
				handleError( err );
			}
		})
		.catch( stderr );
	} else {
		execute( {}, command );
	}
}

const equivalents = {
	banner: 'banner',
	footer: 'footer',
	format: 'format',
	globals: 'globals',
	id: 'moduleId',
	indent: 'indent',
	input: 'entry',
	intro: 'intro',
	name: 'moduleName',
	output: 'dest',
	outro: 'outro',
	sourcemap: 'sourceMap',
	treeshake: 'treeshake'
};

function execute ( options, command ) {
	let external = command.external ?
		typeof options.external === 'function' ?
		((fn, a) => {
			return function (id) {
				return fn() || a.indexOf(id) !== -1;
			};
		})(options.external, command.external.split(',')) :
		(options.external || []).concat(command.external.split(',')) :
		options.external;

	if ( command.globals ) {
		let globals = Object.create( null );

		command.globals.split( ',' ).forEach( str => {
			const names = str.split( ':' );
			globals[ names[0] ] = names[1];

			// Add missing Module IDs to external.
			if ( external.indexOf( names[0] ) === -1 ) {
				external.push( names[0] );
			}
		});

		command.globals = globals;
	}

	options.onwarn = options.onwarn || stderr;

	options.external = external;

	options.noConflict = command.conflict === false;
	delete command.conflict;

	// Use any options passed through the CLI as overrides.
	Object.keys( equivalents ).forEach( cliOption => {
		if ( command.hasOwnProperty( cliOption ) ) {
			options[ equivalents[ cliOption ] ] = command[ cliOption ];
		}
	});

	try {
		if ( command.watch ) {
			if ( !options.entry || ( !options.dest && !options.targets ) ) {
				handleError({ code: 'WATCHER_MISSING_INPUT_OR_OUTPUT' });
			}

			try {
				const watch = relative( 'rollup-watch', process.cwd() );
				const watcher = watch( rollup, options );

				watcher.on( 'event', event => {
					switch ( event.code ) {
						case 'STARTING':
							stderr( 'checking rollup-watch version...' );
							break;

						case 'BUILD_START':
							stderr( 'bundling...' );
							break;

						case 'BUILD_END':
							stderr( 'bundled in ' + event.duration + 'ms. Watching for changes...' );
							break;

						case 'ERROR':
							handleError( event.error, true );
							break;

						default:
							stderr( 'unknown event', event );
					}
				});
			} catch ( err ) {
				if ( err.code === 'MODULE_NOT_FOUND' ) {
					err.code = 'ROLLUP_WATCH_NOT_INSTALLED';
				}

				handleError( err );
			}
		} else {
			bundle( options ).catch( handleError );
		}
	} catch ( err ) {
		handleError( err );
	}
}

function clone ( object ) {
	return assign( {}, object );
}

function assign ( target, source ) {
	Object.keys( source ).forEach( key => {
		target[ key ] = source[ key ];
	});
	return target;
}

function bundle ( options ) {
	if ( !options.entry ) {
		handleError({ code: 'MISSING_INPUT_OPTION' });
	}

	return rollup.rollup( options ).then( bundle => {
		if ( options.dest ) {
			return bundle.write( options );
		}

		if ( options.targets ) {
			let result = null;

			options.targets.forEach( target => {
				result = bundle.write( assign( clone( options ), target ) );
			});

			return result;
		}

		if ( options.sourceMap && options.sourceMap !== 'inline' ) {
			handleError({ code: 'MISSING_OUTPUT_OPTION' });
		}

		let { code, map } = bundle.generate( options );

		if ( options.sourceMap === 'inline' ) {
			code += `\n//# ${SOURCEMAPPING_URL}=${map.toUrl()}`;
		}

		process.stdout.write( code );
	});
}<|endoftext|>


<commit_before>(function($) {
    $.Chat = function(element) {
        var base = this;

        base.init = function() {
            var board      = $(element);
            base.input     = board.find('input[type=text]');
            base.inbox     = board.find('.inbox');
            base.chan      = board.attr('data-chat');
            base.cursor    = base.findCursor();
            base.sleepTime = 500;

            board.find('p').click(base.norloge);
            board.find('form').submit(base.postMessage);
            board.find('.board-right').each(base.norlogize);
            board.find('time').live('mouseenter', base.highlitizer)
                              .live('mouseleave', base.deshighlitizer);
            base.poll();
        };

        base.findCursor = function() {
            var first = base.inbox.find("p:first");
            if (first.length > 0) {
                var id = first[0].id;
                return (id.slice(0,6) == "board-") ? id.slice(6) : null;
            }
            return null;
        };

        base.postMessage = function() {
            var form = $(this);
            var data = form.serialize();
            base.input.val("").select();
            $.ajax({
                url: form.attr('action'),
                data: data,
                type: 'POST',
                dataType: 'script'
            });
            return false;
        };

        base.norloge = function() {
            var time = $(this).find('.norloge').text();
            base.input.val(function(index,value) {
                return  time + ' ' + value;
            }).focus();
        };

        base.norlogize = function() {
            this.innerHTML = this.innerHTML.replace(/[0-2][0-9]:[0-6][0-9](:[0-6][0-9])?([⁰¹²³⁴⁵⁶⁷⁸⁹]+|[:\^][0-9]+)?/g, '<time>$&</time>');
        };

        base.highlitizer = function() {
            var time = $(this).text();
            base.inbox.find("time").filter(function() {
                return $(this).text() == time;
            }).addClass("highlighted");
        }

        base.deshighlitizer = function() {
            console.log("deshighlitizer");
            base.inbox.find("time.highlighted").removeClass("highlighted");
        }

        /* Open a connection to the server, waiting for the next message */
        base.poll = function() {
            var args = {};
            if (base.cursor) {
                args.cursor = base.cursor;
            }
            $.ajax({
                url: "/b/" + base.chan,
                type: "GET",
                dataType: "json",
                data: $.param(args),
                success: base.onSuccess,
                error: base.onError
            });
        };

        /* We got one message (or more)! */
        base.onSuccess = function(response) {
            try {
                base.newMessages(response);
                base.sleepTime = 500;
                setTimeout(base.poll, 0);
            } catch (e) {
                base.onError();
            }
        };

        /* If we have an error, wait longer and longer between calls */
        base.onError = function() {
            base.sleepTime *= 2;
            setTimeout(base.poll, base.sleepTime);
        };

        /* Dispatch messages to their callbacks */
        base.newMessages = function(messages) {
            var message, existing, method;
            if (messages) {
                base.cursor = messages[messages.length - 1].id;
                for (var i = 0; i < messages.length; i += 1) {
                    message  = messages[i];
                    existing = $("#board_" + message.id);
                    // Anti-duplicate protection
                    if (existing.length > 0) {
                        return ;
                    }
                    method  = 'on_' + message.kind;
                    if (base[method]) {
                        base.inbox.prepend(message.msg)
                                  .children('p:first').click(base.norloge);
                        base[method](message.msg);
                    }
                    base.inbox.find('.board-right:first').each(base.norlogize);
                }
            }
        };

        /* Callback for chat */
        base.on_chat = function() {};

        /* Callback for indication */
        base.on_indication = function() {};

        /* Callback for vote */
        base.on_vote = function() {};

        /* Callback for submission */
        base.on_submission = function(message) {
            $.noticeAdd({text: message, stay: true});
        };

        /* Callback for moderation */
        base.on_moderation = function(message) {
            $.noticeAdd({text: message, stay: true});
        };

        /* Callback for locking */
        base.on_locking = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".clear").each(function() {
                $('.locked').removeClass('locked');
                $.noticeAdd({text: message});
            });
            el.find(".link").each(function() {
                var id = $(this).attr('data-id');
                $('#link_' + id).addClass('locked');
            });
            el.find(".paragraph").each(function() {
                var id = $(this).attr('data-id');
                $('#paragraph_' + id).addClass('locked');
            });
        };

        /* Callback for creation */
        base.on_creation = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".link").each(function() {
                var id = $(this).attr('data-id');
                var html = '
' + $(this).html() + '
';
                $('#links').append(html);
                $('#link_' + id).editionInPlace();
            });
            el.find(".paragraph").each(function() {
                var id = $(this).attr('data-id');
                var after = $(this).attr('data-after');
                var html = '
' + $(this).html() + '
';
                $('#paragraph_' + after).after(html);
                $('#paragraph_' + id).editionInPlace();
            });
        };

        /* Callback for edition */
        base.on_edition = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".news").each(function() {
                $('#news_header').html($(this).clone());
            });
            el.find(".link").each(function() {
                $('#link_' + $(this).attr('data-id')).html($(this).html());
            });
            el.find(".paragraph").each(function() {
                $('#paragraph_' + $(this).attr('data-id')).html($(this).html());
            });
        };

        /* Callback for deletion */
        base.on_deletion = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".link").each(function() {
                $('#link_' + $(this).attr('data-id')).remove();
            });
            el.find(".paragraph").each(function() {
                $('#paragraph_' + $(this).attr('data-id')).remove();
            });
        };

        base.init();
    };

    $.fn.chat = function() {
        return this.each(function() {
            (new $.Chat(this));
        });
    };
})(jQuery);
<commit_msg>Oops, I forgot a console.log<commit_after>(function($) {
    $.Chat = function(element) {
        var base = this;

        base.init = function() {
            var board      = $(element);
            base.input     = board.find('input[type=text]');
            base.inbox     = board.find('.inbox');
            base.chan      = board.attr('data-chat');
            base.cursor    = base.findCursor();
            base.sleepTime = 500;

            board.find('p').click(base.norloge);
            board.find('form').submit(base.postMessage);
            board.find('.board-right').each(base.norlogize);
            board.find('time').live('mouseenter', base.highlitizer)
                              .live('mouseleave', base.deshighlitizer);
            base.poll();
        };

        base.findCursor = function() {
            var first = base.inbox.find("p:first");
            if (first.length > 0) {
                var id = first[0].id;
                return (id.slice(0,6) == "board-") ? id.slice(6) : null;
            }
            return null;
        };

        base.postMessage = function() {
            var form = $(this);
            var data = form.serialize();
            base.input.val("").select();
            $.ajax({
                url: form.attr('action'),
                data: data,
                type: 'POST',
                dataType: 'script'
            });
            return false;
        };

        base.norloge = function() {
            var time = $(this).find('.norloge').text();
            base.input.val(function(index,value) {
                return  time + ' ' + value;
            }).focus();
        };

        base.norlogize = function() {
            this.innerHTML = this.innerHTML.replace(/[0-2][0-9]:[0-6][0-9](:[0-6][0-9])?([⁰¹²³⁴⁵⁶⁷⁸⁹]+|[:\^][0-9]+)?/g, '<time>$&</time>');
        };

        base.highlitizer = function() {
            var time = $(this).text();
            base.inbox.find("time").filter(function() {
                return $(this).text() == time;
            }).addClass("highlighted");
        }

        base.deshighlitizer = function() {
            base.inbox.find("time.highlighted").removeClass("highlighted");
        }

        /* Open a connection to the server, waiting for the next message */
        base.poll = function() {
            var args = {};
            if (base.cursor) {
                args.cursor = base.cursor;
            }
            $.ajax({
                url: "/b/" + base.chan,
                type: "GET",
                dataType: "json",
                data: $.param(args),
                success: base.onSuccess,
                error: base.onError
            });
        };

        /* We got one message (or more)! */
        base.onSuccess = function(response) {
            try {
                base.newMessages(response);
                base.sleepTime = 500;
                setTimeout(base.poll, 0);
            } catch (e) {
                base.onError();
            }
        };

        /* If we have an error, wait longer and longer between calls */
        base.onError = function() {
            base.sleepTime *= 2;
            setTimeout(base.poll, base.sleepTime);
        };

        /* Dispatch messages to their callbacks */
        base.newMessages = function(messages) {
            var message, existing, method;
            if (messages) {
                base.cursor = messages[messages.length - 1].id;
                for (var i = 0; i < messages.length; i += 1) {
                    message  = messages[i];
                    existing = $("#board_" + message.id);
                    // Anti-duplicate protection
                    if (existing.length > 0) {
                        return ;
                    }
                    method  = 'on_' + message.kind;
                    if (base[method]) {
                        base.inbox.prepend(message.msg)
                                  .children('p:first').click(base.norloge);
                        base[method](message.msg);
                    }
                    base.inbox.find('.board-right:first').each(base.norlogize);
                }
            }
        };

        /* Callback for chat */
        base.on_chat = function() {};

        /* Callback for indication */
        base.on_indication = function() {};

        /* Callback for vote */
        base.on_vote = function() {};

        /* Callback for submission */
        base.on_submission = function(message) {
            $.noticeAdd({text: message, stay: true});
        };

        /* Callback for moderation */
        base.on_moderation = function(message) {
            $.noticeAdd({text: message, stay: true});
        };

        /* Callback for locking */
        base.on_locking = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".clear").each(function() {
                $('.locked').removeClass('locked');
                $.noticeAdd({text: message});
            });
            el.find(".link").each(function() {
                var id = $(this).attr('data-id');
                $('#link_' + id).addClass('locked');
            });
            el.find(".paragraph").each(function() {
                var id = $(this).attr('data-id');
                $('#paragraph_' + id).addClass('locked');
            });
        };

        /* Callback for creation */
        base.on_creation = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".link").each(function() {
                var id = $(this).attr('data-id');
                var html = '
' + $(this).html() + '
';
                $('#links').append(html);
                $('#link_' + id).editionInPlace();
            });
            el.find(".paragraph").each(function() {
                var id = $(this).attr('data-id');
                var after = $(this).attr('data-after');
                var html = '
' + $(this).html() + '
';
                $('#paragraph_' + after).after(html);
                $('#paragraph_' + id).editionInPlace();
            });
        };

        /* Callback for edition */
        base.on_edition = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".news").each(function() {
                $('#news_header').html($(this).clone());
            });
            el.find(".link").each(function() {
                $('#link_' + $(this).attr('data-id')).html($(this).html());
            });
            el.find(".paragraph").each(function() {
                $('#paragraph_' + $(this).attr('data-id')).html($(this).html());
            });
        };

        /* Callback for deletion */
        base.on_deletion = function(message) {
            var el = base.inbox.find("p:first");
            el.find(".link").each(function() {
                $('#link_' + $(this).attr('data-id')).remove();
            });
            el.find(".paragraph").each(function() {
                $('#paragraph_' + $(this).attr('data-id')).remove();
            });
        };

        base.init();
    };

    $.fn.chat = function() {
        return this.each(function() {
            (new $.Chat(this));
        });
    };
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Builds up the interface for tirade, needs jquery and more than one jquery plugin
 */

ChiliBook.recipeFolder = 'javascripts/syntax/'

$(function() {
  // Auto preview
  $.fn.preview = function() {
    var url = $.string( $(this).attr('action')  )
      .sub(/\.js$/, function(match) { return "/preview"+match }).str;
    var form = $(this);
    var fetchPreview = function(data) {
      $.ajax({
        url: url,
        type: 'POST',
        data: data || form.formSerialize()
      });
    };
    Toolbox.scroller().one('prev', function() {
      fetchPreview(form.find('input[name=authenticity_token],input[name=_method],input[name=context_page_id]').serialize()); /* reset old state */
    });

    form.formWatch({callback: fetchPreview});
  }

  // Apply roles classes from cookie (for body etc.)
  $.fn.applyRoles = function() {
    var e = $(this);
    if ($.cookie("roles")) {
      $(e[0].className.split(/ /)).each(function(i,cls) {
        if (cls.match(/role_\S*/))
          e.removeClass(cls)
      });
      $($.cookie("roles").split(/&/)).each(function(i,role) {
        e.addClass('role_' + role);
      });
      e.addClass('cookie_roles');
    }
    return(e);
  }

  $.fn.surrounds = function(position) {
    me = $(this);
    meoff = me.offset();
    return(
        meoff.top < position.top && meoff.left < position.left &&
        meoff.top + me.height() > position.top &&
        meoff.left + me.width() > position.left
    );
  }

  $.fn.beBusy = function(message) {
    var div = $('
')
      .addClass('busy')
      .hide();

    $('')
      .addClass('message')
      .html(message || 'Loading')
      .appendTo(div);
    $('div.busy', this).remove();

    return div.appendTo(this).fadeIn(500);
  }
  $.fn.unBusy = function() {
    return $('div.busy', this).remove();
  }

  $.ajaxSetup({
    dataType: 'script',
    beforeSend: function(request) {
      request.setRequestHeader("Tirade-Page", $('div.page').resourceId() )
    }
  });

  $.metadata.setType( 'attr', 'data' );

  $('a.login').livequery(function() { $(this).useToolbox(); });
  $('a.with_toolbox').livequery(function() { $(this).useToolbox(); });

  $('code.html').livequery(function() { $(this).chili() });
  $('code.liquid').livequery(function() { $(this).chili() });

  /* Resourceful Links in Toolbox */
  $('ul.list > li > a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  $('ul.list > li > a.index').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  $('ul.list > li > a.edit').livequery(function() { $(this).uiIcon('pencil').useToolbox(); });
  $('dd.record > a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.new').livequery(function() { $(this).uiIcon('plus').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.edit').livequery(function() { $(this).uiIcon('pencil').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.destroy').livequery(function() { $(this).uiIcon('trash').useToolbox(); });
  //$('div#toolbox_sidebar a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  $('div#toolbox > div.body > div.content ul.tree.tree_root').livequery(function() {
    $('div.node:not(:has(span.handle)):not(.page)', this).livequery( function() {
      $(this).append( $('drag').addClass('handle'))
    });
  });

  /*
   * Toolbox Drag+Drop
   */
  $('ul.list.records > li, dl > di > dd.record').livequery(function() {
    $(this)
    .addClass('ui-widget-content ui-corner-all ui-helper-clearfix')
    .draggable({
      helper: 'clone',
      zIndex: 9000,
      appendTo: 'body',
      scroll: true,
      cursor: 'crosshair',
      cursorAt: {top: -1, left: -1},
      drag: function(e,ui) {
        if (Toolbox.surrounds(ui.absolutePosition)) {
          Toolbox.beExclusiveDroppable();
          Toolbox.unGhost();
        } else {
          Toolbox.unExclusiveDroppable();
          Toolbox.beGhost();
        };
      },
      stop: function(e,ui) {
        Toolbox.unExclusiveDroppable();
        Toolbox.unGhost();
      }
    });
  });

  $('ul.list, dl.list').livequery(function() { $(this).listOfItems() });

  /*
   * Clipboard
   */
  $('div#toolbox_sidebar ul.clipboard').livequery(function() {
    var list = $(this);
    list.droppable({
      accept: function(draggable) {
        return(
          draggable.is('li, dd.record') &&
          draggable.parent()[0] != list[0]
        );
      },
      hoverClass: 'drop-hover',
      activeClass: 'active-droppable',
      greedy: true,
      tolerance: 'touch',
      drop: function(e,ui) {
        $.ajax({
          url: Routing.clipboard_url(),
          data: {id: $(ui.draggable).resourceIdentifier()},
          type: 'POST'
        });
      }
    });
  });
  $('div#toolbox_sidebar ul.clipboard li').livequery(function() {
    var item = $(this);
    item.find('a.association').remove();
    $.ui.button({icon: 'circle-close', text: 'remove', class: 'association remove'})
      .click(function(event) {
        item.remove();
        $.ajax({
          url: Routing.clipboard_url(),
          data: {id: item.resourceIdentifier()},
          type: 'DELETE'
        });
      })
      .appendTo(item);
  });
  $('body').applyRoles();

  /* TODO: move to acts_as_custom_configurable */
  $('form ul.define_options').livequery(function() {
    var list = $(this);
    $.ui.button({icon: 'circle-plus', text: 'remove', class: 'add option'})
      .click(function() {
        list.find('li:last').clone().removeClass('dummy').appendTo(list);
        return false;
      })
      .prependTo(list);
  });
  $('form ul.define_options li:not(.dummy)').livequery(function() {
    var item = $(this);
    $.ui.button({icon: 'circle-close', text: 'remove', class: 'association remove'})
      .click(function() { item.remove(); return false; })
      .prependTo(item);
  });

});
<commit_msg>add ui-state-highlight to all a.show and a.index so that the icons are visible again (hover state from items are applied too much)<commit_after>/*
 * Builds up the interface for tirade, needs jquery and more than one jquery plugin
 */

ChiliBook.recipeFolder = 'javascripts/syntax/'

$(function() {
  // Auto preview
  $.fn.preview = function() {
    var url = $.string( $(this).attr('action')  )
      .sub(/\.js$/, function(match) { return "/preview"+match }).str;
    var form = $(this);
    var fetchPreview = function(data) {
      $.ajax({
        url: url,
        type: 'POST',
        data: data || form.formSerialize()
      });
    };
    Toolbox.scroller().one('prev', function() {
      fetchPreview(form.find('input[name=authenticity_token],input[name=_method],input[name=context_page_id]').serialize()); /* reset old state */
    });

    form.formWatch({callback: fetchPreview});
  }

  // Apply roles classes from cookie (for body etc.)
  $.fn.applyRoles = function() {
    var e = $(this);
    if ($.cookie("roles")) {
      $(e[0].className.split(/ /)).each(function(i,cls) {
        if (cls.match(/role_\S*/))
          e.removeClass(cls)
      });
      $($.cookie("roles").split(/&/)).each(function(i,role) {
        e.addClass('role_' + role);
      });
      e.addClass('cookie_roles');
    }
    return(e);
  }

  $.fn.surrounds = function(position) {
    me = $(this);
    meoff = me.offset();
    return(
        meoff.top < position.top && meoff.left < position.left &&
        meoff.top + me.height() > position.top &&
        meoff.left + me.width() > position.left
    );
  }

  $.fn.beBusy = function(message) {
    var div = $('
')
      .addClass('busy')
      .hide();

    $('')
      .addClass('message')
      .html(message || 'Loading')
      .appendTo(div);
    $('div.busy', this).remove();

    return div.appendTo(this).fadeIn(500);
  }
  $.fn.unBusy = function() {
    return $('div.busy', this).remove();
  }

  $.ajaxSetup({
    dataType: 'script',
    beforeSend: function(request) {
      request.setRequestHeader("Tirade-Page", $('div.page').resourceId() )
    }
  });

  $.metadata.setType( 'attr', 'data' );

  $('a.login').livequery(function() { $(this).useToolbox(); });
  $('a.with_toolbox').livequery(function() { $(this).useToolbox(); });

  $('code.html').livequery(function() { $(this).chili() });
  $('code.liquid').livequery(function() { $(this).chili() });

  /* Resourceful Links in Toolbox */
  $('ul.list > li > a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').addClass('ui-state-highlight').useToolbox(); });
  $('ul.list > li > a.index').livequery(function() { $(this).uiIcon('circle-triangle-e').addClass('ui-state-highlight').useToolbox(); });
  $('ul.list > li > a.edit').livequery(function() { $(this).uiIcon('pencil').useToolbox(); });
  $('dd.record > a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.new').livequery(function() { $(this).uiIcon('plus').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.edit').livequery(function() { $(this).uiIcon('pencil').useToolbox(); });
  //$('div#toolbox > div.body > div.content > div.frame a.destroy').livequery(function() { $(this).uiIcon('trash').useToolbox(); });
  //$('div#toolbox_sidebar a.show').livequery(function() { $(this).uiIcon('circle-triangle-e').useToolbox(); });
  $('div#toolbox > div.body > div.content ul.tree.tree_root').livequery(function() {
    $('div.node:not(:has(span.handle)):not(.page)', this).livequery( function() {
      $(this).append( $('drag').addClass('handle'))
    });
  });

  /*
   * Toolbox Drag+Drop
   */
  $('ul.list.records > li, dl > di > dd.record').livequery(function() {
    $(this)
    .addClass('ui-widget-content ui-corner-all ui-helper-clearfix')
    .draggable({
      helper: 'clone',
      zIndex: 9000,
      appendTo: 'body',
      scroll: true,
      cursor: 'crosshair',
      cursorAt: {top: -1, left: -1},
      drag: function(e,ui) {
        if (Toolbox.surrounds(ui.absolutePosition)) {
          Toolbox.beExclusiveDroppable();
          Toolbox.unGhost();
        } else {
          Toolbox.unExclusiveDroppable();
          Toolbox.beGhost();
        };
      },
      stop: function(e,ui) {
        Toolbox.unExclusiveDroppable();
        Toolbox.unGhost();
      }
    });
  });

  $('ul.list, dl.list').livequery(function() { $(this).listOfItems() });

  /*
   * Clipboard
   */
  $('div#toolbox_sidebar ul.clipboard').livequery(function() {
    var list = $(this);
    list.droppable({
      accept: function(draggable) {
        return(
          draggable.is('li, dd.record') &&
          draggable.parent()[0] != list[0]
        );
      },
      hoverClass: 'drop-hover',
      activeClass: 'active-droppable',
      greedy: true,
      tolerance: 'touch',
      drop: function(e,ui) {
        $.ajax({
          url: Routing.clipboard_url(),
          data: {id: $(ui.draggable).resourceIdentifier()},
          type: 'POST'
        });
      }
    });
  });
  $('div#toolbox_sidebar ul.clipboard li').livequery(function() {
    var item = $(this);
    item.find('a.association').remove();
    $.ui.button({icon: 'circle-close', text: 'remove', class: 'association remove'})
      .click(function(event) {
        item.remove();
        $.ajax({
          url: Routing.clipboard_url(),
          data: {id: item.resourceIdentifier()},
          type: 'DELETE'
        });
      })
      .appendTo(item);
  });
  $('body').applyRoles();

  /* TODO: move to acts_as_custom_configurable */
  $('form ul.define_options').livequery(function() {
    var list = $(this);
    $.ui.button({icon: 'circle-plus', text: 'remove', class: 'add option'})
      .click(function() {
        list.find('li:last').clone().removeClass('dummy').appendTo(list);
        return false;
      })
      .prependTo(list);
  });
  $('form ul.define_options li:not(.dummy)').livequery(function() {
    var item = $(this);
    $.ui.button({icon: 'circle-close', text: 'remove', class: 'association remove'})
      .click(function() { item.remove(); return false; })
      .prependTo(item);
  });

});
<|endoftext|>


<commit_before>Utils = {
  loadTemplates: function() {
    var templates = {};
    $('*[type="text/x-js-template"]').map(function() {
      var name = $(this).attr('name');
      var source = $(this).html().replace('>', '>');
      if(name.split('/')[1][0] == '_') { Handlebars.registerPartial(name.replace('/', ''), source) }
      templates[name] = Handlebars.compile(source);
    });
    return templates;
  },
  queryString: function(params) {
    if(!params) return '';
    var query = _.compact(_.map(params, function(value, key) { return value ? key + '=' + value : null }));
    return query.length > 0 ? '?' + query.join('&') : '';
  },
  duration: function(started, finished) {
    started  = new Date(started);
    finished = finished ? new Date(finished) : new Date();
    return started ? Math.round((finished - started) / 1000) : 0;
  },
  activateTab: function(element, tab) {
    $('.tabs li', element).removeClass('active');
    $('#tab_' + tab.toLowerCase(), element).addClass('active');
  },
  animated: function(element) {
    return !!element.queue()[0];
  },
  flash: function(element) {
    if(!element.length == 0 && !Utils.animated(element)) {
      Utils._flash(element);
    }
  },
  _flash: function(element) {
    element.effect('highlight', {}, 1000, function () {
      Utils._flash(element)
    });
  },
  unflash: function(element) {
    if(!element.length == 0) {
      element.stop().css({ 'background-color': '', 'background-image': '' });
    }
  },
  filterLog: function(string) {
    // string = Handlebars.Utils.escapeExpression(string);
    string = Utils.foldLog(string);
    string = Deansi.parse(string);
    return string;
  },
  foldLog: function(string) {
    string = Utils.unfoldLog(string);
    var folds = [
      // /(^|<\/div>)(\$ git clone.*\r?\n(?:(Initialized|remote:|Receiving|Resolving).*?\r?\n)*)/m,
      /(^|<\/div>)(\$ git clean.*\r?\n(?:Removing .*\r?\n)+\r?\n*)/m,
      /(^|<\/div>)(\$ git fetch.*\r?\nFrom .*\n.*)\r?\n/m,
      /(^|<\/div>)(\$ bundle install.*\r?\n*(?:(Fetching|Updating|Using|Installing|remote:|Receiving|Resolving).+\r?\n*)*)/m,
      /(^|<\/div>)(\$ rake db:migrate[\s\S]*(?:^== +\w+: migrated \(.*\) =+\r?\n))\r?\n?/m,
      /(^|<\/div>)(\/home\/([^\/]+)\/.rvm\/rubies\/\S*?(ruby|rbx|jruby).*?)\r?\n/m
    ];
    _.each(folds, function(fold) {
      string = string.replace(fold, function() { return arguments[1] + '
' + arguments[2].trim() + '
'; });
    });
    string = string.replace(/([\.-_*SEF]{120})\n?/g, '$1\n')
    return string;
  },
  unfoldLog: function(string) {
    return string.replace(/
([\s\S]*?)<\/div>/mg, '$1\n');
  },
  updateTimes: function(element) {
    $('.timeago', element).timeago();
    $('.duration', element).readableTime();

    if(!Utils._updateTimesInterval) {
      Utils._updateTimesInterval = setInterval(function() { Utils.updateTimes() }, 3000);
    }
  },
  readableTime: function(duration) {
    var days    = Math.floor(duration / 86400)
    var hours   = Math.floor(duration % 86400 / 3600);
    var minutes = Math.floor(duration % 3600 / 60);
    var seconds = duration % 60;

    if(days > 0) {
      return 'more than 24 hrs';
    } else {
      var result = [];
      if(hours   > 0) { result.push(hours + ' hrs'); }
      if(minutes > 0) { result.push(minutes + ' min'); }
      if(seconds > 0) { result.push(seconds + ' sec'); }
      return result.length > 0 ? result.join(' ') : '-';
    }
  },
  updateGithubStats: function(repository, element) {
    if(!window.__TESTING__) {
      $.getJSON('http://github.com/api/v2/json/repos/show/' + repository.get('slug') + '?callback=?', function(data) {
        var url = 'http://github.com/' + repository.get('slug');
        element.find('.watchers').attr('href', url + '/watchers').text(data.repository.watchers);
        element.find('.forks').attr('href', url + '/network').text(data.repository.forks);
      });
    }
  }
}

function trace() {
  try {
    i.dont.exist; // force an exception
  } catch(e) {
    var lines = e.stack.split('\n').slice(2);
    var stack = _.map(lines, function(line) { return line.replace(/^\s*at/, ''); });
    console.log('trace -------------------------------');
    _.each(stack, function(line) { console.log(line); });
  }
}

<commit_msg>let's fold all these log sections<commit_after>Utils = {
  loadTemplates: function() {
    var templates = {};
    $('*[type="text/x-js-template"]').map(function() {
      var name = $(this).attr('name');
      var source = $(this).html().replace('>', '>');
      if(name.split('/')[1][0] == '_') { Handlebars.registerPartial(name.replace('/', ''), source) }
      templates[name] = Handlebars.compile(source);
    });
    return templates;
  },
  queryString: function(params) {
    if(!params) return '';
    var query = _.compact(_.map(params, function(value, key) { return value ? key + '=' + value : null }));
    return query.length > 0 ? '?' + query.join('&') : '';
  },
  duration: function(started, finished) {
    started  = new Date(started);
    finished = finished ? new Date(finished) : new Date();
    return started ? Math.round((finished - started) / 1000) : 0;
  },
  activateTab: function(element, tab) {
    $('.tabs li', element).removeClass('active');
    $('#tab_' + tab.toLowerCase(), element).addClass('active');
  },
  animated: function(element) {
    return !!element.queue()[0];
  },
  flash: function(element) {
    if(!element.length == 0 && !Utils.animated(element)) {
      Utils._flash(element);
    }
  },
  _flash: function(element) {
    element.effect('highlight', {}, 1000, function () {
      Utils._flash(element)
    });
  },
  unflash: function(element) {
    if(!element.length == 0) {
      element.stop().css({ 'background-color': '', 'background-image': '' });
    }
  },
  filterLog: function(string) {
    // string = Handlebars.Utils.escapeExpression(string);
    string = Utils.foldLog(string);
    string = Deansi.parse(string);
    return string;
  },
  foldLog: function(string) {
    string = Utils.unfoldLog(string);
    var folds = [
      // /(^|<\/div>)(\$ git clone.*\r?\n(?:(Initialized|remote:|Receiving|Resolving).*?\r?\n)*)/m,
      /(^|<\/div>)(\$ git clean.*\r?\n(?:Removing .*\r?\n)+\r?\n*)/gm,
      /(^|<\/div>)(\$ git fetch.*\r?\nFrom .*\n.*)\r?\n/gm,
      /(^|<\/div>)(\$ bundle install.*\r?\n*(?:(Fetching|Updating|Using|Installing|remote:|Receiving|Resolving).+\r?\n*)*)/gm,
      /(^|<\/div>)(\$ rake db:migrate[\s\S]*(?:^== +\w+: migrated \(.*\) =+\r?\n))\r?\n?/gm,
      /(^|<\/div>)(\/home\/([^\/]+)\/.rvm\/rubies\/\S*?(ruby|rbx|jruby).*?)\r?\n/gm
    ];
    _.each(folds, function(fold) {
      string = string.replace(fold, function() { return arguments[1] + '
' + arguments[2].trim() + '
'; });
    });
    string = string.replace(/([\.-_*SEF]{120})\n?/g, '$1\n')
    return string;
  },
  unfoldLog: function(string) {
    return string.replace(/
([\s\S]*?)<\/div>/mg, '$1\n');
  },
  updateTimes: function(element) {
    $('.timeago', element).timeago();
    $('.duration', element).readableTime();

    if(!Utils._updateTimesInterval) {
      Utils._updateTimesInterval = setInterval(function() { Utils.updateTimes() }, 3000);
    }
  },
  readableTime: function(duration) {
    var days    = Math.floor(duration / 86400)
    var hours   = Math.floor(duration % 86400 / 3600);
    var minutes = Math.floor(duration % 3600 / 60);
    var seconds = duration % 60;

    if(days > 0) {
      return 'more than 24 hrs';
    } else {
      var result = [];
      if(hours   > 0) { result.push(hours + ' hrs'); }
      if(minutes > 0) { result.push(minutes + ' min'); }
      if(seconds > 0) { result.push(seconds + ' sec'); }
      return result.length > 0 ? result.join(' ') : '-';
    }
  },
  updateGithubStats: function(repository, element) {
    if(!window.__TESTING__) {
      $.getJSON('http://github.com/api/v2/json/repos/show/' + repository.get('slug') + '?callback=?', function(data) {
        var url = 'http://github.com/' + repository.get('slug');
        element.find('.watchers').attr('href', url + '/watchers').text(data.repository.watchers);
        element.find('.forks').attr('href', url + '/network').text(data.repository.forks);
      });
    }
  }
}

function trace() {
  try {
    i.dont.exist; // force an exception
  } catch(e) {
    var lines = e.stack.split('\n').slice(2);
    var stack = _.map(lines, function(line) { return line.replace(/^\s*at/, ''); });
    console.log('trace -------------------------------');
    _.each(stack, function(line) { console.log(line); });
  }
}

<|endoftext|>


<commit_before>Utils = {
  loadTemplates: function() {
    var templates = {};
    $('*[type="text/x-js-template"]').map(function() {
      var name = $(this).attr('name');
      var source = $(this).html().replace('>', '>');
      if(name.split('/')[1][0] == '_') { Handlebars.registerPartial(name.replace('/', ''), source) }
      templates[name] = Handlebars.compile(source);
    });
    return templates;
  },
  queryString: function(params) {
    if(!params) return '';
    var query = _.compact(_.map(params, function(value, key) { return value ? key + '=' + value : null }));
    return query.length > 0 ? '?' + query.join('&') : '';
  },
  duration: function(started, finished) {
    started  = new Date(started);
    finished = finished ? new Date(finished) : new Date();
    return started ? Math.round((finished - started) / 1000) : 0;
  },
  activateTab: function(element, tab) {
    $('.tabs li', element).removeClass('active');
    $('#tab_' + tab.toLowerCase(), element).addClass('active');
  },
  animated: function(element) {
    return !!element.queue()[0];
  },
  flash: function(element) {
    if(!element.length == 0 && !Utils.animated(element)) {
      Utils._flash(element);
    }
  },
  _flash: function(element) {
    element.effect('highlight', {}, 1000, function () {
      Utils._flash(element)
    });
  },
  unflash: function(element) {
    if(!element.length == 0) {
      element.stop().css({ 'background-color': '', 'background-image': '' });
    }
  },
  filterLog: function(string) {
    // string = Handlebars.Utils.escapeExpression(string);
    string = Utils.stripPaths(string);
    string = Utils.escapeRuby(string);
    string = Utils.foldLog(string);
    string = Deansi.parse(string);
    string = Utils.breakLines(string);
    return string;
  },
  stripPaths: function(string) {
    return string.replace(/\/tmp\/travis\/builds(\/[^\/\n]+){2}\//g, '');
  },
  escapeRuby: function(string) {
    return string.replace(/#<(\w+.*?)>/, '#<$1>');
  },
  breakLines: function(string) {
    var newstring = "";
    var counter = 0;
    _.each(string.split('\n'), function (line) {
      counter++;
      newstring += "
" + counter+ "" + line + "
"
    })
    return newstring;
  },
  foldLog: function(string) {
    string = Utils.unfoldLog(string);
    var folds = {
      // 'clone': /(^|<\/div>)(\$ git clone.*\r?\n(?:(Initialized|remote:|Receiving|Resolving).*?\r?\n)*)/m,
      // 'clean':   /(^|<\\/div>)(\\$ git clean.*\\r?\\n(?:Removing .*\\r?\\n)+\\r?\\n*)/gm,
      // 'fetch':   /(^|<\\/div>)(\\$ git fetch.*\\r?\\nFrom .*\\n.*)\\r?\\n/gm,
      'bundle':  /(^|<\/div>)(\$ bundle install.*\r?\n*(?:(Fetching|Updating|Using|Installing|remote:|Receiving|Resolving|Unpacking).+\r?\n*)*)/gm,
      'migrate': /(^|<\/div>)(\$ rake db:migrate[\s\S]*(?:^== +\w+: migrated \(.*\) =+\r?\n))\r?\n?/gm,
      'exec':    /(^|<\/div>)(\/home\/([^\/]+)\/.rvm\/rubies\/\S*?\/(ruby|rbx|jruby) .*?)\r?\n/gm
    };
    _.each(folds, function(fold, type) {
      string = string.replace(fold, function() { return arguments[1] + '
\n' + arguments[2].trim() + '
\n'; });
    });
    // string = string.replace(/([\.-_*SEF]{120})\n?/g, '$1\n')
    return string;
  },
  unfoldLog: function(string) {
    return string.replace(/
([\s\S]*?)<\/div>/mg, '$1\n');
  },
  updateTimes: function(element) {
    $('.timeago', element).timeago();
    $('.duration', element).readableTime();

    if(!Utils._updateTimesInterval) {
      Utils._updateTimesInterval = setInterval(function() { Utils.updateTimes() }, 3000);
    }
  },
  readableTime: function(duration) {
    var days    = Math.floor(duration / 86400)
    var hours   = Math.floor(duration % 86400 / 3600);
    var minutes = Math.floor(duration % 3600 / 60);
    var seconds = duration % 60;

    if(days > 0) {
      return 'more than 24 hrs';
    } else {
      var result = [];
      if(hours   > 0) { result.push(hours + ' hrs'); }
      if(minutes > 0) { result.push(minutes + ' min'); }
      if(seconds > 0) { result.push(seconds + ' sec'); }
      return result.length > 0 ? result.join(' ') : '-';
    }
  },
  updateGithubStats: function(repository, element) {
    if(!window.__TESTING__) {
      $.getJSON('http://github.com/api/v2/json/repos/show/' + repository.get('slug') + '?callback=?', function(data) {
        var url = 'http://github.com/' + repository.get('slug');
        element.find('.watchers').attr('href', url + '/watchers').text(data.repository.watchers);
        element.find('.forks').attr('href', url + '/network').text(data.repository.forks);
      });
    }
  }
}

Utils.PathHelpers = {
  repositoryPath: function(owner, name, line_number) {
    if (line_number) {
      // #!/:owner/:name/L:line_number
      return "#!/" + owner + "/" + name + "/L" + line_number
    } else {
      // #!/:owner/:name
      var path = "#!/" + owner + "/" + name
    }
  },
  repositoryBuildPath: function(owner, name, build_id, line_number) {
    if (line_number) {
      //#!/:owner/:name/builds/:id/L:line_number
      var path = "#!/" + owner + "/" + name + "/builds/" + build_id +"/L" + line_number
    } else {
      //#!/:owner/:name/builds
      var path = "#!/" + owner + "/" + name + "/builds/" + build_id
    }
  }
}

console.log(Utils.PathHelpers)
function trace() {
  try {
    i.dont.exist; // force an exception
  } catch(e) {
    var lines = e.stack.split('\n').slice(2);
    var stack = _.map(lines, function(line) { return line.replace(/^\s*at/, ''); });
    console.log('trace -------------------------------');
    _.each(stack, function(line) { console.log(line); });
  }
}<commit_msg>Fixing typo: replacing 'var' with 'return'<commit_after>Utils = {
  loadTemplates: function() {
    var templates = {};
    $('*[type="text/x-js-template"]').map(function() {
      var name = $(this).attr('name');
      var source = $(this).html().replace('>', '>');
      if(name.split('/')[1][0] == '_') { Handlebars.registerPartial(name.replace('/', ''), source) }
      templates[name] = Handlebars.compile(source);
    });
    return templates;
  },
  queryString: function(params) {
    if(!params) return '';
    var query = _.compact(_.map(params, function(value, key) { return value ? key + '=' + value : null }));
    return query.length > 0 ? '?' + query.join('&') : '';
  },
  duration: function(started, finished) {
    started  = new Date(started);
    finished = finished ? new Date(finished) : new Date();
    return started ? Math.round((finished - started) / 1000) : 0;
  },
  activateTab: function(element, tab) {
    $('.tabs li', element).removeClass('active');
    $('#tab_' + tab.toLowerCase(), element).addClass('active');
  },
  animated: function(element) {
    return !!element.queue()[0];
  },
  flash: function(element) {
    if(!element.length == 0 && !Utils.animated(element)) {
      Utils._flash(element);
    }
  },
  _flash: function(element) {
    element.effect('highlight', {}, 1000, function () {
      Utils._flash(element)
    });
  },
  unflash: function(element) {
    if(!element.length == 0) {
      element.stop().css({ 'background-color': '', 'background-image': '' });
    }
  },
  filterLog: function(string) {
    // string = Handlebars.Utils.escapeExpression(string);
    string = Utils.stripPaths(string);
    string = Utils.escapeRuby(string);
    string = Utils.foldLog(string);
    string = Deansi.parse(string);
    string = Utils.breakLines(string);
    return string;
  },
  stripPaths: function(string) {
    return string.replace(/\/tmp\/travis\/builds(\/[^\/\n]+){2}\//g, '');
  },
  escapeRuby: function(string) {
    return string.replace(/#<(\w+.*?)>/, '#<$1>');
  },
  breakLines: function(string) {
    var newstring = "";
    var counter = 0;
    _.each(string.split('\n'), function (line) {
      counter++;
      newstring += "
" + counter+ "" + line + "
"
    })
    return newstring;
  },
  foldLog: function(string) {
    string = Utils.unfoldLog(string);
    var folds = {
      // 'clone': /(^|<\/div>)(\$ git clone.*\r?\n(?:(Initialized|remote:|Receiving|Resolving).*?\r?\n)*)/m,
      // 'clean':   /(^|<\\/div>)(\\$ git clean.*\\r?\\n(?:Removing .*\\r?\\n)+\\r?\\n*)/gm,
      // 'fetch':   /(^|<\\/div>)(\\$ git fetch.*\\r?\\nFrom .*\\n.*)\\r?\\n/gm,
      'bundle':  /(^|<\/div>)(\$ bundle install.*\r?\n*(?:(Fetching|Updating|Using|Installing|remote:|Receiving|Resolving|Unpacking).+\r?\n*)*)/gm,
      'migrate': /(^|<\/div>)(\$ rake db:migrate[\s\S]*(?:^== +\w+: migrated \(.*\) =+\r?\n))\r?\n?/gm,
      'exec':    /(^|<\/div>)(\/home\/([^\/]+)\/.rvm\/rubies\/\S*?\/(ruby|rbx|jruby) .*?)\r?\n/gm
    };
    _.each(folds, function(fold, type) {
      string = string.replace(fold, function() { return arguments[1] + '
\n' + arguments[2].trim() + '
\n'; });
    });
    // string = string.replace(/([\.-_*SEF]{120})\n?/g, '$1\n')
    return string;
  },
  unfoldLog: function(string) {
    return string.replace(/
([\s\S]*?)<\/div>/mg, '$1\n');
  },
  updateTimes: function(element) {
    $('.timeago', element).timeago();
    $('.duration', element).readableTime();

    if(!Utils._updateTimesInterval) {
      Utils._updateTimesInterval = setInterval(function() { Utils.updateTimes() }, 3000);
    }
  },
  readableTime: function(duration) {
    var days    = Math.floor(duration / 86400)
    var hours   = Math.floor(duration % 86400 / 3600);
    var minutes = Math.floor(duration % 3600 / 60);
    var seconds = duration % 60;

    if(days > 0) {
      return 'more than 24 hrs';
    } else {
      var result = [];
      if(hours   > 0) { result.push(hours + ' hrs'); }
      if(minutes > 0) { result.push(minutes + ' min'); }
      if(seconds > 0) { result.push(seconds + ' sec'); }
      return result.length > 0 ? result.join(' ') : '-';
    }
  },
  updateGithubStats: function(repository, element) {
    if(!window.__TESTING__) {
      $.getJSON('http://github.com/api/v2/json/repos/show/' + repository.get('slug') + '?callback=?', function(data) {
        var url = 'http://github.com/' + repository.get('slug');
        element.find('.watchers').attr('href', url + '/watchers').text(data.repository.watchers);
        element.find('.forks').attr('href', url + '/network').text(data.repository.forks);
      });
    }
  }
}

Utils.PathHelpers = {
  repositoryPath: function(owner, name, line_number) {
    if (line_number) {
      // #!/:owner/:name/L:line_number
      return "#!/" + owner + "/" + name + "/L" + line_number
    } else {
      // #!/:owner/:name
      var path = "#!/" + owner + "/" + name
    }
  },
  repositoryBuildPath: function(owner, name, build_id, line_number) {
    if (line_number) {
      //#!/:owner/:name/builds/:id/L:line_number
      return "#!/" + owner + "/" + name + "/builds/" + build_id +"/L" + line_number
    } else {
      //#!/:owner/:name/builds
      return "#!/" + owner + "/" + name + "/builds/" + build_id
    }
  }
}

function trace() {
  try {
    i.dont.exist; // force an exception
  } catch(e) {
    var lines = e.stack.split('\n').slice(2);
    var stack = _.map(lines, function(line) { return line.replace(/^\s*at/, ''); });
    console.log('trace -------------------------------');
    _.each(stack, function(line) { console.log(line); });
  }
}<|endoftext|>