<commit_before>'use strict';

var Q = require('q');
var expand = require('glob-expand');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var VFS = require('28').VFS;
var _ = require('lodash');
var minimist = require('minimist');

var Config = require('./config');

var credentials;

var Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};

var castToJson = function(obj){
    var result = obj;
    if(_.isString(obj)){
        try {
            result = JSON.parse(obj);
        } catch (e) {

        }
    }
    return result;
};

var throwError = function (error) {
    var message = JSON.stringify(error);
    if(error.stack || error.filename){
        message = error.toString();
        $.util.log(error.stack);
        $.util.log(error.filename);
    } else if(_.isString(error.message)){
        message = error.message;
    }
    if(error.body){
        var body = castToJson(error.body);
        message = _.isObject(body) ? JSON.stringify(body, null, '\t') : body;
        if((_.isObject(body) && body.context) || (_.isArray(body) && body[0].context)){
            $.util.log(message);
            message = 'Compilation error';
        }
    }

    // truncate error message if too long
    if(message.length > 500){
        message = message.substring(0, 500) + ' ... (truncated)';
    }
    throw new $.util.PluginError(__filename, message);
};

var summarizeTestError = function(error){
    var hasError = false;
    if(error.body) {
        var body = castToJson(error.body);
        if (_.isObject(body) && _.isArray(body.items) && body.items.length > 0) {
            body = castToJson(body.items[0]);
        }
        if (_.isObject(body) && body.content) {
            body = castToJson(body.content);
        }
        /*jshint camelcase:false */
        if (_.isObject(body) && !body.request_id) {
            _.each(body, function(testResult, testName){
                if (_.isObject(testResult) && testResult.url) {
                    hasError = true;
                    $.util.log(testName.red + ': ' + testResult.url);
                    if (_.isObject(testResult.expectedFactTable) && testResult.expectedFactTable.error === true) {
                        // http error (e.g. 404)
                        $.util.log(testName.red + ': ' + JSON.stringify(testResult.expectedFactTable, null, '\t'));
                    }
                    _.each(testResult.factTableDiff, function(diff){
                        if (diff.expectedNumberOfFacts) {
                            $.util.log(testName.red + ': ' + JSON.stringify(diff, null, '\t'));
                        }
                    });
                }
            });
        }
        if (hasError) {
            return new Error('some test queries failed');
        }
    }
    return error;
};

var login = function(email, password){
    $.util.log('Logging in as ' + email);
    return Config.$28.login(email, password).then(function(response){
        $.util.log('Logged in.');
        credentials = response.body;
        return credentials;
    });
};

var removeProject = function(projectName, isIdempotent){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Deleting project ' + projectName);
        Config.$28.deleteProject(projectName, token).then(function () {
            $.util.log('Project deleted.');
            defered.resolve(credentials);
        }).catch(function (error) {
            if (!isIdempotent) {
                defered.reject(error);
            } else {
                defered.resolve(credentials);
            }
        });
    } else {
        $.util.log('Skipping project deletion for production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var createProject = function(projectName){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Creating project ' + projectName);
        Config.$28.createProject(projectName, token).then(function (response) {
            $.util.log('Project  ' + projectName + ' created.');
            /*jshint camelcase:false */
            credentials.project_tokens['project_' + projectName] = response.body.projectToken;
            defered.resolve(credentials);
        }).catch(function (error) {
            $.util.log('Project creation failed: ' + error);
            defered.reject(error);
        });
    } else {
        $.util.log('Skipping project creation on production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var upgradeProject = function(projectName){
    /*jshint camelcase:false */
    var deferred = Q.defer();
    var token = credentials.access_token;
    $.util.log('Upgrading project ' + projectName);
    Config.$28.upgradeProject(projectName, token)
    .then(function () {
        $.util.log('Project ' + projectName + ' upgraded.');
        deferred.resolve(credentials);
    }).catch(function (error) {
        $.util.log('Upgrading Project failed: ' + error);
        deferred.reject(error);
    });
    return deferred.promise;
};

var createOrUpgradeProject = function(project){
    if(project.exists){
        return upgradeProject(project.name);
    } else {
        return createProject(project.name);
    }
};

var existsProject = function(projectName){
    /*jshint camelcase:false */
    var deferred = Q.defer();
    var project = {
        name: projectName
    };
    $.util.log('Checking project ' + projectName);
    Config.$28.existsProject(projectName)
    .then(function () {
        $.util.log('project ' + projectName + ' exists already');
        project.exists = true;
        deferred.resolve(project);
    })
    .catch(function (data) {
        if(data.response.statusCode === 404){
            $.util.log('project ' + projectName + ' does not exist.');
            project.exists = false;
            deferred.resolve(project);
        } else {
            $.util.log('Checking Project failed: ' + data);
            deferred.reject(data);
        }
    });
    return deferred.promise;
};

var ignoreQueriesFunction = function(list){
    return list;
};

var upload = function(projectName){
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    if(!projectToken) {
        throw new Error('project not found ' + projectName);
    }
    var projectPath = Config.paths.queries;
    var overwrite = Options.OVERWRITE_ALWAYS;
    var deleteOrphaned = true;
    var simulate = false;
    $.util.log('Uploading queries.');
    return Config.$28.upload(projectName, projectToken, projectPath, overwrite, deleteOrphaned, simulate, ignoreQueriesFunction).then(function(){
        $.util.log('Queries uploaded.');
        return credentials;
    });
};

var runQueriesInParallel = function(projectName, queriesToRun) {
    var promises = [];
    var QueriesAPI = Config.$28.api.Queries(projectName);
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    _.each(queriesToRun, function(nextQuery){
        promises.push(
            QueriesAPI.executeQuery({
                accept: 'application/28.io+json',
                queryPath: nextQuery,
                format: '',
                token: projectToken
            }).then(function (data) {
                $.util.log($.util.colors.green('✓ ') + nextQuery + ' returned with status code: ' + data.response.statusCode);
                return credentials;
            }).catch(function (error) {
                var requestUri = error.response.request.uri;
                var isTestQuery = (requestUri.pathname.lastIndexOf('/v1/_queries/public/test', 0) === 0);
                var href = isTestQuery ? requestUri.host + requestUri.pathname.substring('/v1/_queries/public'.length) : requestUri.host + requestUri.pathname;
                $.util.log($.util.colors.red('✗ ') + href + ' returned with status code: ' + $.util.colors.red(error.response.statusCode));
                error = isTestQuery ? summarizeTestError(error) : error;
                throw error;
            })
        );
    });
    return Q.all(promises);
};

var runQueries = function(projectName, sequenceOfQueriesToRun) {
    return _.chain(sequenceOfQueriesToRun)
        .map(function(queriesToRun) {
            // create chunks of queries to be executed in parallel
            if (_.isString(queriesToRun)) {
                return expand(queriesToRun);
            } else if (_.isArray(queriesToRun)){
                return _.chain(queriesToRun)
                    .map(function(queriesGlob){
                        return expand(queriesGlob);
                    })
                    .flatten()
                    .value();
            }
        })
        .map(function(queriesToRunArray){
            // substring to relative query path
            return _.map(queriesToRunArray, function(query) {
                return query.substring(Config.paths.queries.length + 1);
            });
        })
        .reduce(function(previousPromise, nextQueriesArray){
            // execute them in chunks
            return previousPromise.then(function() {
                return runQueriesInParallel(projectName, nextQueriesArray);
            });
        }, Q.resolve())
        .value();
};

var createDatasource = function(projectName, datasource){
    var defered = Q.defer();
    $.util.log('Creating datasource ' + datasource.name);
    var difault = datasource.default ? datasource.default : false;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.createDatasource(projectName, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
        .then(function(){
            $.util.log(datasource.name + ' created');
            defered.resolve(credentials);
        })
        .catch(function (error) {
            $.util.log('datasource creation failed: ' + datasource.name);
            defered.reject(error);
        });
    return defered.promise;
};

var updateDatasource = function(projectName, datasource){
    var defered = Q.defer();
    $.util.log('Updating datasource ' + datasource.name);
    var difault = datasource.default ? datasource.default : false;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.updateDatasource(projectName, datasource.name, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
        .then(function(){
            $.util.log(datasource.name + ' updated');
            defered.resolve(credentials);
        })
        .catch(function (error) {
            $.util.log('Updating datasource failed: ' + datasource.name);
            defered.reject(error);
        });
    return defered.promise;
};

var listDatasources = function(projectName){
    var deferred = Q.defer();
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.listDatasources(projectName, projectToken)
        .then(function(data){
            var datasources = data.body;
            if(_.isString(datasources)){
                datasources = JSON.parse(datasources);
            }
            deferred.resolve(datasources);
        })
        .catch(function (error) {
            $.util.log('listing datasources failed: ' + projectName);
            deferred.reject(error);
        });
    return deferred.promise;
};

var createOrUpdateDatasources = function(existingDataSources){
    var promises = [];
    Config.credentials['28'].datasources.forEach(function(datasource){
        var existing = _.find(existingDataSources, function(ds){ return ds.name === datasource.name; });
        if(existing){
            promises.push(updateDatasource(Config.projectName, datasource).catch(throwError));
        } else {
            promises.push(createDatasource(Config.projectName, datasource).catch(throwError));
        }
    });
    return Q.all(promises);
};

gulp.task('28:login', ['config:init'], function(){
    return login(Config.credentials['28'].email, Config.credentials['28'].password).catch(throwError);
});

gulp.task('28:create-project', function(){
    return existsProject(Config.projectName)
        .then(createOrUpgradeProject)
        .catch(throwError);
});

gulp.task('28:remove-project', function(){
    return removeProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:upload', function(){
    return upload(Config.projectName).catch(throwError);
});

gulp.task('28:setup-datasources', function(){
    return listDatasources(Config.projectName)
        .then(createOrUpdateDatasources)
        .catch(throwError);
});

gulp.task('28:init', function(){
    return runQueries(Config.projectName, Config.paths.initQueries).catch(throwError);
});

gulp.task('28:setup', ['28:login'], function(done){
    $.runSequence('28:remove-project', '28:create-project', ['28:setup-datasources', '28:upload'], '28:init', '28:test', done);
});

gulp.task('28:teardown', function(done){
    $.runSequence('28:login', '28:remove-project', done);
});

gulp.task('28:test', function(){
    return runQueries(Config.projectName, Config.paths.apiTestQueries).catch(throwError);
});

gulp.task('28:trace', ['28:login'], function(done){
    var knownOptions = {
        string: [ 'path' ]
    };
    var args = minimist(process.argv.slice(2), knownOptions);
    var path = args.path;
    if(!path) {
        throw new $.util.PluginError(__filename, 'Specify --path option.');
    }
    var projectName = Config.projectName;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    var url = 'http://' + projectName + '.28.io' + '/v1/_queries';
    var request = require('request');
    path = path.indexOf('?') === -1 ? (path + '?') : path;
    url += path + '&trace&_token=' + encodeURIComponent(projectToken);
    request({
        uri: url,
        method: 'POST'
    }, function(error, response, body){
        if(error) {
            throw new $.util.PluginError(__filename, error);
        }
        $.util.log($.util.colors.gray(body));
        var traceFile = response.headers['x-28msec-trace'];
        setTimeout(function(){
            request({
                uri: traceFile,
                method: 'GET'
            }, function(error, response, body){
                if(body) {
                    $.util.log($.util.colors.green(body));
                } else {
                    $.util.log($.util.colors.green('No trace.'));
                }
                done();
            });
        }, 1000);
    });
});

module.exports = {
    watchJSONiqQueries: function(){
        //Initialize the VFS
        /*jshint camelcase:false */
        var projectName = Config.projectName;
        var projectToken = credentials.project_tokens['project_' + projectName];
        var upath = require('upath');
        var projectPath = upath.resolve(Config.paths.queries);
        var vfs = new VFS(Config.$28.api, projectName, projectToken, projectPath);

        //Do the Watch
        gulp.watch(Config.paths.jsoniq, {}, function(event){
            //Get relative query path
            var query = event.path.substring(projectPath.length + 1);
            query = upath.normalize(query);
            $.util.log(query + ' has ' + event.type);

            //Upload
            if(event.type === 'added' || event.type === 'changed') {
                $.util.log($.util.colors.grey('Uploading ' + query));
                vfs.writeRemoteQuery(query, true).then(function(result){
                    //Show compilation errors
                    if(result && result.message) {
                        $.util.log($.util.colors.red(result.message));
                    }
                    $.util.log($.util.colors.green(query + ' uploaded'));
                }).catch(function(error){
                    throwError(error);
                });

            //Delete
            } else if(event.type === 'deleted') {
                $.util.log($.util.colors.grey('Removing ' + query));
                vfs.deleteRemoteQuery(query).then(function(){
                    $.util.log($.util.colors.green(query + ' removed'));
                }).catch(function(error){
                    throwError(error);
                });
            }
        });
    }
};
<commit_msg>:green_heart: Fix build<commit_after>'use strict';

var Q = require('q');
var expand = require('glob-expand');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var VFS = require('28').VFS;
var _ = require('lodash');
var minimist = require('minimist');

var Config = require('./config');

var credentials;

var Options = {
    OVERWRITE_ALWAYS: 0,
    OVERWRITE_NEVER: 1,
    OVERWRITE_ASK: 2,
    OVERWRITE_IF_NEWER: 3
};

var castToJson = function(obj){
    var result = obj;
    if(_.isString(obj)){
        try {
            result = JSON.parse(obj);
        } catch (e) {

        }
    }
    return result;
};

var throwError = function (error) {
    var message = JSON.stringify(error);
    if(error.stack || error.filename){
        message = error.toString();
        $.util.log(error.stack);
        $.util.log(error.filename);
    } else if(_.isString(error.message)){
        message = error.message;
    }
    if(error.body){
        var body = castToJson(error.body);
        message = _.isObject(body) ? JSON.stringify(body, null, '\t') : body;
        if((_.isObject(body) && body.context) || (_.isArray(body) && body[0].context)){
            $.util.log(message);
            message = 'Compilation error';
        }
    }

    // truncate error message if too long
    if(message.length > 500){
        message = message.substring(0, 500) + ' ... (truncated)';
    }
    throw new $.util.PluginError(__filename, message);
};

var summarizeTestError = function(error){
    var hasError = false;
    if(error.body) {
        var body = castToJson(error.body);
        if (_.isObject(body) && _.isArray(body.items) && body.items.length > 0) {
            body = castToJson(body.items[0]);
        }
        if (_.isObject(body) && body.content) {
            body = castToJson(body.content);
        }
        /*jshint camelcase:false */
        if (_.isObject(body) && !body.request_id) {
            _.each(body, function(testResult, testName){
                if (_.isObject(testResult) && testResult.url) {
                    hasError = true;
                    $.util.log(testName.red + ': ' + testResult.url);
                    if (_.isObject(testResult.expectedFactTable) && testResult.expectedFactTable.error === true) {
                        // http error (e.g. 404)
                        $.util.log(testName.red + ': ' + JSON.stringify(testResult.expectedFactTable, null, '\t'));
                    }
                    _.each(testResult.factTableDiff, function(diff){
                        if (diff.expectedNumberOfFacts) {
                            $.util.log(testName.red + ': ' + JSON.stringify(diff, null, '\t'));
                        }
                    });
                }
            });
        }
        if (hasError) {
            return new Error('some test queries failed');
        }
    }
    return error;
};

var login = function(email, password){
    $.util.log('Logging in as ' + email);
    return Config.$28.login(email, password).then(function(response){
        $.util.log('Logged in.');
        credentials = response.body;
        return credentials;
    });
};

var removeProject = function(projectName, isIdempotent){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Deleting project ' + projectName);
        Config.$28.deleteProject(projectName, token).then(function () {
            $.util.log('Project deleted.');
            defered.resolve(credentials);
        }).catch(function (error) {
            if (!isIdempotent) {
                defered.reject(error);
            } else {
                defered.resolve(credentials);
            }
        });
    } else {
        $.util.log('Skipping project deletion for production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var createProject = function(projectName){
    /*jshint camelcase:false */
    var defered = Q.defer();
    if(!Config.isOnProduction) {
        var token = credentials.access_token;
        $.util.log('Creating project ' + projectName);
        Config.$28.createProject(projectName, token).then(function (response) {
            $.util.log('Project  ' + projectName + ' created.');
            /*jshint camelcase:false */
            credentials.project_tokens['project_' + projectName] = response.body.projectToken;
            defered.resolve(credentials);
        }).catch(function (error) {
            $.util.log('Project creation failed: ' + error);
            defered.reject(error);
        });
    } else {
        $.util.log('Skipping project creation on production: ' + projectName);
        defered.resolve(credentials);
    }
    return defered.promise;
};

var upgradeProject = function(projectName){
    /*jshint camelcase:false */
    var deferred = Q.defer();
    var token = credentials.access_token;
    $.util.log('Upgrading project ' + projectName);
    Config.$28.upgradeProject(projectName, token)
    .then(function () {
        $.util.log('Project ' + projectName + ' upgraded.');
        deferred.resolve(credentials);
    }).catch(function (error) {
        $.util.log('Upgrading Project failed: ' + error);
        deferred.reject(error);
    });
    return deferred.promise;
};

var createOrUpgradeProject = function(project){
    if(project.exists){
        return upgradeProject(project.name);
    } else {
        return createProject(project.name);
    }
};

var existsProject = function(projectName){
    /*jshint camelcase:false */
    var deferred = Q.defer();
    var project = {
        name: projectName
    };
    $.util.log('Checking project ' + projectName);
    Config.$28.existsProject(projectName)
    .then(function () {
        $.util.log('project ' + projectName + ' exists already');
        project.exists = true;
        deferred.resolve(project);
    })
    .catch(function (data) {
        if(data.response.statusCode === 404){
            $.util.log('project ' + projectName + ' does not exist.');
            project.exists = false;
            deferred.resolve(project);
        } else {
            $.util.log('Checking Project failed: ' + data);
            deferred.reject(data);
        }
    });
    return deferred.promise;
};

var ignoreQueriesFunction = function(list){
    return list;
};

var upload = function(projectName){
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    if(!projectToken) {
        throw new Error('project not found ' + projectName);
    }
    var projectPath = Config.paths.queries;
    var overwrite = Options.OVERWRITE_ALWAYS;
    var deleteOrphaned = true;
    var simulate = false;
    $.util.log('Uploading queries.');
    return Config.$28.upload(projectName, projectToken, projectPath, overwrite, deleteOrphaned, simulate, ignoreQueriesFunction).then(function(){
        $.util.log('Queries uploaded.');
        return credentials;
    });
};

var runQueriesInParallel = function(projectName, queriesToRun) {
    var promises = [];
    var QueriesAPI = Config.$28.api.Queries(projectName);
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    _.each(queriesToRun, function(nextQuery){
        promises.push(
            QueriesAPI.executeQuery({
                accept: 'application/28.io+json',
                queryPath: nextQuery,
                format: '',
                token: projectToken
            }).then(function (data) {
                $.util.log($.util.colors.green('✓ ') + nextQuery + ' returned with status code: ' + data.response.statusCode);
                return credentials;
            }).catch(function (error) {
                var requestUri = error.response.request.uri;
                var isTestQuery = (requestUri.pathname.lastIndexOf('/v1/_queries/public/test', 0) === 0);
                var href = isTestQuery ? requestUri.host + requestUri.pathname.substring('/v1/_queries/public'.length) : requestUri.host + requestUri.pathname;
                $.util.log($.util.colors.red('✗ ') + href + ' returned with status code: ' + $.util.colors.red(error.response.statusCode));
                error = isTestQuery ? summarizeTestError(error) : error;
                throw error;
            })
        );
    });
    return Q.all(promises);
};

var runQueries = function(projectName, sequenceOfQueriesToRun) {
    return _.chain(sequenceOfQueriesToRun)
        .map(function(queriesToRun) {
            // create chunks of queries to be executed in parallel
            if (_.isString(queriesToRun)) {
                return expand(queriesToRun);
            } else if (_.isArray(queriesToRun)){
                return _.chain(queriesToRun)
                    .map(function(queriesGlob){
                        return expand(queriesGlob);
                    })
                    .flatten()
                    .value();
            }
        })
        .map(function(queriesToRunArray){
            // substring to relative query path
            return _.map(queriesToRunArray, function(query) {
                return query.substring(Config.paths.queries.length + 1);
            });
        })
        .reduce(function(previousPromise, nextQueriesArray){
            // execute them in chunks
            return previousPromise.then(function() {
                return runQueriesInParallel(projectName, nextQueriesArray);
            });
        }, Q.resolve())
        .value();
};

var createDatasource = function(projectName, datasource){
    var defered = Q.defer();
    $.util.log('Creating datasource ' + datasource.name);
    var difault = datasource.default ? datasource.default : false;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.createDatasource(projectName, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
        .then(function(){
            $.util.log(datasource.name + ' created');
            defered.resolve(credentials);
        })
        .catch(function (error) {
            $.util.log('datasource creation failed: ' + datasource.name);
            defered.reject(error);
        });
    return defered.promise;
};

var updateDatasource = function(projectName, datasource){
    var defered = Q.defer();
    $.util.log('Updating datasource ' + datasource.name);
    var difault = datasource.default ? datasource.default : false;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.updateDatasource(projectName, datasource.name, datasource.category, datasource.name, projectToken, difault, JSON.stringify(datasource.credentials))
        .then(function(){
            $.util.log(datasource.name + ' updated');
            defered.resolve(credentials);
        })
        .catch(function (error) {
            $.util.log('Updating datasource failed: ' + datasource.name);
            defered.reject(error);
        });
    return defered.promise;
};

var listDatasources = function(projectName){
    var deferred = Q.defer();
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    Config.$28.listDatasources(projectName, projectToken)
        .then(function(data){
            var datasources = data.body;
            if(_.isString(datasources)){
                datasources = JSON.parse(datasources);
            }
            deferred.resolve(datasources);
        })
        .catch(function (error) {
            $.util.log('listing datasources failed: ' + projectName);
            deferred.reject(error);
        });
    return deferred.promise;
};

var createOrUpdateDatasources = function(existingDataSources){
    var promises = [];
    Config.credentials['28'].datasources.forEach(function(datasource){
        var existing = _.find(existingDataSources, function(ds){ return ds.name === datasource.name; });
        if(existing){
            promises.push(updateDatasource(Config.projectName, datasource).catch(throwError));
        } else {
            promises.push(createDatasource(Config.projectName, datasource).catch(throwError));
        }
    });
    return Q.all(promises);
};

gulp.task('28:login', ['config'], function(){
    return login(Config.credentials['28'].email, Config.credentials['28'].password).catch(throwError);
});

gulp.task('28:create-project', function(){
    return existsProject(Config.projectName)
        .then(createOrUpgradeProject)
        .catch(throwError);
});

gulp.task('28:remove-project', function(){
    return removeProject(Config.projectName, true).catch(throwError);
});

gulp.task('28:upload', function(){
    return upload(Config.projectName).catch(throwError);
});

gulp.task('28:setup-datasources', function(){
    return listDatasources(Config.projectName)
        .then(createOrUpdateDatasources)
        .catch(throwError);
});

gulp.task('28:init', function(){
    return runQueries(Config.projectName, Config.paths.initQueries).catch(throwError);
});

gulp.task('28:setup', ['28:login'], function(done){
    $.runSequence('28:remove-project', '28:create-project', ['28:setup-datasources', '28:upload'], '28:init', '28:test', done);
});

gulp.task('28:teardown', function(done){
    $.runSequence('28:login', '28:remove-project', done);
});

gulp.task('28:test', function(){
    return runQueries(Config.projectName, Config.paths.apiTestQueries).catch(throwError);
});

gulp.task('28:trace', ['28:login'], function(done){
    var knownOptions = {
        string: [ 'path' ]
    };
    var args = minimist(process.argv.slice(2), knownOptions);
    var path = args.path;
    if(!path) {
        throw new $.util.PluginError(__filename, 'Specify --path option.');
    }
    var projectName = Config.projectName;
    /*jshint camelcase:false */
    var projectToken = credentials.project_tokens['project_' + projectName];
    var url = 'http://' + projectName + '.28.io' + '/v1/_queries';
    var request = require('request');
    path = path.indexOf('?') === -1 ? (path + '?') : path;
    url += path + '&trace&_token=' + encodeURIComponent(projectToken);
    request({
        uri: url,
        method: 'POST'
    }, function(error, response, body){
        if(error) {
            throw new $.util.PluginError(__filename, error);
        }
        $.util.log($.util.colors.gray(body));
        var traceFile = response.headers['x-28msec-trace'];
        setTimeout(function(){
            request({
                uri: traceFile,
                method: 'GET'
            }, function(error, response, body){
                if(body) {
                    $.util.log($.util.colors.green(body));
                } else {
                    $.util.log($.util.colors.green('No trace.'));
                }
                done();
            });
        }, 1000);
    });
});

module.exports = {
    watchJSONiqQueries: function(){
        //Initialize the VFS
        /*jshint camelcase:false */
        var projectName = Config.projectName;
        var projectToken = credentials.project_tokens['project_' + projectName];
        var upath = require('upath');
        var projectPath = upath.resolve(Config.paths.queries);
        var vfs = new VFS(Config.$28.api, projectName, projectToken, projectPath);

        //Do the Watch
        gulp.watch(Config.paths.jsoniq, {}, function(event){
            //Get relative query path
            var query = event.path.substring(projectPath.length + 1);
            query = upath.normalize(query);
            $.util.log(query + ' has ' + event.type);

            //Upload
            if(event.type === 'added' || event.type === 'changed') {
                $.util.log($.util.colors.grey('Uploading ' + query));
                vfs.writeRemoteQuery(query, true).then(function(result){
                    //Show compilation errors
                    if(result && result.message) {
                        $.util.log($.util.colors.red(result.message));
                    }
                    $.util.log($.util.colors.green(query + ' uploaded'));
                }).catch(function(error){
                    throwError(error);
                });

            //Delete
            } else if(event.type === 'deleted') {
                $.util.log($.util.colors.grey('Removing ' + query));
                vfs.deleteRemoteQuery(query).then(function(){
                    $.util.log($.util.colors.green(query + ' removed'));
                }).catch(function(error){
                    throwError(error);
                });
            }
        });
    }
};
<|endoftext|>


<commit_before>kickStart.define({ name: 'route' });
kickStart.register('route', function () {
    var app = kickStart;
    // private scope
    var routes  = {};
    var routeRE = {};

    addListener();
    var obj = {
        add     : add,
        remove  : remove,
        go      : go,
        get     : get,
        process : process,
        list    : list,
        onAdd   : null,
        onRemove: null,
        onRoute : null
    };
    if (w2utils.event) $.extend(obj, w2utils.event, { handlers: [] });
    return obj;

    /*
    *   Public methods
    */

    function add (route, handler) {
        if (typeof route == 'object') {
            for (var r in route) {
                var tmp = String('/'+ r).replace(/\/{2,}/g, '/');
                routes[tmp] = route[r];
            }
            return app.route;
        }
        route = String('/'+route).replace(/\/{2,}/g, '/');
        // if events are available
        if (typeof app.route.trigger == 'function') {
            var eventData = app.route.trigger({ phase: 'before', type: 'add', target: 'self', route: route, handler: handler });
            if (eventData.isCancelled === true) return false;
        }
        // default behavior
        routes[route] = handler;
        // if events are available
        if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        return app.route;
    }

    function remove (route) {
        route = String('/'+route).replace(/\/{2,}/g, '/');
        // if events are available
        if (typeof app.route.trigger == 'function') {
            var eventData = app.route.trigger({ phase: 'before', type: 'remove', target: 'self', route: route, handler: handler });
            if (eventData.isCancelled === true) return false;
        }
        // default behavior
        delete routes[route];
        delete routeRE[route];
        // if events are available
        if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        return app.route;
    }

    function go (route) {
        route = String('/'+route).replace(/\/{2,}/g, '/');
        setTimeout(function () { window.location.hash = route; }, 1);
        return app.route;
    }

    function get () {
        return window.location.hash.substr(1).replace(/\/{2,}/g, '/');
    }

    function list () {
        prepare();
        var res = {};
        for (var r in routes) {
            var tmp  = routeRE[r].keys;
            var keys = [];
            for (var t in tmp) keys.push(tmp[t].name);
            res[r] = keys;
        }
        return res;
    }

    function process () {
        prepare();
        // match routes
        var hash = window.location.hash.substr(1).replace(/\/{2,}/g, '/');
        if (hash == '') hash = '/';
        var tmp  = hash.split('/');
        // check if modules is loaed
        if (tmp[1] && typeof app[tmp[1]] == 'undefined') {
            // if events are available
            if (typeof app.route.trigger == 'function') {
                var eventData = app.route.trigger({ phase: 'before', type: 'route', target: 'self', route: hash });
                if (eventData.isCancelled === true) return false;
            }
            // load module
            app.require(tmp[1]).done(function () {
                if (app.modules[tmp[1]]) process();
            });
            // if events are available
            if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        } else {
            // process route
            for (var r in routeRE) {
                var params = {};
                var tmp = routeRE[r].path.exec(hash);
                if (tmp) { // match
                    var i = 1;
                    for (var p in routeRE[r].keys) {
                        params[routeRE[r].keys[p].name] = tmp[i];
                        i++;
                    }
                    // if events are available
                    if (typeof app.route.trigger == 'function') {
                        var eventData = app.route.trigger({ phase: 'before', type: 'route', target: 'self', route: r, params: params });
                        if (eventData.isCancelled === true) return false;
                    }
                    // default error handler
                    routes[r](r, params);
                    // if events are available
                    if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
                }
            }
        }
    }

    /*
    *   Private methods
    */

    function prepare () {
        // make sure all routes are parsed to RegEx
        for (var r in routes) {
            if (routeRE[r]) continue;
            var keys = [];
            var path = r
                .replace(/\/\(/g, '(?:/')
                .replace(/\+/g, '__plus__')
                .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) {
                    keys.push({ name: key, optional: !! optional });
                    slash = slash || '';
                    return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || '');
                })
                .replace(/([\/.])/g, '\\$1')
                .replace(/__plus__/g, '(.+)')
                .replace(/\*/g, '(.*)');
            routeRE[r] = {
                path    : new RegExp('^' + path + '$', 'i'),
                keys    : keys
            }
        }
    }

    function addListener () {
        if (window.addEventListener) {
            window.addEventListener('hashchange', process, false);
        } else {
            window.attachEvent('onhashchange', process);
        }
    }

    function removeListener () {
        if (window.removeEventListener) {
            window.removeEventListener('hashchange', process);
        } else {
            window.detachEvent('onhashchange', process);
        }
    }
});<commit_msg>Small change in kickstart<commit_after>kickStart.define({ name: 'route' });
kickStart.register('route', function () {
    var app = kickStart;
    // private scope
    var routes  = {};
    var routeRE = {};

    addListener();
    var obj = {
        add     : add,
        remove  : remove,
        go      : go,
        get     : get,
        process : process,
        list    : list,
        onAdd   : null,
        onRemove: null,
        onRoute : null
    };
    if (typeof w2utils != 'undefined') $.extend(obj, w2utils.event, { handlers: [] });
    return obj;

    /*
    *   Public methods
    */

    function add (route, handler) {
        if (typeof route == 'object') {
            for (var r in route) {
                var tmp = String('/'+ r).replace(/\/{2,}/g, '/');
                routes[tmp] = route[r];
            }
            return app.route;
        }
        route = String('/'+route).replace(/\/{2,}/g, '/');
        // if events are available
        if (typeof app.route.trigger == 'function') {
            var eventData = app.route.trigger({ phase: 'before', type: 'add', target: 'self', route: route, handler: handler });
            if (eventData.isCancelled === true) return false;
        }
        // default behavior
        routes[route] = handler;
        // if events are available
        if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        return app.route;
    }

    function remove (route) {
        route = String('/'+route).replace(/\/{2,}/g, '/');
        // if events are available
        if (typeof app.route.trigger == 'function') {
            var eventData = app.route.trigger({ phase: 'before', type: 'remove', target: 'self', route: route, handler: handler });
            if (eventData.isCancelled === true) return false;
        }
        // default behavior
        delete routes[route];
        delete routeRE[route];
        // if events are available
        if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        return app.route;
    }

    function go (route) {
        route = String('/'+route).replace(/\/{2,}/g, '/');
        setTimeout(function () { window.location.hash = route; }, 1);
        return app.route;
    }

    function get () {
        return window.location.hash.substr(1).replace(/\/{2,}/g, '/');
    }

    function list () {
        prepare();
        var res = {};
        for (var r in routes) {
            var tmp  = routeRE[r].keys;
            var keys = [];
            for (var t in tmp) keys.push(tmp[t].name);
            res[r] = keys;
        }
        return res;
    }

    function process () {
        prepare();
        // match routes
        var hash = window.location.hash.substr(1).replace(/\/{2,}/g, '/');
        if (hash == '') hash = '/';
        var tmp  = hash.split('/');
        // check if modules is loaed
        if (tmp[1] && typeof app[tmp[1]] == 'undefined') {
            // if events are available
            if (typeof app.route.trigger == 'function') {
                var eventData = app.route.trigger({ phase: 'before', type: 'route', target: 'self', route: hash });
                if (eventData.isCancelled === true) return false;
            }
            // load module
            app.require(tmp[1]).done(function () {
                if (app.modules[tmp[1]]) process();
            });
            // if events are available
            if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
        } else {
            // process route
            for (var r in routeRE) {
                var params = {};
                var tmp = routeRE[r].path.exec(hash);
                if (tmp) { // match
                    var i = 1;
                    for (var p in routeRE[r].keys) {
                        params[routeRE[r].keys[p].name] = tmp[i];
                        i++;
                    }
                    // if events are available
                    if (typeof app.route.trigger == 'function') {
                        var eventData = app.route.trigger({ phase: 'before', type: 'route', target: 'self', route: r, params: params });
                        if (eventData.isCancelled === true) return false;
                    }
                    // default error handler
                    routes[r](r, params);
                    // if events are available
                    if (typeof app.route.trigger == 'function') app.route.trigger($.extend(eventData, { phase: 'after' }));
                }
            }
        }
    }

    /*
    *   Private methods
    */

    function prepare () {
        // make sure all routes are parsed to RegEx
        for (var r in routes) {
            if (routeRE[r]) continue;
            var keys = [];
            var path = r
                .replace(/\/\(/g, '(?:/')
                .replace(/\+/g, '__plus__')
                .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) {
                    keys.push({ name: key, optional: !! optional });
                    slash = slash || '';
                    return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || '');
                })
                .replace(/([\/.])/g, '\\$1')
                .replace(/__plus__/g, '(.+)')
                .replace(/\*/g, '(.*)');
            routeRE[r] = {
                path    : new RegExp('^' + path + '$', 'i'),
                keys    : keys
            }
        }
    }

    function addListener () {
        if (window.addEventListener) {
            window.addEventListener('hashchange', process, false);
        } else {
            window.attachEvent('onhashchange', process);
        }
    }

    function removeListener () {
        if (window.removeEventListener) {
            window.removeEventListener('hashchange', process);
        } else {
            window.detachEvent('onhashchange', process);
        }
    }
});<|endoftext|>


<commit_before>module.exports = {
  templateUrl: "assets/templates/search-container.html",
  controller: function() {
    var ctrl = this;

    ctrl.list = [
      {
        name: 'potato'
      }, {
        name: 'carott'
      }, {
        name: 'brocoli'
      }, {
        name: 'onion'
      }, {
        name: 'oncologic'
      }
    ]
  }
};<commit_msg>Fix typo<commit_after>module.exports = {
  templateUrl: "assets/templates/search-container.html",
  controller: function() {
    var ctrl = this;

    ctrl.list = [
      {
        name: 'potato'
      }, {
        name: 'carot'
      }, {
        name: 'brocoli'
      }, {
        name: 'onion'
      }, {
        name: 'oncologic'
      }
    ]
  }
};<|endoftext|>


<commit_before>/**
 * @description
 * 简单上传:点击按钮,直接选择文件上传
 * @author Jinqn
 * @date 2014-03-31
 */
UE.plugin.register('simpleupload', function (){
    var me = this,
        uploadInput;

    function initUploadBtn(){
        var container = me.container,
            wrapper = document.createElement('form'),
            form = document.createElement('form'),
            input = uploadInput = document.createElement('input'),
            iframe = document.createElement('iframe'),
            iframeId = 'edui_iframe_' + (+new Date()).toString(36),
            imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));

        input.type = 'file';
        input.accept = 'image/*';
        input.name = me.options.imageFieldName;
        input.style.cssText = 'display:none;width:0px;height:0px;border:0;margin:0;padding:0;position:absolute;';

        iframe.name = iframe.id = iframeId;
        iframe.style.cssText = 'display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;';

        form.target = iframeId;
        form.method = 'POST';
        form.enctype = 'multipart/form-data';
        form.action = imageActionUrl;
        form.style.cssText = 'display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;';

        wrapper.className = 'edui-' + me.options.theme;
        wrapper.id = me.ui.id + '_iframeupload';

        form.appendChild(input);
        form.appendChild(iframe);
        wrapper.appendChild(form);
        container.appendChild(form);

        domUtils.on(input, 'change', function(){
            var loadingId = 'loading_' + (+new Date()).toString(36);
            var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
            me.execCommand('inserthtml', '');

            function callback(){
                var link, json, loader, body = (iframe.contentDocument || iframe.contentWindow.contentDocument).body, result = body.innerText || body.textContent || '';
                try{
                    json = (new Function("return " + result))();
                    link = me.options.imageUrlPrefix + json.url;
                    if(json.state == 'SUCCESS' && json.url) {
                        loader = me.document.getElementById(loadingId);
                        loader.setAttribute('src', link);
                        loader.setAttribute('_src', link);
                        loader.removeAttribute('title');
                        domUtils.removeClasses(loader, 'loadingclass');
                    } else {
                        showErrorLoader && showErrorLoader(json.state);
                    }
                }catch(er){
                    showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
                }
                input.value = '';
                domUtils.un(iframe, 'load', callback);
            }
            function showErrorLoader(title){
                if(loadingId) {
                    var loader = me.document.getElementById(loadingId);
                    domUtils.removeClasses(loader, 'loadingclass');
                    domUtils.addClass(loader, 'loaderrorclass');
                    loader.setAttribute('title', title || '');
                }
            }
            domUtils.on(iframe, 'load', callback);
            form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
            form.submit();
        });
    }

    return {
        bindEvents:{
            /* 初始化简单上传按钮 */
            'ready': function(){
                //设置loading的样式
                utils.cssRule('loading',
                    '.loadingclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
                        '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
                        '}',
                    this.document);

                initUploadBtn();
            }
        },
        outputRule: function(root){
            utils.each(root.getNodesByTagName('img'),function(n){
                if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
                    n.parentNode.removeChild(n);
                }
            });
        },
        commands: {
            "simpleupload":{
                execCommand: function(){
                    uploadInput && uploadInput.click();
                }
            }
        }
    }
});<commit_msg>修改上传图片<commit_after>/**
 * @description
 * 简单上传:点击按钮,直接选择文件上传
 * @author Jinqn
 * @date 2014-03-31
 */
UE.plugin.register('simpleupload', function (){
    var me = this,
        uploadInput;

    function initUploadBtn(){
        var container = me.container,
            wrapper = document.createElement('form'),
            form = document.createElement('form'),
            input = uploadInput = document.createElement('input'),
            iframe = document.createElement('iframe'),
            iframeId = 'edui_iframe_' + (+new Date()).toString(36),
            imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));

        input.type = 'file';
        input.accept = 'image/*';
        input.name = me.options.imageFieldName;
        input.style.cssText = 'display:none;width:0px;height:0px;border:0;margin:0;padding:0;position:absolute;';

        iframe.name = iframe.id = iframeId;
        iframe.style.cssText = 'display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;';

        form.target = iframeId;
        form.method = 'POST';
        form.enctype = 'multipart/form-data';
        form.action = imageActionUrl;
        form.style.cssText = 'display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;';

        wrapper.className = 'edui-' + me.options.theme;
        wrapper.id = me.ui.id + '_iframeupload';

        form.appendChild(input);
        form.appendChild(iframe);
        wrapper.appendChild(form);
        container.appendChild(form);

        domUtils.on(input, 'change', function(){
            var loadingId = 'loading_' + (+new Date()).toString(36);
            var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
            me.execCommand('inserthtml', '');

            function callback(){
                var link, json, loader, body = (iframe.contentDocument || iframe.contentWindow.contentDocument).body, result = body.innerText || body.textContent || '';
                try{
                    json = (new Function("return " + result))();
                    link = me.options.imageUrlPrefix + json.url;
                    if(json.state == 'SUCCESS' && json.url) {
                        loader = me.document.getElementById(loadingId);
                        loader.setAttribute('src', link);
                        loader.setAttribute('_src', link);
                        loader.removeAttribute('title');
                        loader.removeAttribute('id');
                        domUtils.removeClasses(loader, 'loadingclass');
                    } else {
                        showErrorLoader && showErrorLoader(json.state);
                    }
                }catch(er){
                    showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
                }
                input.value = '';
                domUtils.un(iframe, 'load', callback);
            }
            function showErrorLoader(title){
                if(loadingId) {
                    var loader = me.document.getElementById(loadingId);
                    domUtils.removeClasses(loader, 'loadingclass');
                    domUtils.addClass(loader, 'loaderrorclass');
                    loader.setAttribute('title', title || '');
                }
            }
            domUtils.on(iframe, 'load', callback);
            form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
            form.submit();
        });
    }

    return {
        bindEvents:{
            /* 初始化简单上传按钮 */
            'ready': function(){
                //设置loading的样式
                utils.cssRule('loading',
                    '.loadingclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
                        '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
                        + this.options.themePath
                        + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
                        '}',
                    this.document);

                initUploadBtn();
            }
        },
        outputRule: function(root){
            utils.each(root.getNodesByTagName('img'),function(n){
                if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
                    n.parentNode.removeChild(n);
                }
            });
        },
        commands: {
            "simpleupload":{
                execCommand: function(){
                    uploadInput && uploadInput.click();
                }
            }
        }
    }
});<|endoftext|>


<commit_before>'use strict';

const verbSynonyms = ['teleport', 'port', 'portal'];

/**
 * Note: Developer Command a.k.a. cheat
 * Parses the input text and decides whether to return a teleport command.
 * The teleport keyword should be followed by the id of the node you want to teleport to.
 *
 * @class PortParser
 */
class TeleportParser {
  static parse(inputText) {
    const words = inputText.toLowerCase().match(/\b(\w+)\b/g);

    if (words && words.length === 2 && verbSynonyms.indexOf(words[0]) !== -1) {
      const nodeId = Number(words[1]);
      return { command: 'teleport', targetId: nodeId };
    }

    return null;
  }
}

module.exports = TeleportParser;
<commit_msg>fix jsdoc comment on teleportparser<commit_after>'use strict';

const verbSynonyms = ['teleport', 'port', 'portal'];

/**
 * Note: Developer Command a.k.a. cheat
 * Parses the input text and decides whether to return a teleport command.
 * The teleport keyword should be followed by the id of the node you want to teleport to.
 *
 * @class TeleportParser
 */
class TeleportParser {
  static parse(inputText) {
    const words = inputText.toLowerCase().match(/\b(\w+)\b/g);

    if (words && words.length === 2 && verbSynonyms.indexOf(words[0]) !== -1) {
      const nodeId = Number(words[1]);
      return { command: 'teleport', targetId: nodeId };
    }

    return null;
  }
}

module.exports = TeleportParser;
<|endoftext|>


<commit_before>Ext.namespace('Vps.Auto.Form');

Vps.Auto.Form.Window = Ext.extend(Ext.Window, {
    initComponent : function()
    {
        this.actions = {};

        if (!this.formConfig) this.formConfig = {};

        Ext.applyIf(this.formConfig, {
            baseCls: 'x-plain',
            controllerUrl: this.controllerUrl
        });
        this.autoForm = new Vps.Auto.FormPanel(this.formConfig);
        this.on('render', function() {
            this.getForm().waitMsgTarget = this.el;
        }, this);

        Ext.applyIf(this, {
            width: 300,
            height: 200,
            layout: 'fit',
            bodyStyle:'padding:5px;',
            plain: true,
            modal: true,
            buttons: [this.getAction('cancel'), this.getAction('save')]
        });

        this.items = [this.autoForm];

        this.relayEvents(this.autoForm, ['renderform']);
        this.addEvents({
            datachange: true
        });

        Vps.Auto.Form.Window.superclass.initComponent.call(this);
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            var action = this.getAutoForm().getAction('save');
            action.handler = function() {
                this.getForm().onSubmit(null, {
                    callback: function() {
                        this.hide();
                    },
                    scope: this
                });
            };
            this.actions[type] = action;
        } else if (type == 'cancel') {
            this.actions[type] = new Ext.Action({
                text    : 'Cancel',
                handler : function() {
                    this.hide();
                },
                scope   : this
            });
        } else {
            throw "unknown action-type: "+type;
        }
        return this.actions[type];
    },

    showAdd : function()
    {
        this.getAutoForm().onAdd();
        this.setTitle('add');
        this.show();
    },

    showEdit : function(id, options)
    {
        this.setTitle('edit');
        this.show();
        this.getAutoForm().load(id, options);
    },

    getAutoForm : function()
    {
        return this.autoForm;
    },

    getForm : function()
    {
        return this.getAutoForm().getForm();
    }
});
<commit_msg>bugfix speichern-action von window<commit_after>Ext.namespace('Vps.Auto.Form');

Vps.Auto.Form.Window = Ext.extend(Ext.Window, {
    initComponent : function()
    {
        this.actions = {};

        if (!this.formConfig) this.formConfig = {};

        Ext.applyIf(this.formConfig, {
            baseCls: 'x-plain',
            controllerUrl: this.controllerUrl
        });
        this.autoForm = new Vps.Auto.FormPanel(this.formConfig);
        this.on('renderform', function() {
            this.getForm().waitMsgTarget = this.el;
        }, this);

        Ext.applyIf(this, {
            width: 300,
            height: 200,
            layout: 'fit',
            bodyStyle:'padding:5px;',
            plain: true,
            modal: true,
            buttons: [this.getAction('cancel'), this.getAction('save')]
        });
        this.closeAction = 'hide';

        this.items = [this.autoForm];

        this.relayEvents(this.autoForm, ['renderform']);
        this.addEvents({
            datachange: true
        });

        Vps.Auto.Form.Window.superclass.initComponent.call(this);
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            var action = this.getAutoForm().getAction('save');
            action.setHandler(function() {
                this.getAutoForm().onSubmit({}, {
                    callback: function() {
                        this.hide();
                    },
                    scope: this
                });
            }, this);
            this.actions[type] = action;
        } else if (type == 'cancel') {
            this.actions[type] = new Ext.Action({
                text    : 'Cancel',
                handler : function() {
                    this.hide();
                },
                scope   : this
            });
        } else {
            throw "unknown action-type: "+type;
        }
        return this.actions[type];
    },

    showAdd : function()
    {
        this.getAutoForm().onAdd();
        this.setTitle('add');
        this.show();
    },

    showEdit : function(id, options)
    {
        this.setTitle('edit');
        this.show();
        this.getAutoForm().load(id, options);
    },

    getAutoForm : function()
    {
        return this.autoForm;
    },

    getForm : function()
    {
        return this.getAutoForm().getForm();
    }
});
<|endoftext|>


<commit_before>define("js!Class", ["js!core"], function (core) {
   /* Simple JavaScript Inheritance
    * By John Resig http://ejohn.org/
    * MIT Licensed.
    */
   // Inspired by base2 and Prototype
   var initializing = false, fnTest = /xyz/.test(function () {xyz;}) ? /\b_super\b/ : /.*/;

   // The base Class implementation (does nothing)
   this.Class = function () {
   };

   // Create a new Class that inherits from this class
   Class.extend = function (prop) {
      var _super = this.prototype;

      // Instantiate a base class (but only create the instance,
      // don't run the init constructor)
      initializing = true;
      var prototype = new this();
      initializing = false;

      // Copy the properties over onto the new prototype
      for (var name in prop) {
         // Check if we're overwriting an existing function
         prototype[name] = typeof prop[name] == "function" &&
            typeof _super[name] == "function" && fnTest.test(prop[name]) ?
            (function (name, fn) {
               return function () {
                  var tmp = this._super;

                  // Add a new ._super() method that is the same method
                  // but on the super-class
                  this._super = _super[name];

                  // The method only need to be bound temporarily, so we
                  // remove it when we're done executing
                  var ret = fn.apply(this, arguments);
                  this._super = tmp;

                  return ret;
               };
            })(name, prop[name]) :
            name == "_options" ? core.extend(true, this[name], prop[name]) : prop[name];
      }

      // The dummy class constructor
      function Class() {
         // All construction is actually done in the init method
         if (!initializing && this.init)
            this.init.apply(this, arguments);
      }

      // Populate our constructed prototype object
      Class.prototype = prototype;

      // Enforce the constructor to be what we expect
      Class.prototype.constructor = Class;

      // And make this class extendable
      Class.extend = arguments.callee;

      return Class;
   };

   return Class;
});<commit_msg>неправильно организовано наследование опций<commit_after>define("js!Class", ["js!core"], function (core) {
   /* Simple JavaScript Inheritance
    * By John Resig http://ejohn.org/
    * MIT Licensed.
    */
   // Inspired by base2 and Prototype
   var initializing = false, fnTest = /xyz/.test(function () {xyz;}) ? /\b_super\b/ : /.*/;

   // The base Class implementation (does nothing)
   this.Class = function () {
   };

   // Create a new Class that inherits from this class
   Class.extend = function (prop) {
      var _super = this.prototype;

      // Instantiate a base class (but only create the instance,
      // don't run the init constructor)
      initializing = true;
      var prototype = new this();
      initializing = false;

      // Copy the properties over onto the new prototype
      for (var name in prop) {
         // Check if we're overwriting an existing function
         prototype[name] = typeof prop[name] == "function" &&
            typeof _super[name] == "function" && fnTest.test(prop[name]) ?
            (function (name, fn) {
               return function () {
                  var tmp = this._super;

                  // Add a new ._super() method that is the same method
                  // but on the super-class
                  this._super = _super[name];

                  // The method only need to be bound temporarily, so we
                  // remove it when we're done executing
                  var ret = fn.apply(this, arguments);
                  this._super = tmp;

                  return ret;
               };
            })(name, prop[name]) :
            name == "_options" ? core.extend(true, this.prototype[name], prop[name]) : prop[name];
      }

      // The dummy class constructor
      function Class() {
         // All construction is actually done in the init method
         if (!initializing && this.init)
            this.init.apply(this, arguments);
      }

      // Populate our constructed prototype object
      Class.prototype = prototype;

      // Enforce the constructor to be what we expect
      Class.prototype.constructor = Class;

      // And make this class extendable
      Class.extend = arguments.callee;

      return Class;
   };

   return Class;
});<|endoftext|>


<commit_before>// jump modal
$(function() {

    var all;
    var visible;
    var active = -1;
    var lastFilter = '';
    var $body = $('#x-jump-body');
    var $list = $('#x-jump-list');
    var $filter = $('#x-jump-filter');
    var $modal = $('#x-jump');

    var update = function(filter) {
        lastFilter = filter;
        if (active >= 0) {
            visible[active].e.removeClass('active');
            active = -1;
        }
        visible = []
        var re = new RegExp(filter.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "gi");
        all.forEach(function (id) {
            id.e.detach();
            var text = id.text;
            if (filter) {
                text = id.text.replace(re, function (s) { return '' + s + ''; });
                if (text == id.text) {
                    return
                }
            }
            id.e.html(text + ' ' + '' + id.kind + '');
            visible.push(id);
        });
        $body.scrollTop(0);
        if (visible.length > 0) {
            active = 0;
            visible[active].e.addClass('active');
        }
        $list.append($.map(visible, function(identifier) { return identifier.e; }));
    }

    var incrActive = function(delta) {
        if (visible.length == 0) {
            return
        }
        visible[active].e.removeClass('active');
        active += delta;
        if (active < 0) {
            active = 0;
            $body.scrollTop(0);
        } else if (active >= visible.length) {
            active = visible.length - 1;
            $body.scrollTop($body[0].scrollHeight - $body[0].clientHeight);
        } else {
            var $e = visible[active].e;
            var t = $e.position().top;
            var b = t + $e.outerHeight(false);
            if (t <= 0) {
                $body.scrollTop($body.scrollTop() + t);
            } else if (b >= $body.outerHeight(false)) {
                $body.scrollTop($body.scrollTop() + b - $body.outerHeight(false));
            }
        }
        visible[active].e.addClass('active');
    }

    $modal.on('show.bs.modal', function() {
        if (!all) {
            all = []
            var kinds = {'c': 'constant', 'v': 'variable', 'f': 'function', 't': 'type', 'd': 'field', 'm': 'method'}
            $('*[id]').each(function() {
                var e = $(this);
                var id = e.attr('id');
                if (/^[^_][^-]*$/.test(id)) {
                    all.push({
                        text: id,
                        ltext: id.toLowerCase(),
                        kind: kinds[e.closest('[data-kind]').attr('data-kind')],
                        e: $('', {href: '#' + id, 'class': 'list-group-item', tabindex: '-1'})
                    });
                }
            });
            all.sort(function (a, b) {
                if (a.ltext > b.ltext) { return 1; }
                if (a.ltext < b.ltext) { return -1; }
                return 0
            });
        }
    }).on('shown.bs.modal', function() {
        update('');
        $filter.val('').focus();
    }).on('hide.bs.modal', function() {
        $filter.blur();
    }).on('click', '.list-group-item', function() {
        $modal.modal('hide');
    });

    $filter.on('change keyup', function() {
        var filter = $filter.val();
        if (filter.toUpperCase() != lastFilter.toUpperCase()) {
            update(filter);
        }
    }).on('keydown', function(e) {
        switch(e.which) {
        case 38: // up
            incrActive(-1);
            e.preventDefault();
            break;
        case 40: // down
            incrActive(1);
            e.preventDefault();
            break;
        case 13: // enter
            if (active >= 0) {
                visible[active].e[0].click();
            }
            break
        }
    });

});

// keyboard shortcuts
$(function() {
    var prevCh = null, prevTime = 0, modal = false;

    $('.modal').on({
        show: function() { modal = true; },
        hidden: function() { modal = false; }
    });

    $(document).on('keypress', function(e) {
        var combo = e.timeStamp - prevTime <= 1000;
        prevTime = 0;

        if (modal) {
            return true;
        }

        var t = e.target.tagName
        if (t == 'INPUT' ||
            t == 'SELECT' ||
            t == 'TEXTAREA' ) {
            return true;
        }

        if (e.target.contentEditable && e.target.contentEditable == 'true') {
            return true;
        }

        var ch = String.fromCharCode(e.which);

        if (combo) {
            switch (prevCh + ch) {
            case "gg":
                $('html,body').animate({scrollTop: 0},'fast');
                return false;
            case "gb":
                $('html,body').animate({scrollTop: $(document).height()},'fast');
                return false;
            case "gi":
                if ($('#pkg-index').length > 0) {
                    $('html,body').animate({scrollTop: $("#pkg-index").offset().top},'fast');
                    return false;
                }
            case "ge":
                if ($('#pkg-examples').length > 0) {
                    $('html,body').animate({scrollTop: $("#pkg-examples").offset().top},'fast');
                    return false;
                }
            }
        }

        switch (ch) {
        case "/":
            $('#x-search-query').focus();
            return false;
        case "?":
            $('#x-shortcuts').modal();
            return false;
        case  "f":
            if ($('#x-jump').length > 0) {
                $('#x-jump').modal();
                return false;
            }
        }

        prevCh = ch
        prevTime = e.timeStamp
        return true;
    });
});

// misc
$(function() {
    $('span.timeago').timeago();
    if (window.location.hash.substring(0, 9) == '#example-') {
       $(id).addClass('in').removeClass('collapse').height('auto');
    }

    $(document).on("click", "input.click-select", function(e) {
        $(e.target).select();
    });

    $('body').scrollspy({
        target: '.gddo-sidebar',
        offset: 10
    });
});
<commit_msg>Ignore metakey in keyboard shortcuts<commit_after>// jump modal
$(function() {

    var all;
    var visible;
    var active = -1;
    var lastFilter = '';
    var $body = $('#x-jump-body');
    var $list = $('#x-jump-list');
    var $filter = $('#x-jump-filter');
    var $modal = $('#x-jump');

    var update = function(filter) {
        lastFilter = filter;
        if (active >= 0) {
            visible[active].e.removeClass('active');
            active = -1;
        }
        visible = []
        var re = new RegExp(filter.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "gi");
        all.forEach(function (id) {
            id.e.detach();
            var text = id.text;
            if (filter) {
                text = id.text.replace(re, function (s) { return '' + s + ''; });
                if (text == id.text) {
                    return
                }
            }
            id.e.html(text + ' ' + '' + id.kind + '');
            visible.push(id);
        });
        $body.scrollTop(0);
        if (visible.length > 0) {
            active = 0;
            visible[active].e.addClass('active');
        }
        $list.append($.map(visible, function(identifier) { return identifier.e; }));
    }

    var incrActive = function(delta) {
        if (visible.length == 0) {
            return
        }
        visible[active].e.removeClass('active');
        active += delta;
        if (active < 0) {
            active = 0;
            $body.scrollTop(0);
        } else if (active >= visible.length) {
            active = visible.length - 1;
            $body.scrollTop($body[0].scrollHeight - $body[0].clientHeight);
        } else {
            var $e = visible[active].e;
            var t = $e.position().top;
            var b = t + $e.outerHeight(false);
            if (t <= 0) {
                $body.scrollTop($body.scrollTop() + t);
            } else if (b >= $body.outerHeight(false)) {
                $body.scrollTop($body.scrollTop() + b - $body.outerHeight(false));
            }
        }
        visible[active].e.addClass('active');
    }

    $modal.on('show.bs.modal', function() {
        if (!all) {
            all = []
            var kinds = {'c': 'constant', 'v': 'variable', 'f': 'function', 't': 'type', 'd': 'field', 'm': 'method'}
            $('*[id]').each(function() {
                var e = $(this);
                var id = e.attr('id');
                if (/^[^_][^-]*$/.test(id)) {
                    all.push({
                        text: id,
                        ltext: id.toLowerCase(),
                        kind: kinds[e.closest('[data-kind]').attr('data-kind')],
                        e: $('', {href: '#' + id, 'class': 'list-group-item', tabindex: '-1'})
                    });
                }
            });
            all.sort(function (a, b) {
                if (a.ltext > b.ltext) { return 1; }
                if (a.ltext < b.ltext) { return -1; }
                return 0
            });
        }
    }).on('shown.bs.modal', function() {
        update('');
        $filter.val('').focus();
    }).on('hide.bs.modal', function() {
        $filter.blur();
    }).on('click', '.list-group-item', function() {
        $modal.modal('hide');
    });

    $filter.on('change keyup', function() {
        var filter = $filter.val();
        if (filter.toUpperCase() != lastFilter.toUpperCase()) {
            update(filter);
        }
    }).on('keydown', function(e) {
        switch(e.which) {
        case 38: // up
            incrActive(-1);
            e.preventDefault();
            break;
        case 40: // down
            incrActive(1);
            e.preventDefault();
            break;
        case 13: // enter
            if (active >= 0) {
                visible[active].e[0].click();
            }
            break
        }
    });

});

// keyboard shortcuts
$(function() {
    var prevCh = null, prevTime = 0, modal = false;

    $('.modal').on({
        show: function() { modal = true; },
        hidden: function() { modal = false; }
    });

    $(document).on('keypress', function(e) {
        var combo = e.timeStamp - prevTime <= 1000;
        prevTime = 0;

        if (modal) {
            return true;
        }

        var t = e.target.tagName
        if (t == 'INPUT' ||
            t == 'SELECT' ||
            t == 'TEXTAREA' ) {
            return true;
        }

        if (e.target.contentEditable && e.target.contentEditable == 'true') {
            return true;
        }

        if (e.metaKey) {
            return true;
        }

        var ch = String.fromCharCode(e.which);

        if (combo) {
            switch (prevCh + ch) {
            case "gg":
                $('html,body').animate({scrollTop: 0},'fast');
                return false;
            case "gb":
                $('html,body').animate({scrollTop: $(document).height()},'fast');
                return false;
            case "gi":
                if ($('#pkg-index').length > 0) {
                    $('html,body').animate({scrollTop: $("#pkg-index").offset().top},'fast');
                    return false;
                }
            case "ge":
                if ($('#pkg-examples').length > 0) {
                    $('html,body').animate({scrollTop: $("#pkg-examples").offset().top},'fast');
                    return false;
                }
            }
        }

        switch (ch) {
        case "/":
            $('#x-search-query').focus();
            return false;
        case "?":
            $('#x-shortcuts').modal();
            return false;
        case  "f":
            if ($('#x-jump').length > 0) {
                $('#x-jump').modal();
                return false;
            }
        }

        prevCh = ch
        prevTime = e.timeStamp
        return true;
    });
});

// misc
$(function() {
    $('span.timeago').timeago();
    if (window.location.hash.substring(0, 9) == '#example-') {
       $(id).addClass('in').removeClass('collapse').height('auto');
    }

    $(document).on("click", "input.click-select", function(e) {
        $(e.target).select();
    });

    $('body').scrollspy({
        target: '.gddo-sidebar',
        offset: 10
    });
});
<|endoftext|>


<commit_before>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// *************************************************************************
//
// stack.js -- stack enabling targets (dialogs) to be "push"ed and "pop"ped
//
// To initiate a new target (dialog), call stack.push(target)
//
// To return to the previous target (dialog), call stack.pop()
//
// Each target type (dmenu, dform, etc.) needs to have methods for saving
// and restoring the target state. These can range from very simple (dmenu)
// to complicated (dbrowser).
//
"use strict";

define ([
    "jquery",
    "lib",
    "prototypes",
    "target"
], function (
    $,
    lib,
    prototypes,
    target
) {

    var
        // object for storing the stack
        _stack = [],

        // pop a target and its state off the stack
        // ARG1 (optional) - object to be merged into stateObj
        // ARG2 (optional) - boolean, whether to call start() (default: true)
        pop = function (mo, start) {
            start = (start === false) ? false : true;
            console.log("Entering stack.pop() with stack", _stack);
            var stackObj,
                type;
            _stack.pop();
            if (_stack.length === 0) {
                console.log("Stack empty - logging out");
                target.pull('logout').start();
                return;
            }
            stackObj = _stack[_stack.length - 1];
            if (typeof mo === 'object') {
                console.log("pop() was passed an object", mo);
                $.extend(stackObj.state, mo);
            }
            stackObj.pushed = false;
            console.log("Popped " + stackObj.target.name);
            type = stackObj.target.type;
            if (start) {
                lib.clearResult();
                stackObj.target.start();
            }
        },

        popWithoutStart = function (mo) {
            pop(mo, false);
        },

        // push a target and its state onto the stack
        push = function (tgt, obj, opts) {
            console.log("Entering stack.push() with target", tgt, "object", obj, "and opts", opts);
            // console.log("and stack", _stack);
            var targetName,
                flag,
                xtarget;
            if (obj === undefined || obj === null) {
                obj = {};
            }
            if (typeof tgt === "string") {
                targetName = tgt;
                tgt = target.pull(tgt);
            }
            if (typeof tgt !== "object") {
                console.log("ERROR in stack.push() - found no target object");
                return;
            }
            if (typeof opts === "object") {
                flag = opts.hasOwnProperty('flag') ? opts.flag : false;
                xtarget = opts.hasOwnProperty('xtarget') ? opts.xtarget : null;
                console.log("In stack.push(), setting flag", flag, "and xtarget", xtarget);
            }
            if (tgt.pushable) {
                _stack.push({
                    "flag": flag,
                    "push": true,
                    "state": obj,
                    "target": tgt,
                    "xtarget": xtarget
                });
            }
            lib.clearResult();
            tgt.start(obj);
        },

        getFlag = function () {
            return _stack[_stack.length - 1].flag;
        },
        getPush = function () {
            return _stack[_stack.length - 1].push;
        },
        getState = function () {
            return _stack[_stack.length - 1].state;
        },
        getTarget = function () {
            return _stack[_stack.length - 1].target;
        },
        getXTarget = function () {
            return _stack[_stack.length - 1].xtarget;
        },

        setFlag = function () {
            _stack[_stack.length - 1].flag = true;
        },
        setPush = function (newPush) {
            _stack[_stack.length - 1].push = newPush;
        },
        setState = function (newState) {
            _stack[_stack.length - 1].state = newState;
        },
        setTarget = function (newTarget) {
            _stack[_stack.length - 1].target = newTarget;
        },
        setXTarget = function (newXTarget) {
            _stack[_stack.length - 1].xtarget = newXTarget;
        },

        unsetFlag = function () {
            _stack[_stack.length - 1].flag = false;
        },
        unsetPush = function (newPush) {
            _stack[_stack.length - 1].push = undefined;
        },
        unsetState = function (newState) {
            _stack[_stack.length - 1].state = undefined;
        },
        unsetTarget = function (newTarget) {
            _stack[_stack.length - 1].target = undefined;
        },
        unsetXTarget = function (newXTarget) {
            _stack[_stack.length - 1].xtarget = undefined;
        },

        // unwind stack until given target is reached
        unwindToTarget = function (tname) {
            console.log("Unwinding the stack to target " + tname);
            var tgt;
            for (var i = _stack.length; i > 0; i--) {
                tgt = _stack[i - 1].target;
                if (tgt.name === tname) {
                   break;
                }
                popWithoutStart();
            }
            tgt.start();
        },

        unwindToFlag = function () {
            console.log("Unwinding the stack to flag");
            var flag;
            for (var i = _stack.length; i > 0; i--) {
                flag = _stack[i - 1].flag;
                if (flag) {
                   break;
                }
                popWithoutStart();
            }
            _stack[_stack.length - 1].target.start();
        };

    return {
        "getFlag": getFlag,
        "getPush": getPush,
        "getState": getState,
        "getTarget": getTarget,
        "getXTarget": getXTarget,
        "pop": pop,
        "popWithoutStart": popWithoutStart,
        "push": push,
        "setFlag": setFlag,
        "setPush": setPush,
        "setState": setState,
        "setTarget": setTarget,
        "setXTarget": setXTarget,
        "unsetFlag": unsetFlag,
        "unsetPush": unsetPush,
        "unsetState": unsetState,
        "unsetTarget": unsetTarget,
        "unsetXTarget": unsetXTarget,
        "unwindToFlag": unwindToFlag,
        "unwindToTarget": unwindToTarget
    };

});
<commit_msg>stack: unsetFoo functions take no argument<commit_after>// *************************************************************************
// Copyright (c) 2014-2017, SUSE LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of SUSE LLC nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// *************************************************************************
//
// stack.js -- stack enabling targets (dialogs) to be "push"ed and "pop"ped
//
// To initiate a new target (dialog), call stack.push(target)
//
// To return to the previous target (dialog), call stack.pop()
//
// Each target type (dmenu, dform, etc.) needs to have methods for saving
// and restoring the target state. These can range from very simple (dmenu)
// to complicated (dbrowser).
//
"use strict";

define ([
    "jquery",
    "lib",
    "prototypes",
    "target"
], function (
    $,
    lib,
    prototypes,
    target
) {

    var
        // object for storing the stack
        _stack = [],

        // pop a target and its state off the stack
        // ARG1 (optional) - object to be merged into stateObj
        // ARG2 (optional) - boolean, whether to call start() (default: true)
        pop = function (mo, start) {
            start = (start === false) ? false : true;
            console.log("Entering stack.pop() with stack", _stack);
            var stackObj,
                type;
            _stack.pop();
            if (_stack.length === 0) {
                console.log("Stack empty - logging out");
                target.pull('logout').start();
                return;
            }
            stackObj = _stack[_stack.length - 1];
            if (typeof mo === 'object') {
                console.log("pop() was passed an object", mo);
                $.extend(stackObj.state, mo);
            }
            stackObj.pushed = false;
            console.log("Popped " + stackObj.target.name);
            type = stackObj.target.type;
            if (start) {
                lib.clearResult();
                stackObj.target.start();
            }
        },

        popWithoutStart = function (mo) {
            pop(mo, false);
        },

        // push a target and its state onto the stack
        push = function (tgt, obj, opts) {
            console.log("Entering stack.push() with target", tgt, "object", obj, "and opts", opts);
            // console.log("and stack", _stack);
            var flag,
                xtarget;
            if (obj === undefined || obj === null) {
                obj = {};
            }
            if (typeof tgt === "string") {
                tgt = target.pull(tgt);
            }
            if (typeof tgt !== "object") {
                console.log("ERROR in stack.push() - found no target object");
                return;
            }
            if (typeof opts === "object") {
                flag = opts.hasOwnProperty('flag') ? opts.flag : false;
                xtarget = opts.hasOwnProperty('xtarget') ? opts.xtarget : null;
                console.log("In stack.push(), setting flag", flag, "and xtarget", xtarget);
            }
            if (tgt.pushable) {
                _stack.push({
                    "flag": flag,
                    "push": true,
                    "state": obj,
                    "target": tgt,
                    "xtarget": xtarget
                });
            }
            lib.clearResult();
            tgt.start(obj);
        },

        getFlag = function () {
            return _stack[_stack.length - 1].flag;
        },
        getPush = function () {
            return _stack[_stack.length - 1].push;
        },
        getState = function () {
            return _stack[_stack.length - 1].state;
        },
        getTarget = function () {
            return _stack[_stack.length - 1].target;
        },
        getXTarget = function () {
            return _stack[_stack.length - 1].xtarget;
        },

        setFlag = function () {
            _stack[_stack.length - 1].flag = true;
        },
        setPush = function (newPush) {
            _stack[_stack.length - 1].push = newPush;
        },
        setState = function (newState) {
            _stack[_stack.length - 1].state = newState;
        },
        setTarget = function (newTarget) {
            _stack[_stack.length - 1].target = newTarget;
        },
        setXTarget = function (newXTarget) {
            _stack[_stack.length - 1].xtarget = newXTarget;
        },

        unsetFlag = function () {
            _stack[_stack.length - 1].flag = false;
        },
        unsetPush = function () {
            _stack[_stack.length - 1].push = undefined;
        },
        unsetState = function () {
            _stack[_stack.length - 1].state = undefined;
        },
        unsetTarget = function () {
            _stack[_stack.length - 1].target = undefined;
        },
        unsetXTarget = function () {
            _stack[_stack.length - 1].xtarget = undefined;
        },

        // unwind stack until given target is reached
        unwindToTarget = function (tname) {
            console.log("Unwinding the stack to target " + tname);
            var tgt;
            for (var i = _stack.length; i > 0; i--) {
                tgt = _stack[i - 1].target;
                if (tgt.name === tname) {
                   break;
                }
                popWithoutStart();
            }
            tgt.start();
        },

        unwindToFlag = function () {
            console.log("Unwinding the stack to flag");
            var flag;
            for (var i = _stack.length; i > 0; i--) {
                flag = _stack[i - 1].flag;
                if (flag) {
                   break;
                }
                popWithoutStart();
            }
            _stack[_stack.length - 1].target.start();
        };

    return {
        "getFlag": getFlag,
        "getPush": getPush,
        "getState": getState,
        "getTarget": getTarget,
        "getXTarget": getXTarget,
        "pop": pop,
        "popWithoutStart": popWithoutStart,
        "push": push,
        "setFlag": setFlag,
        "setPush": setPush,
        "setState": setState,
        "setTarget": setTarget,
        "setXTarget": setXTarget,
        "unsetFlag": unsetFlag,
        "unsetPush": unsetPush,
        "unsetState": unsetState,
        "unsetTarget": unsetTarget,
        "unsetXTarget": unsetXTarget,
        "unwindToFlag": unwindToFlag,
        "unwindToTarget": unwindToTarget
    };

});
<|endoftext|>