<commit_before>const chalk = require('chalk');
const packagejs = require('../../package.json');
const semver = require('semver');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
const jhipsterConstants = require('generator-jhipster/generators/generator-constants');

module.exports = class extends BaseGenerator {
    get initializing() {
        return {
            init() {
                // This adds support for a `--all-entities` flag
                this.option('all-entities', {
                    desc: 'Apply grpc to all entities',
                    type: Boolean,
                    defaults: false
                });
            },
            readConfig() {
                this.jhipsterAppConfig = this.getAllJhipsterConfig();
                if (!this.jhipsterAppConfig) {
                    this.error('Can\'t read .yo-rc.json');
                }
            },
            displayLogo: function () {
                this.log('Welcome to the ' + chalk.red('JHipster grpc') + ' generator! ' + chalk.yellow('v' + packagejs.version + '\n'));
            },
            checkJhipster() {
                const currentJhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
                const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
                if (!semver.satisfies(currentJhipsterVersion, minimumJhipsterVersion)) {
                    this.warning(`\nYour generated project used an old JHipster version (${currentJhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
                }
            },
            checkAuthentication() {
                if(this.jhipsterAppConfig.authenticationType === 'oauth2') {
                    this.log(chalk.red('OIDC/Oauth authentication is not supported at the moment'));
                    this.abort = true;
                }
            }
        };
    }

    prompting() {
        if (this.abort) return;
        this.entities = [];
        this.existingEntitiesNames = this.getExistingEntities()
            .filter(entity => entity.definition.service === 'serviceClass' || entity.definition.service === 'serviceImpl')
            .map(entity => entity.name);

        if (this.existingEntitiesNames.length === 0) {
            this.log(chalk.yellow('No existing entities with a service layer found.'));
            return;
        }

        if (this.options.allEntities) {
            this.entities = this.existingEntitiesNames;
            return;
        }

        const done = this.async();

        const prompts = [{
            type: 'checkbox',
            name: 'entities',
            message: 'Select existing entities for which you want to add gRPC endpoints' ,
            choices: this.existingEntitiesNames
        }];

        this.prompt(prompts).then((props) => {
            this.entities = props.entities;
            done();
        });
    }

    get writing() {
        return {
            writeCommonFiles() {
                if (this.abort) return;
                // function to use directly template
                this.template = function (source, destination) {
                    this.fs.copyTpl(
                        this.templatePath(source),
                        this.destinationPath(destination),
                        this
                    );
                };

                this.addCompileDependency = function (groupId, artifactId, version, buildTool) {
                    if (buildTool === 'gradle') {
                        this.addGradleDependency('compile', groupId, artifactId, version);
                    } else {
                        this.addMavenDependency(groupId, artifactId, version);
                    }
                };

                this.baseName = this.jhipsterAppConfig.baseName;
                this.mainClass = this.getMainClassName();
                this.packageFolder = this.jhipsterAppConfig.packageFolder;
                this.packageName = this.jhipsterAppConfig.packageName;
                this.applicationType = this.jhipsterAppConfig.applicationType;
                this.authenticationType = this.jhipsterAppConfig.authenticationType;
                this.databaseType = this.jhipsterAppConfig.databaseType;
                this.searchEngine = this.jhipsterAppConfig.searchEngine;
                this.skipUserManagement = this.jhipsterAppConfig.skipUserManagement;
                if (this.applicationType === 'gateway' && this.authenticationType === 'uaa') {
                    this.skipUserManagement = true;
                }
                this.buildTool = this.jhipsterAppConfig.buildTool;
                this.cacheManagerIsAvailable = ['ehcache', 'hazelcast', 'infinispan'].includes(this.jhipsterAppConfig.cacheProvider) || this.applicationType === 'gateway';
                this.messageBroker = this.jhipsterAppConfig.messageBroker;

                const javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
                const testDir = `${jhipsterConstants.SERVER_TEST_SRC_DIR + this.packageFolder}/`;
                const protoDir = jhipsterConstants.MAIN_DIR + 'proto/';
                const protoPackageDir = protoDir + this.packageFolder + '/';

                if (this.databaseType === 'sql' && this.authenticationType !== 'oauth2') {
                    this.idProtoType = 'int64';
                    this.idProtoWrappedType = 'Int64Value';
                } else {
                    this.idProtoType = 'string';
                    this.idProtoWrappedType = 'StringValue';
                }

                this.template('_date.proto', protoDir + 'util/date.proto');
                this.template('_decimal.proto', protoDir + 'util/decimal.proto');
                this.template('_pagination.proto', protoDir + 'util/pagination.proto');
                this.template('_queryfilters.proto', protoDir + 'util/queryfilters.proto');

                this.template('_AuthenticationInterceptor.java', javaDir + 'grpc/AuthenticationInterceptor.java');
                this.template('_AuthenticationInterceptorTest.java', testDir + 'grpc/AuthenticationInterceptorTest.java');

                this.template('_ProtobufMappers.java', javaDir + 'grpc/ProtobufMappers.java');

                this.template('_configprops.proto', protoPackageDir + 'configprops.proto');
                this.template('_ConfigurationPropertiesReportService.java', javaDir + 'grpc/ConfigurationPropertiesReportService.java');
                this.template('_ConfigurationPropertiesReportServiceIntTest.java', testDir + 'grpc/ConfigurationPropertiesReportServiceIntTest.java');

                this.template('_environment.proto', protoPackageDir + 'environment.proto');
                this.template('_EnvironmentService.java', javaDir + 'grpc/EnvironmentService.java');
                this.template('_EnvironmentServiceIntTest.java', testDir + 'grpc/EnvironmentServiceIntTest.java');

                this.template('_health.proto', protoPackageDir + 'health.proto');
                this.template('_HealthService.java', javaDir + 'grpc/HealthService.java');
                this.template('_HealthServiceIntTest.java', testDir + 'grpc/HealthServiceIntTest.java');

                this.template('_loggers.proto', protoPackageDir + 'loggers.proto');
                this.template('_LoggersService.java', javaDir + 'grpc/LoggersService.java');
                this.template('_LoggersServiceIntTest.java', testDir + 'grpc/LoggersServiceIntTest.java');

                //this.template('_metric.proto', protoPackageDir + 'metric.proto');
                //this.template('_MetricService.java', javaDir + 'grpc/MetricService.java');
                //this.template('_MetricServiceIntTest.java', testDir + 'grpc/MetricServiceIntTest.java');

                this.template('_info.proto', protoPackageDir + 'info.proto');
                this.template('_InfoService.java', javaDir + 'grpc/InfoService.java');
                this.template('_InfoServiceIntTest.java', testDir + 'grpc/InfoServiceIntTest.java');

                this.grpcVersion = '1.6.1';
                this.protocVersion = '3.1.0';
                this.reactiveGrpcVersion = '0.7.2';

                this.addCompileDependency('org.lognet', 'grpc-spring-boot-starter', '2.0.0', this.buildTool);
                this.addCompileDependency('com.google.protobuf', 'protobuf-java', this.protocVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-core', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-context', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-netty', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-protobuf', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-stub', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.projectreactor', 'reactor-core', '3.1.1.RELEASE', this.buildTool);
                this.addCompileDependency('com.salesforce.servicelibs', 'reactor-grpc-stub', this.reactiveGrpcVersion, this.buildTool);

                if (this.buildTool === 'maven') {
                    this.addMavenRepository('jcenter', 'http://jcenter.bintray.com');
                    this.addMavenPlugin('org.xolstice.maven.plugins', 'protobuf-maven-plugin', '0.5.0',
                        '                ' +
                        '<configuration>' + '\n                ' +
                        '    <protocArtifact>com.google.protobuf:protoc:' + this.protocVersion + ':exe:${os.detected.classifier}</protocArtifact>' + '\n                ' +
                        '    <pluginId>grpc-java</pluginId>' + '\n                ' +
                        '    <pluginArtifact>io.grpc:protoc-gen-grpc-java:'+ this.grpcVersion + ':exe:${os.detected.classifier}</pluginArtifact>' + '\n                ' +
                        '</configuration>' + '\n                ' +
                        '<executions>' + '\n                ' +
                        '    <execution>' + '\n                ' +
                        '        <goals>' + '\n                ' +
                        '            <goal>compile</goal>' + '\n                ' +
                        '            <goal>compile-custom</goal>' + '\n                ' +
                        '        </goals>' + '\n                ' +
                        '        <configuration>' + '\n                ' +
                        '            <protocPlugins>' + '\n                ' +
                        '                <protocPlugin>' + '\n                ' +
                        '                    <id>reactor-grpc</id>' + '\n                ' +
                        '                    <groupId>com.salesforce.servicelibs</groupId>' + '\n                ' +
                        '                    <artifactId>reactor-grpc</artifactId>' + '\n                ' +
                        '                    <version>' + this.reactiveGrpcVersion + '</version>' + '\n                ' +
                        '                    <mainClass>com.salesforce.reactorgrpc.ReactorGrpcGenerator</mainClass>' + '\n                ' +
                        '                </protocPlugin>' + '\n                ' +
                        '            </protocPlugins>' + '\n                ' +
                        '        </configuration>' + '\n                ' +
                        '    </execution>' + '\n                ' +
                        '</executions>'
                    );
                    this.replaceContent('pom.xml', '<build>\n        <defaultGoal>',
                        '<build>' + '\n        ' +
                        '<extensions>' + '\n        ' +
                        '    <extension>' + '\n        ' +
                        '        <groupId>kr.motd.maven</groupId>' + '\n        ' +
                        '        <artifactId>os-maven-plugin</artifactId>' + '\n        ' +
                        '        <version>1.4.1.Final</version>' + '\n        ' +
                        '    </extension>' + '\n        ' +
                        '</extensions>' + '\n        ' +
                        '<defaultGoal>'
                    );

                } else {
                    this.copy('.mvn/mvnw', '.mvn/mvnw');
                    this.copy('.mvn/mvnw.cmd', '.mvn/mvnw.cmd');
                    this.copy('.mvn/wrapper/maven-wrapper.jar', '.mvn/wrapper/maven-wrapper.jar');
                    this.copy('.mvn/wrapper/maven-wrapper.properties', '.mvn/wrapper/maven-wrapper.properties');
                    this.template('_reactive-grpc-pom.xml', 'gradle/reactive-grpc-pom.xml');
                    this.template('_grpc.gradle', 'gradle/grpc.gradle');
                    this.addGradleMavenRepository('http://jcenter.bintray.com');
                    this.addGradlePlugin('com.google.protobuf', 'protobuf-gradle-plugin', '0.8.1');
                    this.applyFromGradleScript('gradle/grpc');
                }

                if (!this.skipUserManagement || this.authenticationType === 'oauth2') {
                    this.template('_account.proto', protoPackageDir + 'account.proto');
                    this.template('_user.proto', protoPackageDir + 'user.proto');
                    this.template('_UserProtoMapper.java', javaDir + 'grpc/UserProtoMapper.java');
                    this.template('_UserGrpcService.java', javaDir + 'grpc/UserGrpcService.java');
                    this.template('_UserGrpcServiceIntTest.java', testDir + 'grpc/UserGrpcServiceIntTest.java');
                    if (this.databaseType === 'sql' || this.databaseType === 'mongodb') {
                        this.template('_audit.proto', protoPackageDir + 'audit.proto');
                        this.template('_AuditGrpcService.java', javaDir + 'grpc/AuditGrpcService.java');
                        this.template('_AuditGrpcServiceIntTest.java', testDir + 'grpc/AuditGrpcServiceIntTest.java');
                    }
                    if (this.authenticationType === 'jwt') {
                        this.template('_jwt.proto', protoPackageDir + 'jwt.proto');
                        this.template('_JWTService.java', javaDir + 'grpc/JWTService.java');
                        this.template('_JWTServiceIntTest.java', testDir + 'grpc/JWTServiceIntTest.java');
                    }
                }

                if (!this.skipUserManagement || this.authenticationType === 'oauth2' && ['monolith', 'gateway'].includes(this.applicationType)) {
                    this.template('_AccountService.java', javaDir + 'grpc/AccountService.java');
                    this.template('_AccountServiceIntTest.java', testDir + 'grpc/AccountServiceIntTest.java');
                }

            },

            updateExistinfEntities() {
                if (this.abort) return;
                this.entities.forEach(entityName => {
                    this.updateEntityConfig('.jhipster/' + entityName + '.json', 'grpcService', true);
                });
            },

            registering: function () {
                if (this.abort) return;
                try {
                    this.registerModule('generator-jhipster-grpc', 'entity', 'post', 'entity', 'Adds support for gRPC and generates gRPC CRUD services');
                } catch (err) {
                    this.log(chalk.red.bold('WARN!') + ' Could not register as a jhipster entity post creation hook...\n');
                }
            },

            regenerateEntities: function () {
                if (this.abort) return;
                if (this.entities.length !== 0) {
                    this.log(chalk.green('Regenerating entities with gRPC service'));
                }
                this.entities.forEach(entity => {
                    this.composeWith('jhipster:entity', {
                        regenerate: true,
                        'skip-install': true,
                        force: this.options['force'],
                        'skip-server':true,
                        'skip-client':true,
                        arguments: [entity]
                    });
                });
            }
        };
    }

    end() {
        if (this.abort) return;
        this.log('End of grpc generator');
    }
};
<commit_msg>Set https for jcenter<commit_after>const chalk = require('chalk');
const packagejs = require('../../package.json');
const semver = require('semver');
const BaseGenerator = require('generator-jhipster/generators/generator-base');
const jhipsterConstants = require('generator-jhipster/generators/generator-constants');

module.exports = class extends BaseGenerator {
    get initializing() {
        return {
            init() {
                // This adds support for a `--all-entities` flag
                this.option('all-entities', {
                    desc: 'Apply grpc to all entities',
                    type: Boolean,
                    defaults: false
                });
            },
            readConfig() {
                this.jhipsterAppConfig = this.getAllJhipsterConfig();
                if (!this.jhipsterAppConfig) {
                    this.error('Can\'t read .yo-rc.json');
                }
            },
            displayLogo: function () {
                this.log('Welcome to the ' + chalk.red('JHipster grpc') + ' generator! ' + chalk.yellow('v' + packagejs.version + '\n'));
            },
            checkJhipster() {
                const currentJhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
                const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
                if (!semver.satisfies(currentJhipsterVersion, minimumJhipsterVersion)) {
                    this.warning(`\nYour generated project used an old JHipster version (${currentJhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
                }
            },
            checkAuthentication() {
                if(this.jhipsterAppConfig.authenticationType === 'oauth2') {
                    this.log(chalk.red('OIDC/Oauth authentication is not supported at the moment'));
                    this.abort = true;
                }
            }
        };
    }

    prompting() {
        if (this.abort) return;
        this.entities = [];
        this.existingEntitiesNames = this.getExistingEntities()
            .filter(entity => entity.definition.service === 'serviceClass' || entity.definition.service === 'serviceImpl')
            .map(entity => entity.name);

        if (this.existingEntitiesNames.length === 0) {
            this.log(chalk.yellow('No existing entities with a service layer found.'));
            return;
        }

        if (this.options.allEntities) {
            this.entities = this.existingEntitiesNames;
            return;
        }

        const done = this.async();

        const prompts = [{
            type: 'checkbox',
            name: 'entities',
            message: 'Select existing entities for which you want to add gRPC endpoints' ,
            choices: this.existingEntitiesNames
        }];

        this.prompt(prompts).then((props) => {
            this.entities = props.entities;
            done();
        });
    }

    get writing() {
        return {
            writeCommonFiles() {
                if (this.abort) return;
                // function to use directly template
                this.template = function (source, destination) {
                    this.fs.copyTpl(
                        this.templatePath(source),
                        this.destinationPath(destination),
                        this
                    );
                };

                this.addCompileDependency = function (groupId, artifactId, version, buildTool) {
                    if (buildTool === 'gradle') {
                        this.addGradleDependency('compile', groupId, artifactId, version);
                    } else {
                        this.addMavenDependency(groupId, artifactId, version);
                    }
                };

                this.baseName = this.jhipsterAppConfig.baseName;
                this.mainClass = this.getMainClassName();
                this.packageFolder = this.jhipsterAppConfig.packageFolder;
                this.packageName = this.jhipsterAppConfig.packageName;
                this.applicationType = this.jhipsterAppConfig.applicationType;
                this.authenticationType = this.jhipsterAppConfig.authenticationType;
                this.databaseType = this.jhipsterAppConfig.databaseType;
                this.searchEngine = this.jhipsterAppConfig.searchEngine;
                this.skipUserManagement = this.jhipsterAppConfig.skipUserManagement;
                if (this.applicationType === 'gateway' && this.authenticationType === 'uaa') {
                    this.skipUserManagement = true;
                }
                this.buildTool = this.jhipsterAppConfig.buildTool;
                this.cacheManagerIsAvailable = ['ehcache', 'hazelcast', 'infinispan'].includes(this.jhipsterAppConfig.cacheProvider) || this.applicationType === 'gateway';
                this.messageBroker = this.jhipsterAppConfig.messageBroker;

                const javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
                const testDir = `${jhipsterConstants.SERVER_TEST_SRC_DIR + this.packageFolder}/`;
                const protoDir = jhipsterConstants.MAIN_DIR + 'proto/';
                const protoPackageDir = protoDir + this.packageFolder + '/';

                if (this.databaseType === 'sql' && this.authenticationType !== 'oauth2') {
                    this.idProtoType = 'int64';
                    this.idProtoWrappedType = 'Int64Value';
                } else {
                    this.idProtoType = 'string';
                    this.idProtoWrappedType = 'StringValue';
                }

                this.template('_date.proto', protoDir + 'util/date.proto');
                this.template('_decimal.proto', protoDir + 'util/decimal.proto');
                this.template('_pagination.proto', protoDir + 'util/pagination.proto');
                this.template('_queryfilters.proto', protoDir + 'util/queryfilters.proto');

                this.template('_AuthenticationInterceptor.java', javaDir + 'grpc/AuthenticationInterceptor.java');
                this.template('_AuthenticationInterceptorTest.java', testDir + 'grpc/AuthenticationInterceptorTest.java');

                this.template('_ProtobufMappers.java', javaDir + 'grpc/ProtobufMappers.java');

                this.template('_configprops.proto', protoPackageDir + 'configprops.proto');
                this.template('_ConfigurationPropertiesReportService.java', javaDir + 'grpc/ConfigurationPropertiesReportService.java');
                this.template('_ConfigurationPropertiesReportServiceIntTest.java', testDir + 'grpc/ConfigurationPropertiesReportServiceIntTest.java');

                this.template('_environment.proto', protoPackageDir + 'environment.proto');
                this.template('_EnvironmentService.java', javaDir + 'grpc/EnvironmentService.java');
                this.template('_EnvironmentServiceIntTest.java', testDir + 'grpc/EnvironmentServiceIntTest.java');

                this.template('_health.proto', protoPackageDir + 'health.proto');
                this.template('_HealthService.java', javaDir + 'grpc/HealthService.java');
                this.template('_HealthServiceIntTest.java', testDir + 'grpc/HealthServiceIntTest.java');

                this.template('_loggers.proto', protoPackageDir + 'loggers.proto');
                this.template('_LoggersService.java', javaDir + 'grpc/LoggersService.java');
                this.template('_LoggersServiceIntTest.java', testDir + 'grpc/LoggersServiceIntTest.java');

                //this.template('_metric.proto', protoPackageDir + 'metric.proto');
                //this.template('_MetricService.java', javaDir + 'grpc/MetricService.java');
                //this.template('_MetricServiceIntTest.java', testDir + 'grpc/MetricServiceIntTest.java');

                this.template('_info.proto', protoPackageDir + 'info.proto');
                this.template('_InfoService.java', javaDir + 'grpc/InfoService.java');
                this.template('_InfoServiceIntTest.java', testDir + 'grpc/InfoServiceIntTest.java');

                this.grpcVersion = '1.6.1';
                this.protocVersion = '3.1.0';
                this.reactiveGrpcVersion = '0.7.2';

                this.addCompileDependency('org.lognet', 'grpc-spring-boot-starter', '2.0.0', this.buildTool);
                this.addCompileDependency('com.google.protobuf', 'protobuf-java', this.protocVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-core', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-context', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-netty', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-protobuf', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-stub', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.projectreactor', 'reactor-core', '3.1.1.RELEASE', this.buildTool);
                this.addCompileDependency('com.salesforce.servicelibs', 'reactor-grpc-stub', this.reactiveGrpcVersion, this.buildTool);

                if (this.buildTool === 'maven') {
                    this.addMavenRepository('jcenter', 'https://jcenter.bintray.com');
                    this.addMavenPlugin('org.xolstice.maven.plugins', 'protobuf-maven-plugin', '0.5.0',
                        '                ' +
                        '<configuration>' + '\n                ' +
                        '    <protocArtifact>com.google.protobuf:protoc:' + this.protocVersion + ':exe:${os.detected.classifier}</protocArtifact>' + '\n                ' +
                        '    <pluginId>grpc-java</pluginId>' + '\n                ' +
                        '    <pluginArtifact>io.grpc:protoc-gen-grpc-java:'+ this.grpcVersion + ':exe:${os.detected.classifier}</pluginArtifact>' + '\n                ' +
                        '</configuration>' + '\n                ' +
                        '<executions>' + '\n                ' +
                        '    <execution>' + '\n                ' +
                        '        <goals>' + '\n                ' +
                        '            <goal>compile</goal>' + '\n                ' +
                        '            <goal>compile-custom</goal>' + '\n                ' +
                        '        </goals>' + '\n                ' +
                        '        <configuration>' + '\n                ' +
                        '            <protocPlugins>' + '\n                ' +
                        '                <protocPlugin>' + '\n                ' +
                        '                    <id>reactor-grpc</id>' + '\n                ' +
                        '                    <groupId>com.salesforce.servicelibs</groupId>' + '\n                ' +
                        '                    <artifactId>reactor-grpc</artifactId>' + '\n                ' +
                        '                    <version>' + this.reactiveGrpcVersion + '</version>' + '\n                ' +
                        '                    <mainClass>com.salesforce.reactorgrpc.ReactorGrpcGenerator</mainClass>' + '\n                ' +
                        '                </protocPlugin>' + '\n                ' +
                        '            </protocPlugins>' + '\n                ' +
                        '        </configuration>' + '\n                ' +
                        '    </execution>' + '\n                ' +
                        '</executions>'
                    );
                    this.replaceContent('pom.xml', '<build>\n        <defaultGoal>',
                        '<build>' + '\n        ' +
                        '<extensions>' + '\n        ' +
                        '    <extension>' + '\n        ' +
                        '        <groupId>kr.motd.maven</groupId>' + '\n        ' +
                        '        <artifactId>os-maven-plugin</artifactId>' + '\n        ' +
                        '        <version>1.4.1.Final</version>' + '\n        ' +
                        '    </extension>' + '\n        ' +
                        '</extensions>' + '\n        ' +
                        '<defaultGoal>'
                    );

                } else {
                    this.copy('.mvn/mvnw', '.mvn/mvnw');
                    this.copy('.mvn/mvnw.cmd', '.mvn/mvnw.cmd');
                    this.copy('.mvn/wrapper/maven-wrapper.jar', '.mvn/wrapper/maven-wrapper.jar');
                    this.copy('.mvn/wrapper/maven-wrapper.properties', '.mvn/wrapper/maven-wrapper.properties');
                    this.template('_reactive-grpc-pom.xml', 'gradle/reactive-grpc-pom.xml');
                    this.template('_grpc.gradle', 'gradle/grpc.gradle');
                    this.addGradleMavenRepository('https://jcenter.bintray.com');
                    this.addGradlePlugin('com.google.protobuf', 'protobuf-gradle-plugin', '0.8.1');
                    this.applyFromGradleScript('gradle/grpc');
                }

                if (!this.skipUserManagement || this.authenticationType === 'oauth2') {
                    this.template('_account.proto', protoPackageDir + 'account.proto');
                    this.template('_user.proto', protoPackageDir + 'user.proto');
                    this.template('_UserProtoMapper.java', javaDir + 'grpc/UserProtoMapper.java');
                    this.template('_UserGrpcService.java', javaDir + 'grpc/UserGrpcService.java');
                    this.template('_UserGrpcServiceIntTest.java', testDir + 'grpc/UserGrpcServiceIntTest.java');
                    if (this.databaseType === 'sql' || this.databaseType === 'mongodb') {
                        this.template('_audit.proto', protoPackageDir + 'audit.proto');
                        this.template('_AuditGrpcService.java', javaDir + 'grpc/AuditGrpcService.java');
                        this.template('_AuditGrpcServiceIntTest.java', testDir + 'grpc/AuditGrpcServiceIntTest.java');
                    }
                    if (this.authenticationType === 'jwt') {
                        this.template('_jwt.proto', protoPackageDir + 'jwt.proto');
                        this.template('_JWTService.java', javaDir + 'grpc/JWTService.java');
                        this.template('_JWTServiceIntTest.java', testDir + 'grpc/JWTServiceIntTest.java');
                    }
                }

                if (!this.skipUserManagement || this.authenticationType === 'oauth2' && ['monolith', 'gateway'].includes(this.applicationType)) {
                    this.template('_AccountService.java', javaDir + 'grpc/AccountService.java');
                    this.template('_AccountServiceIntTest.java', testDir + 'grpc/AccountServiceIntTest.java');
                }

            },

            updateExistinfEntities() {
                if (this.abort) return;
                this.entities.forEach(entityName => {
                    this.updateEntityConfig('.jhipster/' + entityName + '.json', 'grpcService', true);
                });
            },

            registering: function () {
                if (this.abort) return;
                try {
                    this.registerModule('generator-jhipster-grpc', 'entity', 'post', 'entity', 'Adds support for gRPC and generates gRPC CRUD services');
                } catch (err) {
                    this.log(chalk.red.bold('WARN!') + ' Could not register as a jhipster entity post creation hook...\n');
                }
            },

            regenerateEntities: function () {
                if (this.abort) return;
                if (this.entities.length !== 0) {
                    this.log(chalk.green('Regenerating entities with gRPC service'));
                }
                this.entities.forEach(entity => {
                    this.composeWith('jhipster:entity', {
                        regenerate: true,
                        'skip-install': true,
                        force: this.options['force'],
                        'skip-server':true,
                        'skip-client':true,
                        arguments: [entity]
                    });
                });
            }
        };
    }

    end() {
        if (this.abort) return;
        this.log('End of grpc generator');
    }
};
<|endoftext|>


<commit_before>class ModelController {
  constructor($rootScope, $parse) {
    this.$parse = $parse;
    this.listener = $rootScope.$on('render', (event, component) => {
      this.render(event, component);
    });
    this.settings = {
      mode: 'json',
      useWrapMode : true,
      // showGutter: false,
      onLoad: this.onEditorChange.bind(this)
    }
    this.$rootScope = $rootScope;
    this.inFirst = true;
  }

  $onDestroy() {
    this.listener();
  }

  onEditorChange(editor) {
    let session = editor.getSession();
    session.on("change", (e) => {
      this.broadcastModel(session.getValue());
    });
  }

  broadcastModel(model) {
    if (this.inFirst) {
      this.inFirst = false;
      return;
    }
    try {
      let v = JSON.parse(model);
      this.$rootScope.$broadcast('model', v);
    } catch(e) {}
  }

  render(event, component) {
    this.model = JSON.stringify(component.model, null, Number(4));
  }

}

export default ModelController;
<commit_msg>Use Infinity blockScrolling for ace editor<commit_after>class ModelController {
  constructor($rootScope, $parse) {
    this.$parse = $parse;
    this.listener = $rootScope.$on('render', (event, component) => {
      this.render(event, component);
    });
    this.settings = {
      mode: 'json',
      useWrapMode : true,
      // showGutter: false,
      onLoad: this.onEditorChange.bind(this),
      $blockScrolling: Infinity
    }
    this.$rootScope = $rootScope;
    this.inFirst = true;
  }

  $onDestroy() {
    this.listener();
  }

  onEditorChange(editor) {
    let session = editor.getSession();
    session.on("change", (e) => {
      this.broadcastModel(session.getValue());
    });
  }

  broadcastModel(model) {
    if (this.inFirst) {
      this.inFirst = false;
      return;
    }
    try {
      let v = JSON.parse(model);
      this.$rootScope.$broadcast('model', v);
    } catch(e) {}
  }

  render(event, component) {
    this.model = JSON.stringify(component.model, null, Number(4));
  }

}

export default ModelController;
<|endoftext|>


<commit_before>var jf = jasmine.getFixtures();
jf.fixturesPath = '/base';
jf.load('html/index.html');

// Add ifDefined to jasmine
var oldExpect = jasmine.Spec.prototype.expect;
jasmine.Spec.prototype.expect = function (actual) {
  var expect = oldExpect.call(this, actual);
  expect.ifDefined = jQuery.extend({}, expect);

  var keys = [];
  for (var k in expect) {
    if (typeof expect[k] === 'function') {
      keys.push(k);
    }
  }

  keys.forEach(function (key) {
    expect.ifDefined[key] = function () {
      if (actual === null || typeof actual === 'undefined') {
        return expect.toBeUndefined.apply(this);
      } else {
        return expect[key].apply(this, arguments);
      }
    };
  });
  return expect;
};

var describeEach = function (thingName) {
  var DescribeEach = function () {
    this.id = function (o) { return String(o); }
  };
  DescribeEach.prototype.withIdenfier = function (fn) {
    this.id = fn;
    if (typeof fn === "string") {
      this.id = function (o) { return o[fn]; };
    }
    return this;
  };
  DescribeEach.prototype.inArray = function (array, fn) {
    var that = this;
    if (array) {
      array.forEach(function (element, i) {
        return describe(thingName + ' ' + that.id(element, i), function () {
          fn(element, i)
        });
      });
    }
    return this;
  };
  return new DescribeEach();
};

describe('the documentation', function () {
  beforeEach(function () {
    this.addMatchers({
      toBeString: function () {
        return typeof this.actual === 'string';
      },
      toBeNumber: function () {
        return typeof this.actual === 'number';
      },
      toBeArray: function () {
        return this.actual instanceof Array;
      },
      toBeObject: function () {
        return this.actual instanceof Object &&
          !(this.actual instanceof Array);
      },
      toAtMostHaveProperties: function () {
        var pass = true;
        if (typeof this.actual !== 'Object') {
          return false;
        }
        this.actual.keys().forEach(key, function (key) {
          pass = pass & arguments.indexOf(key) > -1;
        });
        return pass;
      }
    });
  });

  describe('ifDefined', function () {
    it('works', function () {
      expect(1).ifDefined.toBe(1);
      expect(1).toBe(1);
      expect("k").ifDefined.toBeString();
    })
  })

  describeEach('number').inArray([1, 2, 3], function (n) {
    it('is a number', function () {
      expect(n).toBeNumber();
    });
  })

  describe('data model:', function () {

    describe('the project', function () {

    });

    // Each file
    describeEach('file').withIdenfier('filename').inArray(data.files, function (file) {
      describe('description', function () {
        it('should be string', function () {
          expect(file.description).ifDefined.toBeString();
        });
        it('should have converted description from markdown to html', function () {
          expect(file.description).ifDefined.toContain('<p>');
        })
      });
      describe('@author', function () {
        it('should be an array', function () {
          expect(file.author).ifDefined.toBeArray();
        });
        describeEach('author').withIdenfier('name').inArray(file.author, function (author) {
          it('should be an object', function () {
            expect(author).toBeObject();
          });
          it('should have at most a name and email', function () {
            expect(author).toAtMostHaveProperties('name', 'email');
          })
          it('should have a name that is a string (if defined)', function () {
            expect(author.name).ifDefined.toBeString();
          });
          it('should have an email that is a string (if defined)', function () {
            expect(author.email).ifDefined.toBeString();
          })
        });
      });
      describe('@see', function () {
        it('should be an array', function () {
          expect(file.see).ifDefined.toBeArray();
        });
        describeEach('reference').inArray(file.see, function (reference) {
          it('should be an string', function () {
            expect(reference).toBeString();
          });
        });
      });
      describe('@since', function () {
        it('should be a string', function () {
          expect(file.since).ifDefined.toBeString();
        });
      });
      describe('@title', function () {
        it('should be a string', function () {
          expect(file.title).toBeString();
        });
      });
      describe('@version', function () {
        it('should be a string', function () {
          expect(file.version).ifDefined.toBeString();
        });
      });
    });

    describe('all classes', function () {

    });

    describe('all attributes', function () {

    });

    describe('all methods', function () {

    });
    var file = data.files[1];

    describe('the file', function () {
      describe('description', function () {
        it('should have a description', function () {
          expect(file.description).toContain('If the tests succeed');
        });
        it('should have converted description from markdown to html', function () {
          expect(file.description).toContain('<p>');
        })
      });
      describe('@author', function () {
        it('should have two authors', function () {
          expect(file.author.length).toBe(2);
        });
        it('should have two authors with names', function () {
          expect(file.author[0].name).toBeDefined()
          expect(file.author[1].name).toBeDefined()
        })
        it('should have first author with an email address', function () {
          expect(file.author[0].email).toBeDefined()
          expect(file.author[1].email).toBeUndefined()
        });
      });
      describe('@see', function () {
        it('should have two references (@sees)', function () {
          expect(file.sees.length).toBe(2);
        })
      });
      describe('@since', function () {
        it('should have a date that this has been relevant since', function () {
          expect(file.since).toBeDefined();
        });
      });
      describe('@title', function () {
        it('should have a title', function () {
          expect(file.title).toBeDefined();
        });
      });
      describe('@version', function () {
        it('should have a version', function () {
          expect(file.version).toBeDefined();
        });
      });
    });
    describe('the Farm class', function () {
      it('should have two methods', function () {

      });
      describe('the sell method', function () {

      });
      describe('the addField method', function () {

      })
    });
    describe('the Field class', function () {
      describe('the drawCropCircle method', function () {

      })
    })
  })

  describe('the documentation html', function () {
    describe('the title', function () {
      var $title = $('.mainbody > h1');
      it('should appear once', function () {
        expect($title.length).toBe(1);
      });
      it('should be Tests 0.01', function () {
        expect($title.html()).toBe('Tests 0.01');
      });
    });
  });
});<commit_msg>fixed test cases<commit_after>var jf = jasmine.getFixtures();
jf.fixturesPath = '/base';
jf.load('html/index.html');

// Add ifDefined to jasmine
var oldExpect = jasmine.Spec.prototype.expect;
jasmine.Spec.prototype.expect = function (actual) {
  var expect = oldExpect.call(this, actual);
  expect.ifDefined = jQuery.extend({}, expect);

  var keys = [];
  for (var k in expect) {
    if (typeof expect[k] === 'function') {
      keys.push(k);
    }
  }

  keys.forEach(function (key) {
    expect.ifDefined[key] = function () {
      if (actual === null || typeof actual === 'undefined') {
        return expect.toBeUndefined.apply(this);
      } else {
        return expect[key].apply(this, arguments);
      }
    };
  });
  return expect;
};

var describeEach = function (thingName) {
  var DescribeEach = function () {
    this.id = function (o) { return String(o); }
  };
  DescribeEach.prototype.withIdenfier = function (fn) {
    this.id = fn;
    if (typeof fn === "string") {
      this.id = function (o) { return o[fn]; };
    }
    return this;
  };
  DescribeEach.prototype.inArray = function (array, fn) {
    var that = this;
    if (array) {
      array.forEach(function (element, i) {
        return describe(thingName + ' ' + that.id(element, i), function () {
          fn(element, i)
        });
      });
    }
    return this;
  };
  return new DescribeEach();
};

describe('the documentation', function () {
  beforeEach(function () {
    this.addMatchers({
      toBeString: function () {
        return typeof this.actual === 'string';
      },
      toBeNumber: function () {
        return typeof this.actual === 'number';
      },
      toBeArray: function () {
        return this.actual instanceof Array;
      },
      toBeObject: function () {
        return this.actual instanceof Object &&
          !(this.actual instanceof Array);
      },
      toAtMostHaveProperties: function () {
        var pass = true,
            accepted = Array.prototype.slice.call(arguments, 0);
        if (typeof this.actual !== 'object') {
          return false;
        }
        Object.keys(this.actual).forEach(function (key) {
          pass = pass && accepted.indexOf(key) > -1;
        });
        return pass;
      }
    });
  });

  describe('ifDefined', function () {
    it('works', function () {
      expect(1).ifDefined.toBe(1);
      expect(1).toBe(1);
      expect("k").ifDefined.toBeString();
    })
  })

  describeEach('number').inArray([1, 2, 3], function (n) {
    it('is a number', function () {
      expect(n).toBeNumber();
    });
  })

  describe('data model:', function () {

    describe('the project', function () {

    });

    // Each file
    describeEach('file').withIdenfier('filename').inArray(data.files, function (file) {
      describe('description', function () {
        it('should be string', function () {
          expect(file.description).ifDefined.toBeString();
        });
        it('should have converted description from markdown to html', function () {
          expect(file.description).ifDefined.toContain('<p>');
        })
      });
      describe('@author', function () {
        it('should be an array', function () {
          expect(file.author).ifDefined.toBeArray();
        });
        describeEach('author').withIdenfier('name').inArray(file.author, function (author) {
          it('should be an object', function () {
            expect(author).toBeObject();
          });
          it('should have at most a name and email', function () {
            expect(author).toAtMostHaveProperties('name', 'email');
          })
          it('should have a name that is a string (if defined)', function () {
            expect(author.name).ifDefined.toBeString();
          });
          it('should have an email that is a string (if defined)', function () {
            expect(author.email).ifDefined.toBeString();
          })
        });
      });
      describe('@see', function () {
        it('should be an array', function () {
          expect(file.see).ifDefined.toBeArray();
        });
        describeEach('reference').inArray(file.see, function (reference) {
          it('should be an string', function () {
            expect(reference).toBeString();
          });
        });
      });
      describe('@since', function () {
        it('should be a string', function () {
          expect(file.since).ifDefined.toBeString();
        });
      });
      describe('@title', function () {
        it('should be a string', function () {
          expect(file.title).toBeString();
        });
      });
      describe('@version', function () {
        it('should be a string', function () {
          expect(file.version).ifDefined.toBeString();
        });
      });
    });

    describe('all classes', function () {

    });

    describe('all attributes', function () {

    });

    describe('all methods', function () {

    });
    var file = data.files[1];

    describe('the file', function () {
      describe('description', function () {
        it('should have a description', function () {
          expect(file.description).toContain('If the tests succeed');
        });
        it('should have converted description from markdown to html', function () {
          expect(file.description).toContain('<p>');
        })
      });
      describe('@author', function () {
        it('should have two authors', function () {
          expect(file.author.length).toBe(2);
        });
        it('should have two authors with names', function () {
          expect(file.author[0].name).toBeDefined()
          expect(file.author[1].name).toBeDefined()
        })
        it('should have first author with an email address', function () {
          expect(file.author[0].email).toBeDefined()
          expect(file.author[1].email).toBeUndefined()
        });
      });
      describe('@see', function () {
        it('should have two references (@see)', function () {
          expect(file.see.length).toBe(2);
        })
      });
      describe('@since', function () {
        it('should have a date that this has been relevant since', function () {
          expect(file.since).toBeDefined();
        });
      });
      describe('@title', function () {
        it('should have a title', function () {
          expect(file.title).toBeDefined();
        });
      });
      describe('@version', function () {
        it('should have a version', function () {
          expect(file.version).toBeDefined();
        });
      });
    });
    describe('the Farm class', function () {
      it('should have two methods', function () {

      });
      describe('the sell method', function () {

      });
      describe('the addField method', function () {

      })
    });
    describe('the Field class', function () {
      describe('the drawCropCircle method', function () {

      })
    })
  })

  describe('the documentation html', function () {
    describe('the title', function () {
      var $title = $('.mainbody > h1');
      it('should appear once', function () {
        expect($title.length).toBe(1);
      });
      it('should be Tests 0.01', function () {
        expect($title.html()).toBe('Tests 0.01');
      });
    });
  });
});<|endoftext|>


<commit_before>/**
 * Requires the first alphabetical character of a comment to be uppercase, unless it is part of a multi-line textblock.
 *
 * This rule automatically ignores jscs, jshint, eslint and istanbul specific comments.
 *
 * Types: `Boolean` or `Object`
 *
 * Values:
 *  - `true`
 *  - `Object`:
 *     - `allExcept`: array of quoted exceptions
 *     - `inlined`: Ignore comments in the middle of the code line
 *
 * #### Example
 *
 * ```js
 * "requireCapitalizedComments": true
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * // Valid
 * //Valid
 *
 * /*
 *   Valid
 *  *\/
 *
 * /**
 *  * Valid
 *  *\/
 *
 * // A textblock is a set of lines
 * // that starts with a capitalized letter
 * // and has one or more non-capitalized lines
 * // afterwards
 *
 * // A textblock may also have multiple lines.
 * // Those lines can be uppercase as well to support
 * // sentence breaks in textblocks
 *
 * // 123 or any non-alphabetical starting character
 * // @are also valid anywhere
 *
 * // jscs: enable
 * ```
 *
 * ##### Invalid:
 *
 * ```js
 * // invalid
 * //invalid
 * /** invalid *\/
 * /**
 *  * invalid
 *  *\/
 * ```
 *
 * ```js
 * "requireCapitalizedComments": { "allExcept": ["pragma"] }
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * function sayHello() {
 *     /* pragma something *\/
 *
 *     // I can now say hello in lots of statements, if I like.
 *     return "Hello";
 * }
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * function sayHello() {
 *     /* istanbul ignore next *\/
 *
 *     // I'd like to ignore this statement in coverage reports.
 *     return "Hello";
 * }
 * ```
 *
 * ##### Invalid:
 *
 * ```js
 * function sayHello() {
 *     /* otherPragma something *\/
 *
 *     // i can now say hello in lots of statements, if I like.
 *     return "Hello";
 * }
 * ```
 *
 * ```js
 * "requireCapitalizedComments": { "inlined": true }
 * ```
 * ##### Valid:
 *
 * * ```js
 * function sayHello( world /*internal*\/ ) {
 * }
 * ```
 */

var assert = require('assert');

var isPragma = require('../utils').isPragma;
var letterPattern = require('../../patterns/L');
var upperCasePattern = require('../../patterns/Lu');

module.exports = function() {};

module.exports.prototype = {
    configure: function(options) {
        var exceptions;

        this.inlined = false;
        this._isPragma = null;

        var optionName = this.getOptionName();

        var isObject = typeof options === 'object';
        var error = optionName + ' option requires a true value ' +
            'or an object with String[] `allExcept` property or true with `inlined`';

        assert(
            options === true ||
            isObject,
            error
        );

        if (isObject && options.allExcept) {
            exceptions = options.allExcept;

            // verify items in `allExcept` property in object are string values
            assert(
                Array.isArray(exceptions) &&
                exceptions.every(function(el) { return typeof el === 'string'; }),
                'Property `allExcept` in ' + optionName + ' should be an array of strings'
            );

            this._isPragma = isPragma(exceptions);
        }

        if (!this._isPragma) {
            this._isPragma = isPragma();
        }

        if (isObject && options.inlined) {
            this.inlined = true;
        }

        if (isObject && !options.allExcept && !options.inlined) {
            assert(false, error);
        }
    },

    getOptionName: function() {
        return 'requireCapitalizedComments';
    },

    _isUrl: function(comment) {
        var protocolParts = comment.value.split('://');

        if (protocolParts.length === 1) {
            return false;
        }

        return comment.value.indexOf(protocolParts[0]) === 0;
    },

    _isException: function(comment) {
        return this._isPragma(comment.value);
    },

    _isValid: function(comment) {
        var first = this._getFirstChar(comment);

        return first && upperCasePattern.test(first);
    },

    _isLetter: function(comment) {
        var first = this._getFirstChar(comment);

        return first && letterPattern.test(first);
    },

    _getFirstChar: function(comment) {
        return comment.value.replace(/[\n\s\*]/g, '')[0];
    },

    _isTextBlock: function(comment, file) {
        var prevComment = file.getPrevToken(comment, {includeComments: true});

        if (prevComment) {
            return prevComment.type === 'Line' &&
                prevComment.loc.start.line + 1 === comment.loc.start.line &&
                prevComment.value.trim().length > 0;
        }

        return false;
    },

    _shouldIgnoreIfInTheMiddle: function(file, comment) {
        if (!this.inlined) {
            return false;
        }

        var firstToken = file.getFirstNodeToken(comment);
        var otherToken = file.getPrevToken(firstToken, { includeComments: true });

        return otherToken ? otherToken.loc.start.line === firstToken.loc.start.line : false;
    },

    check: function(file, errors) {
        var _this = this;

        function add(comment) {
            errors.cast({
                message: 'Comments must start with an uppercase letter, unless it is part of a textblock',
                line: comment.loc.start.line,
                column: comment.loc.start.column,
                additional: comment
            });
        }

        file.iterateTokensByType('Line', function(comment) {
            if (_this._isException(comment)) {
                return;
            }

            if (_this._isUrl(comment)) {
                return;
            }

            if (!_this._isLetter(comment)) {
                return;
            }

            if (_this._isTextBlock(comment, file)) {
                return;
            }

            if (_this._isValid(comment)) {
                return;
            }

            add(comment);
        });

        file.iterateTokensByType('Block', function(comment) {
            if (_this._isException(comment)) {
                return;
            }

            if (_this._isUrl(comment)) {
                return;
            }

            if (!_this._isLetter(comment)) {
                return;
            }

            if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
                return;
            }

            if (_this._isValid(comment)) {
                return;
            }

            add(comment);
        });
    },

    _fix: function(file, error) {
        var comment = error.additional;
        var first = this._getFirstChar(comment);

        comment.value = comment.value.replace(first, first.toUpperCase());
    }
};
<commit_msg>`requireCapitalizedComments`: fixed formatting in docs<commit_after>/**
 * Requires the first alphabetical character of a comment to be uppercase, unless it is part of a multi-line textblock.
 *
 * This rule automatically ignores jscs, jshint, eslint and istanbul specific comments.
 *
 * Types: `Boolean` or `Object`
 *
 * Values:
 *  - `true`
 *  - `Object`:
 *     - `allExcept`: array of quoted exceptions
 *     - `inlined`: Ignore comments in the middle of the code line
 *
 * #### Example
 *
 * ```js
 * "requireCapitalizedComments": true
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * // Valid
 * //Valid
 *
 * /*
 *   Valid
 *  *\/
 *
 * /**
 *  * Valid
 *  *\/
 *
 * // A textblock is a set of lines
 * // that starts with a capitalized letter
 * // and has one or more non-capitalized lines
 * // afterwards
 *
 * // A textblock may also have multiple lines.
 * // Those lines can be uppercase as well to support
 * // sentence breaks in textblocks
 *
 * // 123 or any non-alphabetical starting character
 * // @are also valid anywhere
 *
 * // jscs: enable
 * ```
 *
 * ##### Invalid:
 *
 * ```js
 * // invalid
 * //invalid
 * /** invalid *\/
 * /**
 *  * invalid
 *  *\/
 * ```
 *
 * ```js
 * "requireCapitalizedComments": { "allExcept": ["pragma"] }
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * function sayHello() {
 *     /* pragma something *\/
 *
 *     // I can now say hello in lots of statements, if I like.
 *     return "Hello";
 * }
 * ```
 *
 * ##### Valid:
 *
 * ```js
 * function sayHello() {
 *     /* istanbul ignore next *\/
 *
 *     // I'd like to ignore this statement in coverage reports.
 *     return "Hello";
 * }
 * ```
 *
 * ##### Invalid:
 *
 * ```js
 * function sayHello() {
 *     /* otherPragma something *\/
 *
 *     // i can now say hello in lots of statements, if I like.
 *     return "Hello";
 * }
 * ```
 *
 * ```js
 * "requireCapitalizedComments": { "inlined": true }
 * ```
 * ##### Valid:
 *
 * ```js
 * function sayHello( world /*internal*\/ ) {
 * }
 * ```
 */

var assert = require('assert');

var isPragma = require('../utils').isPragma;
var letterPattern = require('../../patterns/L');
var upperCasePattern = require('../../patterns/Lu');

module.exports = function() {};

module.exports.prototype = {
    configure: function(options) {
        var exceptions;

        this.inlined = false;
        this._isPragma = null;

        var optionName = this.getOptionName();

        var isObject = typeof options === 'object';
        var error = optionName + ' option requires a true value ' +
            'or an object with String[] `allExcept` property or true with `inlined`';

        assert(
            options === true ||
            isObject,
            error
        );

        if (isObject && options.allExcept) {
            exceptions = options.allExcept;

            // verify items in `allExcept` property in object are string values
            assert(
                Array.isArray(exceptions) &&
                exceptions.every(function(el) { return typeof el === 'string'; }),
                'Property `allExcept` in ' + optionName + ' should be an array of strings'
            );

            this._isPragma = isPragma(exceptions);
        }

        if (!this._isPragma) {
            this._isPragma = isPragma();
        }

        if (isObject && options.inlined) {
            this.inlined = true;
        }

        if (isObject && !options.allExcept && !options.inlined) {
            assert(false, error);
        }
    },

    getOptionName: function() {
        return 'requireCapitalizedComments';
    },

    _isUrl: function(comment) {
        var protocolParts = comment.value.split('://');

        if (protocolParts.length === 1) {
            return false;
        }

        return comment.value.indexOf(protocolParts[0]) === 0;
    },

    _isException: function(comment) {
        return this._isPragma(comment.value);
    },

    _isValid: function(comment) {
        var first = this._getFirstChar(comment);

        return first && upperCasePattern.test(first);
    },

    _isLetter: function(comment) {
        var first = this._getFirstChar(comment);

        return first && letterPattern.test(first);
    },

    _getFirstChar: function(comment) {
        return comment.value.replace(/[\n\s\*]/g, '')[0];
    },

    _isTextBlock: function(comment, file) {
        var prevComment = file.getPrevToken(comment, {includeComments: true});

        if (prevComment) {
            return prevComment.type === 'Line' &&
                prevComment.loc.start.line + 1 === comment.loc.start.line &&
                prevComment.value.trim().length > 0;
        }

        return false;
    },

    _shouldIgnoreIfInTheMiddle: function(file, comment) {
        if (!this.inlined) {
            return false;
        }

        var firstToken = file.getFirstNodeToken(comment);
        var otherToken = file.getPrevToken(firstToken, { includeComments: true });

        return otherToken ? otherToken.loc.start.line === firstToken.loc.start.line : false;
    },

    check: function(file, errors) {
        var _this = this;

        function add(comment) {
            errors.cast({
                message: 'Comments must start with an uppercase letter, unless it is part of a textblock',
                line: comment.loc.start.line,
                column: comment.loc.start.column,
                additional: comment
            });
        }

        file.iterateTokensByType('Line', function(comment) {
            if (_this._isException(comment)) {
                return;
            }

            if (_this._isUrl(comment)) {
                return;
            }

            if (!_this._isLetter(comment)) {
                return;
            }

            if (_this._isTextBlock(comment, file)) {
                return;
            }

            if (_this._isValid(comment)) {
                return;
            }

            add(comment);
        });

        file.iterateTokensByType('Block', function(comment) {
            if (_this._isException(comment)) {
                return;
            }

            if (_this._isUrl(comment)) {
                return;
            }

            if (!_this._isLetter(comment)) {
                return;
            }

            if (_this._shouldIgnoreIfInTheMiddle(file, comment)) {
                return;
            }

            if (_this._isValid(comment)) {
                return;
            }

            add(comment);
        });
    },

    _fix: function(file, error) {
        var comment = error.additional;
        var first = this._getFirstChar(comment);

        comment.value = comment.value.replace(first, first.toUpperCase());
    }
};
<|endoftext|>


<commit_before>window.onload = function() {
	var stage = new createjs.Stage("playground");

	var keyStates = {
		UP: false,
		DOWN: false,
		LEFT: false,
		RIGHT: false
	};
	var INV_PI_180 = 180.0/Math.PI;

	var player = { shape: null, vel: {x: 0, y: 0}, acc: {x: 0, y: 0}, maxspeed: 200 };
	var enemies;
	var bullets;
	var background;

	function init() {
		var i;
		var divisions = 16;

		background = new createjs.Shape();
		var bgGfx = background.graphics;
		bgGfx.setStrokeStyle(1).beginStroke("#505050");
		var dx = stage.canvas.width / divisions;
		for (i=0; i<=divisions; ++i) {
			var div = i*dx;
			bgGfx.moveTo(div, 0).lineTo(div, stage.canvas.height);
			bgGfx.moveTo(0, div).lineTo(stage.canvas.width, div);
		}
		stage.addChild(background);

		player.shape = new createjs.Shape();
		player.shape.graphics.setStrokeStyle(1, "round")
			.beginStroke("#ffffff")
			.moveTo(-8, -10)
			.lineTo(0, 12)
			.lineTo(8, -10)
			.lineTo(-8, -10);
		player.shape.x = player.shape.y = 100;
		stage.addChild(player.shape);

		createjs.Ticker.setFPS(60);
		createjs.Ticker.addEventListener("tick", handleTick);
		window.onkeydown = keyEvent(true);
		window.onkeyup = keyEvent(false);
	}

	function handleTick() {
		// Input handling
		var acc = 200;
		player.acc.y = 0;
		if (keyStates["UP"]) player.acc.y += -acc;
		if (keyStates["DOWN"]) player.acc.y += acc;

		player.acc.x = 0;
		if (keyStates["LEFT"]) player.acc.x += -acc;
		if (keyStates["RIGHT"]) player.acc.x += acc;

		// Game updates
		var elapsed = createjs.Ticker.getInterval() * 0.001;

		updateMotion(player, elapsed);
		if (player.acc.y != 0 || player.acc.x != 0)
			player.shape.rotation = Math.atan2(player.acc.y, player.acc.x) * INV_PI_180 - 90;
		stage.update();
	}

	function updateMotion(obj, elapsed) {
		if (obj.acc.x == 0)
			obj.vel.x *= 0.8;
		else
			obj.vel.x += obj.acc.x * elapsed;
		if (Math.abs(obj.vel.x) <= 0.0001)
			obj.vel.x = 0;

		if (obj.acc.y == 0)
			obj.vel.y *= 0.8;
		else
			obj.vel.y += obj.acc.y * elapsed;
		if (Math.abs(obj.vel.y) <= 0.0001)
			obj.vel.y = 0;

		clampMag(obj.vel, obj.maxspeed);

		obj.shape.x += obj.vel.x * elapsed;
		obj.shape.y += obj.vel.y * elapsed;
	}

	// Helper functions
	// Returns a keyUp/keyDown callback
	function keyEvent(isKeyDown) {
		var state = isKeyDown;

		var KEYCODE_UP = 38;
		var KEYCODE_DOWN = 40;
		var KEYCODE_LEFT = 37;
		var KEYCODE_RIGHT = 39;
		var KEYCODE_W = 87;
		var KEYCODE_S = 83;
		var KEYCODE_A = 65;
		var KEYCODE_D = 68;

		return function(evt) {
			switch (evt.keyCode) {
				case KEYCODE_UP:
				case KEYCODE_W:
					keyStates["UP"] = state;
					break;
				case KEYCODE_DOWN:
				case KEYCODE_S:
					keyStates["DOWN"] = state;
					break;
				case KEYCODE_LEFT:
				case KEYCODE_A:
					keyStates["LEFT"] = state;
					break;
				case KEYCODE_RIGHT:
				case KEYCODE_D:
					keyStates["RIGHT"] = state;
					break;
			}
		};
	}

	// Clamps the magnitude of a vector to a given maximum
	function clampMag(vec, maxmag) {
		var mag_sq = vec.x*vec.x + vec.y*vec.y;
		if (mag_sq > maxmag*maxmag) {
			var factor = maxmag / Math.sqrt(mag_sq);
			vec.x *= factor;
			vec.y *= factor;
		}
	}

	// Finally, start it all
	init();
};
<commit_msg>Added dynamic resizing to the stage.<commit_after>window.onload = function() {
	var stage = new createjs.Stage("playground");
	var gameWidth = 400;
	var gameHeight = 400;

	var keyStates = {
		UP: false,
		DOWN: false,
		LEFT: false,
		RIGHT: false
	};
	var INV_PI_180 = 180.0/Math.PI;

	var player = { shape: null, vel: {x: 0, y: 0}, acc: {x: 0, y: 0}, maxspeed: 200 };
	var enemies;
	var bullets;
	var background;

	function init() {
		var i;
		var divisions = 16;

		background = new createjs.Shape();
		var bgGfx = background.graphics;
		bgGfx.setStrokeStyle(1).beginStroke("#505050");
		var dx = gameWidth / divisions;
		for (i=0; i<=divisions; ++i) {
			var div = i*dx;
			bgGfx.moveTo(div, 0).lineTo(div, gameHeight);
			bgGfx.moveTo(0, div).lineTo(gameWidth, div);
		}
		stage.addChild(background);

		player.shape = new createjs.Shape();
		player.shape.graphics.setStrokeStyle(1, "round")
			.beginStroke("#ffffff")
			.moveTo(-8, -10)
			.lineTo(0, 12)
			.lineTo(8, -10)
			.lineTo(-8, -10);
		player.shape.x = player.shape.y = 100;
		stage.addChild(player.shape);

		createjs.Ticker.setFPS(60);
		createjs.Ticker.addEventListener("tick", handleTick);
		window.onkeydown = keyEvent(true);
		window.onkeyup = keyEvent(false);
		window.onresize = resize;

		resize();
	}

	function handleTick() {
		// Input handling
		var acc = 200;
		player.acc.y = 0;
		if (keyStates["UP"]) player.acc.y += -acc;
		if (keyStates["DOWN"]) player.acc.y += acc;

		player.acc.x = 0;
		if (keyStates["LEFT"]) player.acc.x += -acc;
		if (keyStates["RIGHT"]) player.acc.x += acc;

		// Game updates
		var elapsed = createjs.Ticker.getInterval() * 0.001;

		updateMotion(player, elapsed);
		if (player.acc.y != 0 || player.acc.x != 0)
			player.shape.rotation = Math.atan2(player.acc.y, player.acc.x) * INV_PI_180 - 90;
		stage.update();
	}

	function updateMotion(obj, elapsed) {
		if (obj.acc.x == 0)
			obj.vel.x *= 0.8;
		else
			obj.vel.x += obj.acc.x * elapsed;
		if (Math.abs(obj.vel.x) <= 0.0001)
			obj.vel.x = 0;

		if (obj.acc.y == 0)
			obj.vel.y *= 0.8;
		else
			obj.vel.y += obj.acc.y * elapsed;
		if (Math.abs(obj.vel.y) <= 0.0001)
			obj.vel.y = 0;

		clampMag(obj.vel, obj.maxspeed);

		obj.shape.x += obj.vel.x * elapsed;
		obj.shape.y += obj.vel.y * elapsed;
	}

	// Helper functions
	// Returns a keyUp/keyDown callback
	function keyEvent(isKeyDown) {
		var state = isKeyDown;

		var KEYCODE_UP = 38;
		var KEYCODE_DOWN = 40;
		var KEYCODE_LEFT = 37;
		var KEYCODE_RIGHT = 39;
		var KEYCODE_W = 87;
		var KEYCODE_S = 83;
		var KEYCODE_A = 65;
		var KEYCODE_D = 68;

		return function(evt) {
			switch (evt.keyCode) {
				case KEYCODE_UP:
				case KEYCODE_W:
					keyStates["UP"] = state;
					break;
				case KEYCODE_DOWN:
				case KEYCODE_S:
					keyStates["DOWN"] = state;
					break;
				case KEYCODE_LEFT:
				case KEYCODE_A:
					keyStates["LEFT"] = state;
					break;
				case KEYCODE_RIGHT:
				case KEYCODE_D:
					keyStates["RIGHT"] = state;
					break;
			}
		};
	}

	// Clamps the magnitude of a vector to a given maximum
	function clampMag(vec, maxmag) {
		var mag_sq = vec.x*vec.x + vec.y*vec.y;
		if (mag_sq > maxmag*maxmag) {
			var factor = maxmag / Math.sqrt(mag_sq);
			vec.x *= factor;
			vec.y *= factor;
		}
	}

	// Handles resizing of stage
	function resize() {
		var winWidth = window.innerWidth * 0.9;
		var winHeight = window.innerHeight * 0.9;

		var scale = Math.min(winWidth/gameWidth, winHeight/gameHeight);
		stage.scaleX = stage.scaleY = scale;

		stage.canvas.width = gameWidth * scale;
		stage.canvas.height = gameHeight * scale;
		console.log(stage.canvas.width, stage.canvas.height);
	}

	// Finally, start it all
	init();
};
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.requireStylesheet('cc.raster_task_slice_view');
tvcm.require('cc.tile');
tvcm.require('cc.tile_view');
tvcm.require('cc.layer_tree_host_impl_view');
tvcm.require('tracing.analysis.slice_view');
tvcm.require('tvcm.ui.info_bar');

tvcm.exportTo('cc', function() {

  /**
   * @constructor
   */
  var RasterTaskSliceView = tvcm.ui.define(
      'raster-task-slice-view', tracing.analysis.SliceView);

  RasterTaskSliceView.prototype = {
    __proto__: tracing.analysis.SliceView.prototype,

    decorate: function() {
      this.classList.add('raster-task-slice-view');
      this.layerTreeView_ = new cc.LayerTreeHostImplSnapshotView();
      this.infoBar_ = new tvcm.ui.InfoBar();
      this.appendChild(this.infoBar_);
      this.appendChild(this.layerTreeView_);
    },

    updateContents: function() {
      this.infoBar_.visible = false;

      if (!this.slice.args.data) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'No data on this raster task.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      var tile = this.slice.args.data.tile_id;
      if (!tile) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'No tile on this raster task.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      if (!(tile instanceof cc.TileSnapshot)) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'This raster task didn\'t get fully traced.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      this.layerTreeView_.style.display = '';

      var containingSnapshot = tile.containingSnapshot;
      this.layerTreeView_.objectSnapshot = containingSnapshot;
      this.layerTreeView_.selection = new cc.RasterTaskSelection(this.slice);
    }
  };

  tracing.analysis.SliceView.register(
      'TileManager::RunRasterTask', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::RunRasterOnThread', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::Raster', RasterTaskSliceView);

  tracing.analysis.SliceView.register(
      'TileManager::RunAnalyzeTask', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::RunAnalysisOnThread', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::Analyze', RasterTaskSliceView);

  return {
    RasterTaskSliceView: RasterTaskSliceView
  };

});
<commit_msg>Recognize the latest RasterTaskImpl names<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.requireStylesheet('cc.raster_task_slice_view');
tvcm.require('cc.tile');
tvcm.require('cc.tile_view');
tvcm.require('cc.layer_tree_host_impl_view');
tvcm.require('tracing.analysis.slice_view');
tvcm.require('tvcm.ui.info_bar');

tvcm.exportTo('cc', function() {

  /**
   * @constructor
   */
  var RasterTaskSliceView = tvcm.ui.define(
      'raster-task-slice-view', tracing.analysis.SliceView);

  RasterTaskSliceView.prototype = {
    __proto__: tracing.analysis.SliceView.prototype,

    decorate: function() {
      this.classList.add('raster-task-slice-view');
      this.layerTreeView_ = new cc.LayerTreeHostImplSnapshotView();
      this.infoBar_ = new tvcm.ui.InfoBar();
      this.appendChild(this.infoBar_);
      this.appendChild(this.layerTreeView_);
    },

    updateContents: function() {
      this.infoBar_.visible = false;

      if (!this.slice.args.data) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'No data on this raster task.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      var tile = this.slice.args.data.tile_id;
      if (!tile) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'No tile on this raster task.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      if (!(tile instanceof cc.TileSnapshot)) {
        this.infoBar_.visible = true;
        this.infoBar_.message = 'This raster task didn\'t get fully traced.';
        this.layerTreeView_.style.display = 'none';
        return;
      }
      this.layerTreeView_.style.display = '';

      var containingSnapshot = tile.containingSnapshot;
      this.layerTreeView_.objectSnapshot = containingSnapshot;
      this.layerTreeView_.selection = new cc.RasterTaskSelection(this.slice);
    }
  };

  tracing.analysis.SliceView.register(
      'TileManager::RunRasterTask', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::RunRasterOnThread', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::Raster', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterTaskImpl::Raster', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterTaskImpl::Analyze', RasterTaskSliceView);

  tracing.analysis.SliceView.register(
      'TileManager::RunAnalyzeTask', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::RunAnalysisOnThread', RasterTaskSliceView);
  tracing.analysis.SliceView.register(
      'RasterWorkerPoolTaskImpl::Analyze', RasterTaskSliceView);

  return {
    RasterTaskSliceView: RasterTaskSliceView
  };

});
<|endoftext|>


<commit_before>import React from 'react'
import RootSiblings from 'react-native-root-siblings'

import type { SnackItemType } from './type'
import SnackBar from './SnackBar'

export default class SnackBarManager {
  current: SnackItemType
  queue: Array<SnackItemType>

  constructor () {
    this.current = null
    this.queue = []
  }

  _setCurrent = (props: SnackItemType, callback?: Function = () => {}): void => {
    if (!('onAutoDismiss' in props)) {
      props.onAutoDismiss = this.dismiss
    }

    const current = new RootSiblings(<SnackBar {...props} />)
    this.current = current
    callback()
  }

  _removeCurrent = (callback?: Function = () => {}): void => {
    if (!this.current) {
      callback()
      return
    }

    this.current.destroy(() => {
      this.current = null
      callback()
    })
  }

  get = () => {
    return {
      current: this.current,
      queue: this.queue
    }
  }

  add = (
    title: string,
    options?: SnackItemType,
    callback?: Function = () => {}
  ): void => {
    const props = { title, ...options }

    if (this.current) {
      this.queue.push(props)
      callback()
      return
    }

    this._setCurrent(props, callback)
  }

  show = (
    title: string,
    options?: SnackItemType,
    callback?: Function = () => {}
  ): void => {
    const props = { title, ...options }

    if (this.current) {
      if (this._isItemAlreadyExistById(props)) {
        return
      }
      this.queue.unshift(props)
      callback()
      return
    }

    this._setCurrent(props, callback)
  }

  dismiss = (callback?: Function = () => {}): void => {
    this._removeCurrent(() => {
      if (!this.queue.length) {
        callback()
        return
      }

      const current = this.queue.shift()
      this._setCurrent(current, callback)
    })
  }

  _isItemAlreadyExistById = (
    props
  ): void => {
    if (props.id && this.queue.length > 0) {
      for (let i = 0; i < this.queue.length; i++) {
        if (this.queue[i].id === props.id) {
          console.debug('SnackBarManager', 'Item ID already exists, skip adding!')
          return true
        }
      }
    }
    return false
  }
}
<commit_msg>#9 - Refactored a bit<commit_after>import React from 'react'
import RootSiblings from 'react-native-root-siblings'

import type { SnackItemType } from './type'
import SnackBar from './SnackBar'

export default class SnackBarManager {
  current: SnackItemType
  queue: Array<SnackItemType>

  constructor () {
    this.current = null
    this.queue = []
  }

  _setCurrent = (props: SnackItemType, callback?: Function = () => {}): void => {
    if (!('onAutoDismiss' in props)) {
      props.onAutoDismiss = this.dismiss
    }

    const current = new RootSiblings(<SnackBar {...props} />, () => {
      this.current = current
      callback()
    })
  }

  _removeCurrent = (callback?: Function = () => {}): void => {
    if (!this.current) {
      callback()
      return
    }

    this.current.destroy(() => {
      this.current = null
      callback()
    })
  }

  get = () => {
    return {
      current: this.current,
      queue: this.queue
    }
  }

  add = (
    title: string,
    options?: SnackItemType,
    callback?: Function = () => {}
  ): void => {
    const props = { title, ...options }

    if (this.current) {
      this.queue.push(props)
      callback()
      return
    }

    this._setCurrent(props, callback)
  }

  show = (
    title: string,
    options?: SnackItemType,
    callback?: Function = () => {}
  ): void => {
    const props = { title, ...options }

    if (this.current) {
      if (this._isItemAlreadyExistById(props)) {
        return
      }
      this.queue.unshift(props)
      callback()
      return
    }

    this._setCurrent(props, callback)
  }

  dismiss = (callback?: Function = () => {}): void => {
    this._removeCurrent(() => {
      if (!this.queue.length) {
        callback()
        return
      }

      const current = this.queue.shift()
      this._setCurrent(current, callback)
    })
  }

  _isItemAlreadyExistById = (
    props
  ): boolean => {
    return props.id && this.queue.find(item => item.id === props.id)
  }
}
<|endoftext|>


<commit_before>import access from './annotations/access';
import alias from './annotations/alias';
import author from './annotations/author';
import content from './annotations/content';
import deprecated from './annotations/deprecated';
import example from './annotations/example';
import group from './annotations/group';
import ignore from './annotations/ignore';
import link from './annotations/link';
import output from './annotations/output';
import parameter from './annotations/parameter';
import property from './annotations/property';
import require_ from './annotations/require';
import return_ from './annotations/return';
import see from './annotations/see';
import since from './annotations/since';
import throw_ from './annotations/throw';
import todo from './annotations/todo';
import type from './annotations/type';

export default class AnnotationsApi {
  constructor(config) {
    this.config = config;
    this.list = {
      _: { alias: {} }
    };

    this.addAnnotation('access', access);
    this.addAnnotation('alias', alias);
    this.addAnnotation('author', author);
    this.addAnnotation('content', content);
    this.addAnnotation('deprecated', deprecated);
    this.addAnnotation('example', example);
    this.addAnnotation('group', group);
    this.addAnnotation('ignore', ignore);
    this.addAnnotation('link', link);
    this.addAnnotation('output', output);
    this.addAnnotation('parameter', parameter);
    this.addAnnotation('property', property);
    this.addAnnotation('require', require_);
    this.addAnnotation('return', return_);
    this.addAnnotation('see', see);
    this.addAnnotation('since', since);
    this.addAnnotation('throw', throw_);
    this.addAnnotation('todo', todo);
    this.addAnnotation('type', type);
  }

  /**
   * Add a single annotation by name
   * @param {String} name - Name of the annotation
   * @param {Object} annotation - Annotation object
   */
  addAnnotation(name, annotation) {
    annotation = annotation(this.config);

    this.list._.alias[name] = name;

    if (Array.isArray(annotation.alias)) {
      annotation.alias.forEach(aliasName => {
        this.list._.alias[aliasName] = name;
      });
    }

    this.list[name] = annotation;
  }

  /**
   * Add an array of annotations. The name of the annotations must be
   * in the `name` key of the annotation.
   * @param {Array} annotations - Annotation objects
   */
  addAnnotations(annotations) {
    if (annotations !== undefined) {
      annotations.forEach(annotation => {
        this.addAnnotation(annotation.name, annotation);
      });
    }
  }
}
<commit_msg>Revert "Statically import annotations, ES6 style"<commit_after>let fs = require('fs');
let path = require('path');

export default class AnnotationsApi {
  constructor(config) {
    this.config = config;
    this.list = {
      _: { alias: {} }
    };

    // Read all files from the annoation folder and add it to the annotations map.
    fs.readdirSync(path.resolve(__dirname, './annotations')).forEach(file => {
      if (!endsWith(file, '.js')) {
        return;
      }

      var annotation = require(path.resolve(__dirname, 'annotations', file));
      var name = path.basename(file, '.js');

      this.addAnnotation(name, annotation);
    });
  }

  /**
   * Add a single annotation by name
   * @param {String} name - Name of the annotation
   * @param {Object} annotation - Annotation object
   */
  addAnnotation(name, annotation) {
    annotation = annotation(this.config);

    this.list._.alias[name] = name;

    if (Array.isArray(annotation.alias)) {
      annotation.alias.forEach(aliasName => {
        this.list._.alias[aliasName] = name;
      });
    }

    this.list[name] = annotation;
  }

  /**
   * Add an array of annotations. The name of the annotations must be
   * in the `name` key of the annotation.
   * @param {Array} annotations - Annotation objects
   */
  addAnnotations(annotations) {
    if (annotations !== undefined) {
      annotations.forEach(annotation => {
        this.addAnnotation(annotation.name, annotation);
      });
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';

class SpinningCraneKick extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };
  badCasts = 0;
  markoftheCraneTargets = [];
  lastSpinningCraneKickTick = 0;
  spinningCraneKickHits = 0;
  totalMarksDuringHits = 0;
  markoftheCraneStacks = 0;

  on_byPlayer_applydebuff(event) {
    const spellId = event.ability.guid;
    let targetInstance = event.targetInstance;
    if (spellId !== SPELLS.MARK_OF_THE_CRANE.id) {
      return;
    }
    // The event doesn't specify instance on the first target of that type
    if (targetInstance === undefined) {
      targetInstance = 1;
    }
    //console.log(event.targetID, targetInstance, event.timestamp);
    const markoftheCraneTarget = {targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp };
    this.markoftheCraneTargets.push(markoftheCraneTarget);
    //console.log(markoftheCraneTarget, "added");
  }

  on_byPlayer_refreshdebuff(event) {
    const spellId = event.ability.guid;
    let targetInstance = event.targetInstance;
    if (spellId !== SPELLS.MARK_OF_THE_CRANE.id) {
      return;
    }
    if (targetInstance === undefined) {
      targetInstance = 1;
    }
    const markoftheCraneTarget = {targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp };
    let i = 0;
    while (i <= this.markoftheCraneTargets.length - 1) {
      if (this.markoftheCraneTargets[i].targetID === markoftheCraneTarget.targetID && this.markoftheCraneTargets[i].targetInstance === markoftheCraneTarget.targetInstance) {
        this.markoftheCraneTargets[i].timestamp = markoftheCraneTarget.timestamp;
      }
      i++;
    }
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.SPINNING_CRANE_KICK.id) {
      return;
    }
    this.markoftheCraneStacks = 0;
    let i = 0;
    while (i < this.markoftheCraneTargets.length) {
      // removing expired targets to avoid looking through huge arrays in logs with a lot of targets
      if (event.timestamp - this.markoftheCraneTargets[i].timestamp > 15000) {
        console.log(this.markoftheCraneTargets[i], "Mark of the Crane expired and to be removed");
        console.log(this.markoftheCraneTargets.splice(i, 1), "Mark Removed");
      }
      else {
        this.markoftheCraneStacks++;
        //console.log(this.markoftheCraneTargets[i], "Mark of the Crane found and counted");
      }
      i++;
    }
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.SPINNING_CRANE_KICK_DAMAGE.id) {
      return;
    }
    this.spinningCraneKickHits++;
    console.log("mark of the crane stacks", this.markoftheCraneStacks, event.timestamp);
    if (event.timestamp - this.lastSpinningCraneKickTick > 100) {
      this.totalMarksDuringHits += this.markoftheCraneStacks;
      this.lastSpinningCraneKickTick = event.timestamp;
    }
    //console.log("Total marks during hits", this.totalMarksDuringHits, "Total hits", this.spinningCraneKickHits, event.timestamp);
  }

  statistic() {
    const averageRatio = this.totalMarksDuringHits / this.spinningCraneKickHits;
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.SPINNING_CRANE_KICK_DAMAGE.id} />}
        value={averageRatio.toFixed(2)}
        label={(
           Ratio between <SpellLink id={SPELLS.MARK_OF_THE_CRANE.id} /> stacks and targets hit by <SpellLink id={SPELLS.SPINNING_CRANE_KICK.id} />
        )}
        tooltip={`If your ratio is less than 1, you're using Spinning Crane Kick before having Mark of the Crane on all targets.`}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.OPTIONAL(4);
}

export default SpinningCraneKick;
<commit_msg>[Windwalker] Updated Spinning Crane Kick module<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import StatisticsListBox, { STATISTIC_ORDER } from 'Main/StatisticsListBox';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';
import StatTracker from 'Parser/Core/Modules/StatTracker';

class SpinningCraneKick extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    abilityTracker: AbilityTracker,
    statTracker: StatTracker,
  };
  badCasts = 0;
  markoftheCraneTargets = [];
  lastSpinningCraneKickTick = 0;
  spinningCraneKickHits = 0;
  totalMarksDuringHits = 0;
  markoftheCraneStacks = 0;
  spinningCraneKickDuration = 15000;

  on_byPlayer_applydebuff(event) {
    const spellId = event.ability.guid;
    let targetInstance = event.targetInstance;
    if (spellId !== SPELLS.MARK_OF_THE_CRANE.id) {
      return;
    }
    // The event doesn't specify instance on the first target of that type
    if (targetInstance === undefined) {
      targetInstance = 1;
    }
    const markoftheCraneTarget = {targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp };
    this.markoftheCraneTargets.push(markoftheCraneTarget);
  }

  on_byPlayer_refreshdebuff(event) {
    const spellId = event.ability.guid;
    let targetInstance = event.targetInstance;
    if (spellId !== SPELLS.MARK_OF_THE_CRANE.id) {
      return;
    }
    if (targetInstance === undefined) {
      targetInstance = 1;
    }
    const markoftheCraneTarget = {targetID: event.targetID, targetInstance: targetInstance, timestamp: event.timestamp };
    let i = 0;
    while (i <= this.markoftheCraneTargets.length - 1) {
      if (this.markoftheCraneTargets[i].targetID === markoftheCraneTarget.targetID && this.markoftheCraneTargets[i].targetInstance === markoftheCraneTarget.targetInstance) {
        this.markoftheCraneTargets[i].timestamp = markoftheCraneTarget.timestamp;
      }
      i++;
    }
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.SPINNING_CRANE_KICK.id) {
      return;
    }
    this.markoftheCraneStacks = 0;
    let i = 0;
    while (i < this.markoftheCraneTargets.length) {
      // removing expired targets to avoid looking through huge arrays in logs with a lot of targets
      if (event.timestamp - this.markoftheCraneTargets[i].timestamp > 15000) {
        console.log(this.markoftheCraneTargets.splice(i, 1), "Mark Removed");
      }
      else {
        this.markoftheCraneStacks++;
        //console.log(this.markoftheCraneTargets[i], "Mark of the Crane found and counted");
      }
      i++;
    }
    // TODO: Expand this to also check for targets hit
    if (this.markoftheCraneStacks <= 1) {
      this.badCasts += 1;
    }
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.SPINNING_CRANE_KICK_DAMAGE.id) {
      return;
    }
    this.spinningCraneKickDuration = 1500 / (1 + this.statTracker.hastePercentage(this.statTracker.currentHasteRating));
    this.spinningCraneKickHits++;
    console.log("mark of the crane stacks", this.markoftheCraneStacks, event.timestamp);
    // Spinning Crane Kick deals damage 3 times over 1.5 seconds (reduced by haste)
    // This makes sure it only counts once per cast and only on casts that hit something
    if (event.timestamp - this.lastSpinningCraneKickTick > this.spinningCraneKickDuration) {
      this.totalMarksDuringHits += this.markoftheCraneStacks;
      this.lastSpinningCraneKickTick = event.timestamp;
    }
  }

  averageHits() {
    const averageHits = this.spinningCraneKickHits / this.abilityTracker.getAbility(SPELLS.SPINNING_CRANE_KICK.id).casts;
    return (

            <SpellIcon id={SPELLS.SPINNING_CRANE_KICK.id} /> Average hits

          {averageHits.toFixed(2)}

    );
  }

  averageMarks() {
    const averageMarks = this.totalMarksDuringHits / this.abilityTracker.getAbility(SPELLS.SPINNING_CRANE_KICK.id).casts;
    return (

            <SpellIcon id={SPELLS.MARK_OF_THE_CRANE.id} /> Average marks

          {averageMarks.toFixed(2)}

    );
  }

  badCastsStatistic() {
    return (

            <SpellIcon id={SPELLS.SPINNING_CRANE_KICK.id} /> Bad casts

          {this.badCasts}

    );
  }

  statistic() {
     return (
      <StatisticsListBox
        title="Spinning Crane Kick"
        tooltip=""
        style={{ minHeight: 186 }}
       >
         {this.averageMarks()}
         {this.averageHits()}
         {this.badCastsStatistic()}
      </StatisticsListBox>
    );
  }
  statisticOrder = STATISTIC_ORDER.OPTIONAL(4);
}

export default SpinningCraneKick;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import copy from 'clipboard-copy';
import MdContentCopy from 'react-icons/lib/md/content-copy';
import ToolbarButton from 'rsg-components/ToolbarButton';
import Styled from 'rsg-components/Styled';

export const styles = ({ space, fontFamily, fontSize, color }) => ({
	pathline: {
		fontFamily: fontFamily.monospace,
		fontSize: fontSize.small,
		color: color.light,
	},
	copyButton: {
		marginLeft: space[0],
	},
});

export function PathlineRenderer({ classes, children }) {
	return (

			{children}
			<ToolbarButton
				small
				className={classes.copyButton}
				onClick={() => copy(children)}
				title="Copy to clipboard"
			>
				<MdContentCopy />
			</ToolbarButton>

	);
}

PathlineRenderer.propTypes = {
	classes: PropTypes.object.isRequired,
	children: PropTypes.string,
};

export default Styled(styles)(PathlineRenderer);
<commit_msg>Fix: Allow pathline to wrap (#1125)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import copy from 'clipboard-copy';
import MdContentCopy from 'react-icons/lib/md/content-copy';
import ToolbarButton from 'rsg-components/ToolbarButton';
import Styled from 'rsg-components/Styled';

export const styles = ({ space, fontFamily, fontSize, color }) => ({
	pathline: {
		fontFamily: fontFamily.monospace,
		fontSize: fontSize.small,
		color: color.light,
		wordBreak: 'break-all'
	},
	copyButton: {
		marginLeft: space[0],
	},
});

export function PathlineRenderer({ classes, children }) {
	return (

			{children}
			<ToolbarButton
				small
				className={classes.copyButton}
				onClick={() => copy(children)}
				title="Copy to clipboard"
			>
				<MdContentCopy />
			</ToolbarButton>

	);
}

PathlineRenderer.propTypes = {
	classes: PropTypes.object.isRequired,
	children: PropTypes.string,
};

export default Styled(styles)(PathlineRenderer);
<|endoftext|>