<commit_before>/**
 * Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const chalk = require('chalk');
const _ = require('lodash');
const BaseGenerator = require('../generator-base');
const cleanup = require('../cleanup');
const prompts = require('./prompts');
const packagejs = require('../../package.json');
const statistics = require('../statistics');

module.exports = class extends BaseGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false
        });
        // This adds support for a `--skip-client` flag
        this.option('skip-client', {
            desc: 'Skip the client-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-server` flag
        this.option('skip-server', {
            desc: 'Skip the server-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-git` flag
        this.option('skip-git', {
            desc: 'Skip the git initialization',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-commit-hook` flag
        this.option('skip-commit-hook', {
            desc: 'Skip adding husky commit hooks',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-user-management` flag
        this.option('skip-user-management', {
            desc: 'Skip the user management module during app generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-check-length-of-identifier` flag
        this.option('skip-check-length-of-identifier', {
            desc: 'Skip check the length of the identifier, only for recent Oracle databases that support 30+ characters metadata',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--[no-]i18n` flag
        this.option('i18n', {
            desc: 'Disable or enable i18n when skipping client side generation, has no effect otherwise',
            type: Boolean,
            defaults: true
        });

        // This adds support for a `--with-entities` flag
        this.option('with-entities', {
            desc: 'Regenerate the existing entities if any',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-checks` flag
        this.option('skip-checks', {
            desc: 'Check the status of the required tools',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--jhi-prefix` flag
        this.option('jhi-prefix', {
            desc: 'Add prefix before services, controllers and states name',
            type: String,
            defaults: 'jhi'
        });

        // This adds support for a `--yarn` flag
        this.option('yarn', {
            desc: 'Use yarn instead of npm',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--auth` flag
        this.option('auth', {
            desc: 'Provide authentication type for the application when skipping server',
            type: String
        });

        // This adds support for a `--db` flag
        this.option('db', {
            desc: 'Provide DB name for the application when skipping server',
            type: String
        });

        // This adds support for a `--blueprint` flag which can be used to specify a blueprint to use for generation
        this.option('blueprint', {
            desc: '[BETA] Specify a generator blueprint to use for the sub generators',
            type: String
        });

        // This adds support for a `--experimental` flag which can be used to enable experimental features
        this.option('experimental', {
            desc:
                'Enable experimental features. Please note that these features may be unstable and may undergo breaking changes at any time',
            type: Boolean,
            defaults: false
        });

        this.skipClient = this.configOptions.skipClient = this.options['skip-client'] || this.config.get('skipClient');
        this.skipServer = this.configOptions.skipServer = this.options['skip-server'] || this.config.get('skipServer');
        this.skipUserManagement = this.configOptions.skipUserManagement =
            this.options['skip-user-management'] || this.config.get('skipUserManagement');
        this.skipCheckLengthOfIdentifier = this.configOptions.skipCheckLengthOfIdentifier =
            this.options['skip-check-length-of-identifier'] || this.config.get('skipCheckLengthOfIdentifier');
        this.jhiPrefix = this.configOptions.jhiPrefix = _.camelCase(this.config.get('jhiPrefix') || this.options['jhi-prefix']);
        this.withEntities = this.options['with-entities'];
        this.skipChecks = this.options['skip-checks'];
        const blueprint = this.normalizeBlueprintName(this.options.blueprint || this.config.get('blueprint'));
        this.blueprint = this.configOptions.blueprint = blueprint;
        this.useNpm = this.configOptions.useNpm = !this.options.yarn;
        this.useYarn = !this.useNpm;

        this.isDebugEnabled = this.configOptions.isDebugEnabled = this.options.debug;
        this.experimental = this.configOptions.experimental = this.options.experimental;
        this.registerClientTransforms();
    }

    get initializing() {
        return {
            validateFromCli() {
                if (!this.options['from-cli']) {
                    this.warning(
                        `Deprecated: JHipster seems to be invoked using Yeoman command. Please use the JHipster CLI. Run ${chalk.red(
                            'jhipster <command>'
                        )} instead of ${chalk.red('yo jhipster:<command>')}`
                    );
                }
            },

            displayLogo() {
                this.printJHipsterLogo();
            },

            validateBlueprint() {
                if (this.blueprint) {
                    this.checkBlueprint(this.blueprint);
                }
            },

            validateJava() {
                this.checkJava();
            },

            validateNode() {
                this.checkNode();
            },

            validateGit() {
                this.checkGit();
            },

            validateYarn() {
                this.checkYarn();
            },

            checkForNewJHVersion() {
                if (!this.skipChecks) {
                    this.checkForNewVersion();
                }
            },

            validate() {
                if (this.skipServer && this.skipClient) {
                    this.error(
                        chalk.red(`You can not pass both ${chalk.yellow('--skip-client')} and ${chalk.yellow('--skip-server')} together`)
                    );
                }
            },

            setupconsts() {
                this.applicationType = this.config.get('applicationType');
                if (!this.applicationType) {
                    this.applicationType = 'monolith';
                }
                this.baseName = this.config.get('baseName');
                this.jhipsterVersion = packagejs.version;
                if (this.jhipsterVersion === undefined) {
                    this.jhipsterVersion = this.config.get('jhipsterVersion');
                }
                this.otherModules = this.config.get('otherModules');
                this.testFrameworks = this.config.get('testFrameworks');
                this.enableTranslation = this.config.get('enableTranslation');
                this.nativeLanguage = this.config.get('nativeLanguage');
                this.languages = this.config.get('languages');
                const configFound = this.baseName !== undefined && this.applicationType !== undefined;
                if (configFound) {
                    this.existingProject = true;
                    // If translation is not defined, it is enabled by default
                    if (this.enableTranslation === undefined) {
                        this.enableTranslation = true;
                    }
                }
                this.clientPackageManager = this.config.get('clientPackageManager');
                if (!this.clientPackageManager) {
                    if (this.useNpm) {
                        this.clientPackageManager = 'npm';
                    } else {
                        this.clientPackageManager = 'yarn';
                    }
                }
            }
        };
    }

    get prompting() {
        return {
            askForInsightOptIn: prompts.askForInsightOptIn,
            // TODO : enable this. It's a bit messy for now, it need better sync.
            // askForAccountLinking: prompts.askForAccountLinking,
            askForApplicationType: prompts.askForApplicationType,
            askForModuleName: prompts.askForModuleName
        };
    }

    get configuring() {
        return {
            setup() {
                this.configOptions.skipI18nQuestion = true;
                this.configOptions.baseName = this.baseName;
                this.configOptions.logo = false;
                this.configOptions.otherModules = this.otherModules;
                this.generatorType = 'app';
                if (this.reactive) {
                    // TODO: support client in reactive app
                    this.skipClient = true;
                    this.generatorType = 'server';
                }
                if (this.applicationType === 'microservice') {
                    this.skipClient = true;
                    this.generatorType = 'server';
                    this.skipUserManagement = this.configOptions.skipUserManagement = true;
                }
                if (this.applicationType === 'uaa') {
                    this.skipClient = true;
                    this.generatorType = 'server';
                    this.skipUserManagement = this.configOptions.skipUserManagement = false;
                    this.authenticationType = this.configOptions.authenticationType = 'uaa';
                }
                if (this.skipClient) {
                    // defaults to use when skipping client
                    this.generatorType = 'server';
                    this.configOptions.enableTranslation = this.options.i18n;
                }
                if (this.skipServer) {
                    // defaults to use when skipping server
                    this.generatorType = 'client';
                    this.configOptions.databaseType = this.getDBTypeFromDBValue(this.options.db);
                    this.configOptions.devDatabaseType = this.options.db;
                    this.configOptions.prodDatabaseType = this.options.db;
                    this.configOptions.authenticationType = this.options.auth;
                    this.configOptions.uaaBaseName = this.options.uaaBaseName;
                }
                this.configOptions.clientPackageManager = this.clientPackageManager;
            },

            // composeAccountLinking() {
            //     if (!this.linkAccount) return;

            //     this.composeWith(require.resolve('../link-account'));
            // },

            composeServer() {
                if (this.skipServer) return;

                this.composeWith(require.resolve('../server'), {
                    'client-hook': !this.skipClient,
                    'from-cli': this.options['from-cli'],
                    configOptions: this.configOptions,
                    force: this.options.force,
                    debug: this.isDebugEnabled
                });
            },

            composeClient() {
                if (this.skipClient) return;

                this.composeWith(require.resolve('../client'), {
                    'skip-install': this.options['skip-install'],
                    'skip-commit-hook': this.options['skip-commit-hook'],
                    'from-cli': this.options['from-cli'],
                    configOptions: this.configOptions,
                    force: this.options.force,
                    debug: this.isDebugEnabled
                });
            },

            askFori18n: prompts.askFori18n
        };
    }

    get default() {
        return {
            askForTestOpts: prompts.askForTestOpts,

            askForMoreModules: prompts.askForMoreModules,

            setSharedConfigOptions() {
                this.configOptions.testFrameworks = this.testFrameworks;
                this.configOptions.enableTranslation = this.enableTranslation;
                this.configOptions.nativeLanguage = this.nativeLanguage;
                this.configOptions.languages = this.languages;
                this.configOptions.clientPackageManager = this.clientPackageManager;
            },

            composeLanguages() {
                if (this.skipI18n) return;
                this.composeLanguagesSub(this, this.configOptions, this.generatorType);
            },

            saveConfig() {
                const config = {
                    jhipsterVersion: packagejs.version,
                    applicationType: this.applicationType,
                    baseName: this.baseName,
                    testFrameworks: this.testFrameworks,
                    jhiPrefix: this.jhiPrefix,
                    skipCheckLengthOfIdentifier: this.skipCheckLengthOfIdentifier,
                    otherModules: this.otherModules,
                    enableTranslation: this.enableTranslation,
                    clientPackageManager: this.clientPackageManager
                };
                if (this.enableTranslation) {
                    config.nativeLanguage = this.nativeLanguage;
                    config.languages = this.languages;
                }
                this.blueprint && (config.blueprint = this.blueprint);
                this.reactive && (config.reactive = this.reactive);
                this.skipClient && (config.skipClient = true);
                this.skipServer && (config.skipServer = true);
                this.skipUserManagement && (config.skipUserManagement = true);
                this.config.set(config);
            },

            insight() {
                const yorc = {
                    ..._.omit(this.configOptions, [
                        'jhiPrefix',
                        'baseName',
                        'jwtSecretKey',
                        'packageName',
                        'packagefolder',
                        'rememberMeKey'
                    ])
                };
                yorc.applicationType = this.applicationType;
                statistics.sendYoRc(yorc, this.existingProject, this.jhipsterVersion);
            }
        };
    }

    get writing() {
        return {
            cleanup() {
                cleanup.cleanupOldFiles(this);
            },

            regenerateEntities() {
                if (this.withEntities) {
                    this.getExistingEntities().forEach(entity => {
                        this.composeWith(require.resolve('../entity'), {
                            regenerate: true,
                            'skip-install': true,
                            'from-cli': this.options['from-cli'],
                            force: this.options.force,
                            debug: this.isDebugEnabled,
                            arguments: [entity.name]
                        });
                    });
                }
            },

            generatePackageForMS() {
                if (this.skipClient) {
                    if (this.otherModules === undefined) {
                        this.otherModules = [];
                    }
                    // Generate a package.json file containing the current version
                    // of the generator as dependency
                    this.dasherizedBaseName = _.kebabCase(this.baseName);
                    this.template('skipClientApp.package.json.ejs', 'package.json');
                }
            },

            initGitRepo() {
                if (!this.options['skip-git']) {
                    this.isGitInstalled(code => {
                        if (code === 0) {
                            this.gitExec('rev-parse --is-inside-work-tree', { trace: false }, (err, gitDir) => {
                                if (!gitDir) {
                                    this.gitExec('init', { trace: false }, () => {
                                        this.log(chalk.green.bold('Git repo initiated.'));
                                        this.gitInitialized = true;
                                    });
                                }
                            });
                        } else {
                            this.warning('Git repository could not be initialized, as Git is not installed on your system');
                        }
                    });
                }
            }
        };
    }

    get end() {
        return {
            gitCommit() {
                if (!this.options['skip-git']) {
                    this.debug('Committing files to git');
                    const done = this.async();
                    this.isGitInstalled(code => {
                        if (code === 0 && this.gitInitialized) {
                            this.gitExec('add -A', { trace: false }, () => {
                                let commitMsg = `Initial application generated by JHipster-${this.jhipsterVersion}`;
                                if (this.blueprint) {
                                    commitMsg += ` with blueprint: ${this.blueprint.replace('generator-jhipster-', '')}`;
                                }
                                this.gitExec(`commit -am "${commitMsg}"`, { trace: false }, () => {
                                    this.log(chalk.green.bold('Application successfully committed to Git.'));
                                    done();
                                });
                            });
                        } else {
                            this.warning(
                                'The generated application could not be committed to Git, as a Git repository could not be initialized.'
                            );
                        }
                    });
                }
            },

            afterRunHook() {
                try {
                    const modules = this.getModuleHooks();
                    if (modules.length > 0) {
                        this.log(`\n${chalk.bold.green('Running post run module hooks\n')}`);
                        // run through all post app creation module hooks
                        this.callHooks('app', 'post', {
                            appConfig: this.configOptions,
                            force: this.options.force
                        });
                    }
                } catch (err) {
                    this.log(`\n${chalk.bold.red('Running post run module hooks failed. No modification done to the generated app.')}`);
                    this.debug('Error:', err);
                }
                this.log(
                    chalk.green(
                        `\nIf you find JHipster useful consider supporting our collective ${chalk.yellow(
                            'https://opencollective.com/generator-jhipster'
                        )}`
                    )
                );
            }
        };
    }
};
<commit_msg>wording<commit_after>/**
 * Copyright 2013-2018 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const chalk = require('chalk');
const _ = require('lodash');
const BaseGenerator = require('../generator-base');
const cleanup = require('../cleanup');
const prompts = require('./prompts');
const packagejs = require('../../package.json');
const statistics = require('../statistics');

module.exports = class extends BaseGenerator {
    constructor(args, opts) {
        super(args, opts);

        this.configOptions = {};
        // This adds support for a `--from-cli` flag
        this.option('from-cli', {
            desc: 'Indicates the command is run from JHipster CLI',
            type: Boolean,
            defaults: false
        });
        // This adds support for a `--skip-client` flag
        this.option('skip-client', {
            desc: 'Skip the client-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-server` flag
        this.option('skip-server', {
            desc: 'Skip the server-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-git` flag
        this.option('skip-git', {
            desc: 'Skip the git initialization',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-commit-hook` flag
        this.option('skip-commit-hook', {
            desc: 'Skip adding husky commit hooks',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-user-management` flag
        this.option('skip-user-management', {
            desc: 'Skip the user management module during app generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-check-length-of-identifier` flag
        this.option('skip-check-length-of-identifier', {
            desc: 'Skip check the length of the identifier, only for recent Oracle databases that support 30+ characters metadata',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--[no-]i18n` flag
        this.option('i18n', {
            desc: 'Disable or enable i18n when skipping client side generation, has no effect otherwise',
            type: Boolean,
            defaults: true
        });

        // This adds support for a `--with-entities` flag
        this.option('with-entities', {
            desc: 'Regenerate the existing entities if any',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-checks` flag
        this.option('skip-checks', {
            desc: 'Check the status of the required tools',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--jhi-prefix` flag
        this.option('jhi-prefix', {
            desc: 'Add prefix before services, controllers and states name',
            type: String,
            defaults: 'jhi'
        });

        // This adds support for a `--yarn` flag
        this.option('yarn', {
            desc: 'Use yarn instead of npm',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--auth` flag
        this.option('auth', {
            desc: 'Provide authentication type for the application when skipping server',
            type: String
        });

        // This adds support for a `--db` flag
        this.option('db', {
            desc: 'Provide DB name for the application when skipping server',
            type: String
        });

        // This adds support for a `--blueprint` flag which can be used to specify a blueprint to use for generation
        this.option('blueprint', {
            desc: '[BETA] Specify a generator blueprint to use for the sub generators',
            type: String
        });

        // This adds support for a `--experimental` flag which can be used to enable experimental features
        this.option('experimental', {
            desc:
                'Enable experimental features. Please note that these features may be unstable and may undergo breaking changes at any time',
            type: Boolean,
            defaults: false
        });

        this.skipClient = this.configOptions.skipClient = this.options['skip-client'] || this.config.get('skipClient');
        this.skipServer = this.configOptions.skipServer = this.options['skip-server'] || this.config.get('skipServer');
        this.skipUserManagement = this.configOptions.skipUserManagement =
            this.options['skip-user-management'] || this.config.get('skipUserManagement');
        this.skipCheckLengthOfIdentifier = this.configOptions.skipCheckLengthOfIdentifier =
            this.options['skip-check-length-of-identifier'] || this.config.get('skipCheckLengthOfIdentifier');
        this.jhiPrefix = this.configOptions.jhiPrefix = _.camelCase(this.config.get('jhiPrefix') || this.options['jhi-prefix']);
        this.withEntities = this.options['with-entities'];
        this.skipChecks = this.options['skip-checks'];
        const blueprint = this.normalizeBlueprintName(this.options.blueprint || this.config.get('blueprint'));
        this.blueprint = this.configOptions.blueprint = blueprint;
        this.useNpm = this.configOptions.useNpm = !this.options.yarn;
        this.useYarn = !this.useNpm;

        this.isDebugEnabled = this.configOptions.isDebugEnabled = this.options.debug;
        this.experimental = this.configOptions.experimental = this.options.experimental;
        this.registerClientTransforms();
    }

    get initializing() {
        return {
            validateFromCli() {
                if (!this.options['from-cli']) {
                    this.warning(
                        `Deprecated: JHipster seems to be invoked using Yeoman command. Please use the JHipster CLI. Run ${chalk.red(
                            'jhipster <command>'
                        )} instead of ${chalk.red('yo jhipster:<command>')}`
                    );
                }
            },

            displayLogo() {
                this.printJHipsterLogo();
            },

            validateBlueprint() {
                if (this.blueprint) {
                    this.checkBlueprint(this.blueprint);
                }
            },

            validateJava() {
                this.checkJava();
            },

            validateNode() {
                this.checkNode();
            },

            validateGit() {
                this.checkGit();
            },

            validateYarn() {
                this.checkYarn();
            },

            checkForNewJHVersion() {
                if (!this.skipChecks) {
                    this.checkForNewVersion();
                }
            },

            validate() {
                if (this.skipServer && this.skipClient) {
                    this.error(
                        chalk.red(`You can not pass both ${chalk.yellow('--skip-client')} and ${chalk.yellow('--skip-server')} together`)
                    );
                }
            },

            setupconsts() {
                this.applicationType = this.config.get('applicationType');
                if (!this.applicationType) {
                    this.applicationType = 'monolith';
                }
                this.baseName = this.config.get('baseName');
                this.jhipsterVersion = packagejs.version;
                if (this.jhipsterVersion === undefined) {
                    this.jhipsterVersion = this.config.get('jhipsterVersion');
                }
                this.otherModules = this.config.get('otherModules');
                this.testFrameworks = this.config.get('testFrameworks');
                this.enableTranslation = this.config.get('enableTranslation');
                this.nativeLanguage = this.config.get('nativeLanguage');
                this.languages = this.config.get('languages');
                const configFound = this.baseName !== undefined && this.applicationType !== undefined;
                if (configFound) {
                    this.existingProject = true;
                    // If translation is not defined, it is enabled by default
                    if (this.enableTranslation === undefined) {
                        this.enableTranslation = true;
                    }
                }
                this.clientPackageManager = this.config.get('clientPackageManager');
                if (!this.clientPackageManager) {
                    if (this.useNpm) {
                        this.clientPackageManager = 'npm';
                    } else {
                        this.clientPackageManager = 'yarn';
                    }
                }
            }
        };
    }

    get prompting() {
        return {
            askForInsightOptIn: prompts.askForInsightOptIn,
            // TODO : enable this. It's a bit messy for now, it need better sync.
            // askForAccountLinking: prompts.askForAccountLinking,
            askForApplicationType: prompts.askForApplicationType,
            askForModuleName: prompts.askForModuleName
        };
    }

    get configuring() {
        return {
            setup() {
                this.configOptions.skipI18nQuestion = true;
                this.configOptions.baseName = this.baseName;
                this.configOptions.logo = false;
                this.configOptions.otherModules = this.otherModules;
                this.generatorType = 'app';
                if (this.reactive) {
                    // TODO: support client in reactive app
                    this.skipClient = true;
                    this.generatorType = 'server';
                }
                if (this.applicationType === 'microservice') {
                    this.skipClient = true;
                    this.generatorType = 'server';
                    this.skipUserManagement = this.configOptions.skipUserManagement = true;
                }
                if (this.applicationType === 'uaa') {
                    this.skipClient = true;
                    this.generatorType = 'server';
                    this.skipUserManagement = this.configOptions.skipUserManagement = false;
                    this.authenticationType = this.configOptions.authenticationType = 'uaa';
                }
                if (this.skipClient) {
                    // defaults to use when skipping client
                    this.generatorType = 'server';
                    this.configOptions.enableTranslation = this.options.i18n;
                }
                if (this.skipServer) {
                    // defaults to use when skipping server
                    this.generatorType = 'client';
                    this.configOptions.databaseType = this.getDBTypeFromDBValue(this.options.db);
                    this.configOptions.devDatabaseType = this.options.db;
                    this.configOptions.prodDatabaseType = this.options.db;
                    this.configOptions.authenticationType = this.options.auth;
                    this.configOptions.uaaBaseName = this.options.uaaBaseName;
                }
                this.configOptions.clientPackageManager = this.clientPackageManager;
            },

            // composeAccountLinking() {
            //     if (!this.linkAccount) return;

            //     this.composeWith(require.resolve('../link-account'));
            // },

            composeServer() {
                if (this.skipServer) return;

                this.composeWith(require.resolve('../server'), {
                    'client-hook': !this.skipClient,
                    'from-cli': this.options['from-cli'],
                    configOptions: this.configOptions,
                    force: this.options.force,
                    debug: this.isDebugEnabled
                });
            },

            composeClient() {
                if (this.skipClient) return;

                this.composeWith(require.resolve('../client'), {
                    'skip-install': this.options['skip-install'],
                    'skip-commit-hook': this.options['skip-commit-hook'],
                    'from-cli': this.options['from-cli'],
                    configOptions: this.configOptions,
                    force: this.options.force,
                    debug: this.isDebugEnabled
                });
            },

            askFori18n: prompts.askFori18n
        };
    }

    get default() {
        return {
            askForTestOpts: prompts.askForTestOpts,

            askForMoreModules: prompts.askForMoreModules,

            setSharedConfigOptions() {
                this.configOptions.testFrameworks = this.testFrameworks;
                this.configOptions.enableTranslation = this.enableTranslation;
                this.configOptions.nativeLanguage = this.nativeLanguage;
                this.configOptions.languages = this.languages;
                this.configOptions.clientPackageManager = this.clientPackageManager;
            },

            composeLanguages() {
                if (this.skipI18n) return;
                this.composeLanguagesSub(this, this.configOptions, this.generatorType);
            },

            saveConfig() {
                const config = {
                    jhipsterVersion: packagejs.version,
                    applicationType: this.applicationType,
                    baseName: this.baseName,
                    testFrameworks: this.testFrameworks,
                    jhiPrefix: this.jhiPrefix,
                    skipCheckLengthOfIdentifier: this.skipCheckLengthOfIdentifier,
                    otherModules: this.otherModules,
                    enableTranslation: this.enableTranslation,
                    clientPackageManager: this.clientPackageManager
                };
                if (this.enableTranslation) {
                    config.nativeLanguage = this.nativeLanguage;
                    config.languages = this.languages;
                }
                this.blueprint && (config.blueprint = this.blueprint);
                this.reactive && (config.reactive = this.reactive);
                this.skipClient && (config.skipClient = true);
                this.skipServer && (config.skipServer = true);
                this.skipUserManagement && (config.skipUserManagement = true);
                this.config.set(config);
            },

            insight() {
                const yorc = {
                    ..._.omit(this.configOptions, [
                        'jhiPrefix',
                        'baseName',
                        'jwtSecretKey',
                        'packageName',
                        'packagefolder',
                        'rememberMeKey'
                    ])
                };
                yorc.applicationType = this.applicationType;
                statistics.sendYoRc(yorc, this.existingProject, this.jhipsterVersion);
            }
        };
    }

    get writing() {
        return {
            cleanup() {
                cleanup.cleanupOldFiles(this);
            },

            regenerateEntities() {
                if (this.withEntities) {
                    this.getExistingEntities().forEach(entity => {
                        this.composeWith(require.resolve('../entity'), {
                            regenerate: true,
                            'skip-install': true,
                            'from-cli': this.options['from-cli'],
                            force: this.options.force,
                            debug: this.isDebugEnabled,
                            arguments: [entity.name]
                        });
                    });
                }
            },

            generatePackageForMS() {
                if (this.skipClient) {
                    if (this.otherModules === undefined) {
                        this.otherModules = [];
                    }
                    // Generate a package.json file containing the current version
                    // of the generator as dependency
                    this.dasherizedBaseName = _.kebabCase(this.baseName);
                    this.template('skipClientApp.package.json.ejs', 'package.json');
                }
            },

            initGitRepo() {
                if (!this.options['skip-git']) {
                    this.isGitInstalled(code => {
                        if (code === 0) {
                            this.gitExec('rev-parse --is-inside-work-tree', { trace: false }, (err, gitDir) => {
                                if (!gitDir) {
                                    this.gitExec('init', { trace: false }, () => {
                                        this.log(chalk.green.bold('Git repository initialized.'));
                                        this.gitInitialized = true;
                                    });
                                }
                            });
                        } else {
                            this.warning('Git repository could not be initialized, as Git is not installed on your system');
                        }
                    });
                }
            }
        };
    }

    get end() {
        return {
            gitCommit() {
                if (!this.options['skip-git']) {
                    this.debug('Committing files to git');
                    const done = this.async();
                    this.isGitInstalled(code => {
                        if (code === 0 && this.gitInitialized) {
                            this.gitExec('add -A', { trace: false }, () => {
                                let commitMsg = `Initial application generated by JHipster-${this.jhipsterVersion}`;
                                if (this.blueprint) {
                                    commitMsg += ` with blueprint: ${this.blueprint.replace('generator-jhipster-', '')}`;
                                }
                                this.gitExec(`commit -am "${commitMsg}"`, { trace: false }, () => {
                                    this.log(chalk.green.bold('Application successfully committed to Git.'));
                                    done();
                                });
                            });
                        } else {
                            this.warning(
                                'The generated application could not be committed to Git, as a Git repository could not be initialized.'
                            );
                        }
                    });
                }
            },

            afterRunHook() {
                try {
                    const modules = this.getModuleHooks();
                    if (modules.length > 0) {
                        this.log(`\n${chalk.bold.green('Running post run module hooks\n')}`);
                        // run through all post app creation module hooks
                        this.callHooks('app', 'post', {
                            appConfig: this.configOptions,
                            force: this.options.force
                        });
                    }
                } catch (err) {
                    this.log(`\n${chalk.bold.red('Running post run module hooks failed. No modification done to the generated app.')}`);
                    this.debug('Error:', err);
                }
                this.log(
                    chalk.green(
                        `\nIf you find JHipster useful consider supporting our collective ${chalk.yellow(
                            'https://opencollective.com/generator-jhipster'
                        )}`
                    )
                );
            }
        };
    }
};
<|endoftext|>


<commit_before>import regeneratorRuntime from 'regenerator-runtime' // eslint-disable-line

export default class Tooling {
  constructor(request) {
    this.request = request
  }

  getOrCreateDebugLevel() {
    const LOG_LEVEL_NAME = 'ApexDebugger'
    const headers = {
      Accept: '*/*'
    }
    const query = encodeURIComponent(
      "Select Id From DebugLevel Where DeveloperName = '" + LOG_LEVEL_NAME + "'"
    )
    var debugLevelPayload = {
      DeveloperName: LOG_LEVEL_NAME,
      MasterLabel: LOG_LEVEL_NAME,
      Workflow: 'DEBUG',
      Validation: 'DEBUG',
      Callout: 'DEBUG',
      ApexCode: 'DEBUG',
      ApexProfiling: 'DEBUG',
      Visualforce: 'DEBUG',
      System: 'DEBUG',
      Database: 'DEBUG'
    }
    return this.request(
      `/services/data/v36.0/tooling/query?q=${query}`,
      'GET',
      headers
    ).then(existingDebugLevel => {
      if (existingDebugLevel.records.length > 0) {
        return existingDebugLevel.records[0].Id
      } else {
        return this.request(
          '/services/data/v36.0/tooling/sobjects/DebugLevel',
          'POST',
          headers,
          debugLevelPayload
        ).then(result => result.id)
      }
    })
  }

  async removeTraceFlags(userId, debugLevelId) {
    const query = `Select Id From TraceFlag Where TracedEntityId = '${userId}' AND DebugLevelId= '${debugLevelId}'`
    const existingTraceFlags = await this.query(query)
    return Promise.all(
      existingTraceFlags.records.map(traceFlag =>
        this.request(
          `/services/data/v41.0/tooling/sobjects/TraceFlag/${traceFlag.Id}`,
          'DELETE'
        )
      )
    )
  }

  createTraceFlag(userId, debugLevelId) {
    const MS_IN_DAY = 1000 * 59 * 60 * 24
    let expirationDate = new Date(Date.now() + MS_IN_DAY)
    var payload = {
      TracedEntityId: userId,
      DebugLevelId: debugLevelId,
      LogType: 'DEVELOPER_LOG'
    }
    return this.request(
      '/services/data/v41.0/tooling/sobjects/TraceFlag',
      'POST',
      {},
      { ...payload, ExpirationDate: expirationDate }
    ).catch(async err => {
      // fallback, try without expiration date
      await this.removeTraceFlags(userId, debugLevelId)
      this.request(
        '/services/data/v41.0/tooling/sobjects/TraceFlag',
        'POST',
        {},
        payload
      )
    })
  }

  getLogBody(logId) {
    return this.request(
      `/services/data/v32.0/tooling/sobjects/ApexLog/${logId}/Body`,
      'GET',
      {},
      undefined,
      'text'
    ).then(r => r.text())
  }

  query(query) {
    return this.request(`/services/data/v36.0/tooling/query?q=${query}`)
  }
}
<commit_msg>change debuglevel name<commit_after>import regeneratorRuntime from 'regenerator-runtime' // eslint-disable-line

export default class Tooling {
  constructor(request) {
    this.request = request
  }

  getOrCreateDebugLevel() {
    const LOG_LEVEL_NAME = 'ApexDebuggerExtension'
    const headers = {
      Accept: '*/*'
    }
    const query = encodeURIComponent(
      "Select Id From DebugLevel Where DeveloperName = '" + LOG_LEVEL_NAME + "'"
    )
    var debugLevelPayload = {
      DeveloperName: LOG_LEVEL_NAME,
      MasterLabel: LOG_LEVEL_NAME,
      Workflow: 'DEBUG',
      Validation: 'DEBUG',
      Callout: 'DEBUG',
      ApexCode: 'DEBUG',
      ApexProfiling: 'DEBUG',
      Visualforce: 'DEBUG',
      System: 'DEBUG',
      Database: 'DEBUG'
    }
    return this.request(
      `/services/data/v36.0/tooling/query?q=${query}`,
      'GET',
      headers
    ).then(existingDebugLevel => {
      if (existingDebugLevel.records.length > 0) {
        return existingDebugLevel.records[0].Id
      } else {
        return this.request(
          '/services/data/v36.0/tooling/sobjects/DebugLevel',
          'POST',
          headers,
          debugLevelPayload
        ).then(result => result.id)
      }
    })
  }

  async removeTraceFlags(userId, debugLevelId) {
    const query = `Select Id From TraceFlag Where TracedEntityId = '${userId}' AND DebugLevelId= '${debugLevelId}'`
    const existingTraceFlags = await this.query(query)
    return Promise.all(
      existingTraceFlags.records.map(traceFlag =>
        this.request(
          `/services/data/v41.0/tooling/sobjects/TraceFlag/${traceFlag.Id}`,
          'DELETE'
        )
      )
    )
  }

  createTraceFlag(userId, debugLevelId) {
    const MS_IN_DAY = 1000 * 59 * 60 * 24
    let expirationDate = new Date(Date.now() + MS_IN_DAY)
    var payload = {
      TracedEntityId: userId,
      DebugLevelId: debugLevelId,
      LogType: 'DEVELOPER_LOG'
    }
    return this.request(
      '/services/data/v41.0/tooling/sobjects/TraceFlag',
      'POST',
      {},
      { ...payload, ExpirationDate: expirationDate }
    ).catch(async err => {
      // fallback, try without expiration date
      await this.removeTraceFlags(userId, debugLevelId)
      this.request(
        '/services/data/v41.0/tooling/sobjects/TraceFlag',
        'POST',
        {},
        payload
      )
    })
  }

  getLogBody(logId) {
    return this.request(
      `/services/data/v32.0/tooling/sobjects/ApexLog/${logId}/Body`,
      'GET',
      {},
      undefined,
      'text'
    ).then(r => r.text())
  }

  query(query) {
    return this.request(`/services/data/v36.0/tooling/query?q=${query}`)
  }
}
<|endoftext|>


<commit_before>'use strict';

//
//  Yeoman bat app generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   mkdirp          = require( 'mkdirp' )
,   chalk           = require( 'chalk' )
,   semver          = require( 'semver' )
,   _               = require( 'lodash' )
;

var clean           = require( 'underscore.string/clean' );

//  Use different delimiters when our template itself is meant to be a template or template-like.
//
var tpl_tpl_settings =
        {
            evaluate:       /#%([\s\S]+?)%#/g
        ,   escape:         /#-([\s\S]+?)-#/g

        //  Not (yet) used:
        //
        ,   interpolate:    null
        }
;

var AppGenerator = generators.Base.extend(
    {
        constructor: function ()
        {
            generators.Base.apply( this, arguments );

            this.argument(
                'packageName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The package name of the webapp to create.'
                ,   defaults:       this.appname
                }
            );
        }

    ,   initializing: function ()
        {
            //  Load the BAT generator's 'package.json'.
            //
            this.pkg = require( './../../package.json' );

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                /* jshint laxbreak: true */

                var done = this.async();

                //  Have Yeoman greet the user.
                //
                this.log( yosay(
                    'Welcome to the BAT generator! (Backbone Application Template)\n'
                +   'Powered by marviq'
                ));

                //  Ask the user for the webapp details.
                //
                var prompts = [
                    {
                        name:       'packageName'
                    ,   message:    'What is the package name of this webapp?'
                    ,   default:    this.packageName
                    ,   validate:   youtil.isNpmName
                    }
                ,   {
                        name:       'packageDescription'
                    ,   message:    'What is the purpose (description) of this webapp?'
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     youtil.sentencify
                    }
                ,   {
                        name:       'authorName'
                    ,   message:    'What is your name?'
                    ,   default:    this.user.git.name()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     clean
                    }
                ,   {
                        name:       'authorEmail'
                    ,   message:    'What is your email address?'
                    ,   default:    this.user.git.email()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'authorUrl'
                    ,   message:    'If any, by what URL would you like to be known?'
                    ,   default:    ''
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'multiLanguage'
                    ,   type:       'confirm'
                    ,   message:    'Do you need multi language support?'
                    ,   default:    false
                    }
                ,   {
                        name:       'ie8'
                    ,   type:       'confirm'
                    ,   message:    'Do you need IE8 and lower support? (affects the jQuery version and shims HTML5 and media query support)'
                    ,   default:    false
                    }
                ,   {
                        name:       'demo'
                    ,   type:       'confirm'
                    ,   message:    'Would you like the demo app now? (If not, you can always get it later through `yo bat:demo`)'
                    ,   default:    false
                    }
                ];

                this.prompt(
                    prompts
                ,   function ( answers )
                    {
                        _.extend( this.templateData, answers );

                        done();

                    }.bind( this )
                );
            }
        }

    ,   configuring: function ()
        {
            var data    = this.templateData;

            data.i18n   = data.multiLanguage || data.demo;

            //
            //  Save a '.yo-rc.json' config file.
            //  At the very least this marks your project root for sub-generators.
            //
            //  Note that answers to prompts that have `store: true` defined aren't stored here, but in '~/.yo-rc-global.json'.
            //

            this.config.set(
                {
                    'generator-version':    this.pkg.version

                ,   ie8:                    data.ie8
                ,   i18n:                   data.i18n
                }
            );
        }

    ,   writing:
        {
            setupDirectoryStructure: function ()
            {
                var data    = this.templateData
                ,   layout  =
                    [
                        //  App source:

                        'src'

                        //  Backbone:

                    ,   'src/collections'
                    ,   'src/models'
                    ,   'src/views'

                        //  Style and Compass:

                    ,   'src/sass'

                    ,   'src/style'
                    ,   'src/style/images/'
                    ,   'src/style/images/sprites/'

                        //  Testing:

                    ,   'test'

                        //  Third-party, external libraries:

                    ,   'vendor'
                    ]
                ;

                //  Location for 'i' + 'nternationalisatio'.length + 'n' definitions:
                //
                //  https://github.com/marviq/madlib-locale#readme
                //

                if ( data.i18n )
                {
                    layout.push( 'src/i18n' );
                }

                for ( var i=0, l=layout.length; i < l ; i++ )
                {
                    mkdirp.sync( this.destinationPath( layout[ i ] ));
                }
            }

        ,   setupProjectFiles: function()
            {
                var data        = this.templateData
                ,   templates   =
                    [
                        //  Project

                        '@.editorconfig'
                    ,   '@.gitattributes'
                    ,   '@.gitignore'
                    ,   '@.jshintrc'
                    ,   [ '@AUTHORS' ]
                    ,   [ '@Gruntfile.coffee', tpl_tpl_settings ]
                    ,   '@LICENSE'
                    ,   [ '@README.md' ]
                    ,   '@coffeelint.json'

                    ,   [ '@package.json' ]

                        //  Style and Compass:

                    ,   'src/sass/app.sass'
                    ,   'src/sass/_settings.sass'
                    ,   'src/sass/_views.sass'
                    ,   'src/style/images/sprites/check-green.png'
                    ]
                ;

                if ( data.demo )
                {
                    this.composeWith( 'bat:demo' );
                }
                else
                {
                    //
                    //  Do not write these when a demo app is wanted right now; avoids conflicts.
                    //

                    templates.push(

                        //  The app main entry point:

                        [ 'src/app.coffee' ]
                    ,   [ 'src/index.template.html', tpl_tpl_settings ]

                        //  Backbone:

                    ,   [ 'src/router.coffee' ]

                    ,   'src/sass/views/_index.sass'
                    ,   'src/views/index.coffee'
                    ,   'src/views/index.hbs'
                    );

                    if ( this.i18n )
                    {
                        templates.push(
                            'src/i18n/en_GB.json'
                        ,   'src/i18n/nl_NL.json'
                        );
                    }
                }

                this._templatesProcess( templates );
            }
        }

    ,   install: function ()
        {
            /* jshint laxbreak: true */

            var data = this.templateData
            ,   deps =
                    [
                        'backbone'
                    ,   ( 'jquery' + ( data.ie8 ? '@<2' : '' ))
                    ,   'madlib-console'
                    ,   'madlib-hostmapping'
                    ,   'madlib-settings'
                    ,   'q'
                    ,   'underscore'
                    ]
            ,   devDeps =
                    [
                        'browserify'
                    ,   'browserify-shim'
                    ,   'chai'
                    ,   'coffeeify'
                    ,   'grunt'
                    ,   'grunt-browserify'
                    ,   'grunt-coffee-jshint'
                    ,   'grunt-coffeelint'
                    ,   'grunt-contrib-clean'
                    ,   'grunt-contrib-compass'
                    ,   'grunt-contrib-compress'
                    ,   'grunt-contrib-copy'
                    ,   'grunt-contrib-uglify'
                    ,   'grunt-contrib-watch'
                    ,   'grunt-contrib-yuidoc'
                    ,   'grunt-mocha-test'
                    ,   'grunt-template'
                    ,   'handlebars'
                    ,   'hbsfy'
                    ]
            ;

            if ( data.i18n )
            {
                deps.push( 'madlib-locale' );
            }

            this.log( chalk.bold(
                '\n'
            +   'Running a number of "'
            +   chalk.yellow( 'npm install ' + chalk.cyan( '<package>' ) + ' --save' + chalk.cyan( '[' ) + '-dev' + chalk.cyan( ']' ))
            +   '"s for you to install required dependencies.'
            ));

            this.npmInstall( deps,      { save:     true } );
            this.npmInstall( devDeps,   { saveDev:  true } );
        }

    ,   end:
        {
            intro: function ()
            {
                /* jshint laxbreak: true */

                this.preReqIssues = 0;

                this.log(
                    '\n'
                +   chalk.bold( 'I\m all done. You may invoke "' + chalk.yellow( 'grunt' ) + chalk.cyan( ' <arg>...' ) + '" now to build your project.' )
                );
            }

        ,   assesGrunt: function ()
            {
                var done    = this.async()
                ,   error   = function ()
                    {
                        /* jshint laxbreak: true */

                        this.log(
                            '\n'
                        +   chalk.red( 'Hang on, it appears that "' + chalk.bold.yellow( 'grunt' ) + '" hasn\'t been installed yet!\n' )
                        +   '\n'
                        +   chalk.gray(
                                'Consider running "'
                            +   chalk.bold.yellow( chalk.cyan( '[' ) + 'sudo ' + chalk.cyan( ']' ) + 'npm install -g grunt-cli' )
                            +   '" first.\n'
                            )
                        );

                        this.preReqIssues++;

                    }.bind( this )
                ;

                this.spawnCommand( 'command', [ '-v', 'grunt' ], { stdio: 'ignore' } )
                    .on( 'exit', function ( exit )
                        {
                            if ( exit ) { error(); }
                            done();
                        }
                    )
                ;
            }

        ,   assesCompass: function ()
            {
                var done    = this.async()
                ,   minver  = '1.0.0'
                ,   version = ''
                ,   compass = chalk.bold.yellow( 'compass' )
                ,   error   = function ( nexist )
                    {
                        /* jshint laxbreak: true */

                        var first = !( this.preReqIssues );

                        this.log(
                            '\n'
                        +   chalk.red(
                                ( first ? 'Hang on,' : 'Oh, and' )
                            +   (   nexist
                                ?   ' it appears that "' + compass + '" hasn\'t been installed ' + ( first ? 'yet' : 'either' ) + '!\n'
                                :   ' your "' + compass + '" version appears outdated' + ( first ? '' : ' as well' ) + '! '
                                +   'I found only ' + chalk.underline( version ) + ' and you\'ll need ' + chalk.underline( minver + ' or newer' ) + '.\n'
                                )
                            )
                        +   '\n'
                        +   chalk.gray(
                                'Consider running "'
                            +   chalk.bold.yellow( chalk.cyan( '[' ) + 'sudo ' + chalk.cyan( ']' ) + 'gem install compass' ) + '" '
                            +   ( first ? 'first' : 'too' ) + '.\n'
                            +   '\n'
                            +   'Or see: ' + chalk.blue( 'http://thesassway.com/beginner/getting-started-with-sass-and-compass#install-sass-and-compass\n' )
                            )
                        );

                        this.preReqIssues++;

                    }.bind( this )
                ;

                this.spawnCommand( 'command', [ 'compass', '-q', '-v' ], { stdio: [ 'ignore', 'pipe', 'ignore' ] } )
                    .on( 'exit', function ( exit )
                        {
                            version = version.trim();

                            if ( exit || !( semver.satisfies( version, '>=' + minver )) ) { error( exit ); }
                            done();
                        }
                    )
                    .stdout.on( 'data', function ( chunk )
                        {
                            version += chunk;
                        }
                    )
                ;
            }

        ,   epilogue: function ()
            {
                /* jshint laxbreak: true */

                this.log(
                    '\n'
                +   ( this.preReqIssues ? 'In any case, h' : 'H' ) + 'ere\'s a quick reminder of common grunt idioms:\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt ' + chalk.cyan( '[' ) + 'default' + chalk.cyan( ']' ) + '     ' ))
                +   '- does a production, non-debugging, all-parts, minified build plus artifacts;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt debug         ' ))
                +   '- does a testing, debugging, all-parts except documentation, as-is build;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt dev           ' ))
                +   '- does a local, debugging, all-parts except documentation, as-is build; and keeps a close\n'
                +   '                          watch on filesystem changes, selectively re-triggering part builds as needed;\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt doc           ' ))
                +   '- will build just the code documentation;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt lint          ' ))
                +   '- will just lint your code;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt test          ' ))
                +   '- will run your test suite;\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt --help        ' ))
                +   '- will show you all of the above and the kitchen sink;\n'
                );
            }
        }
    }
);

_.extend(
    AppGenerator.prototype
,   require( './../../lib/generator.js' )
);

module.exports = AppGenerator;
<commit_msg>fix(app generator): fix expanding default index view for the template that it always was.<commit_after>'use strict';

//
//  Yeoman bat app generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   mkdirp          = require( 'mkdirp' )
,   chalk           = require( 'chalk' )
,   semver          = require( 'semver' )
,   _               = require( 'lodash' )
;

var clean           = require( 'underscore.string/clean' );

//  Use different delimiters when our template itself is meant to be a template or template-like.
//
var tpl_tpl_settings =
        {
            evaluate:       /#%([\s\S]+?)%#/g
        ,   escape:         /#-([\s\S]+?)-#/g

        //  Not (yet) used:
        //
        ,   interpolate:    null
        }
;

var AppGenerator = generators.Base.extend(
    {
        constructor: function ()
        {
            generators.Base.apply( this, arguments );

            this.argument(
                'packageName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The package name of the webapp to create.'
                ,   defaults:       this.appname
                }
            );
        }

    ,   initializing: function ()
        {
            //  Load the BAT generator's 'package.json'.
            //
            this.pkg = require( './../../package.json' );

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                /* jshint laxbreak: true */

                var done = this.async();

                //  Have Yeoman greet the user.
                //
                this.log( yosay(
                    'Welcome to the BAT generator! (Backbone Application Template)\n'
                +   'Powered by marviq'
                ));

                //  Ask the user for the webapp details.
                //
                var prompts = [
                    {
                        name:       'packageName'
                    ,   message:    'What is the package name of this webapp?'
                    ,   default:    this.packageName
                    ,   validate:   youtil.isNpmName
                    }
                ,   {
                        name:       'packageDescription'
                    ,   message:    'What is the purpose (description) of this webapp?'
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     youtil.sentencify
                    }
                ,   {
                        name:       'authorName'
                    ,   message:    'What is your name?'
                    ,   default:    this.user.git.name()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     clean
                    }
                ,   {
                        name:       'authorEmail'
                    ,   message:    'What is your email address?'
                    ,   default:    this.user.git.email()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'authorUrl'
                    ,   message:    'If any, by what URL would you like to be known?'
                    ,   default:    ''
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'multiLanguage'
                    ,   type:       'confirm'
                    ,   message:    'Do you need multi language support?'
                    ,   default:    false
                    }
                ,   {
                        name:       'ie8'
                    ,   type:       'confirm'
                    ,   message:    'Do you need IE8 and lower support? (affects the jQuery version and shims HTML5 and media query support)'
                    ,   default:    false
                    }
                ,   {
                        name:       'demo'
                    ,   type:       'confirm'
                    ,   message:    'Would you like the demo app now? (If not, you can always get it later through `yo bat:demo`)'
                    ,   default:    false
                    }
                ];

                this.prompt(
                    prompts
                ,   function ( answers )
                    {
                        _.extend( this.templateData, answers );

                        done();

                    }.bind( this )
                );
            }
        }

    ,   configuring: function ()
        {
            var data    = this.templateData;

            data.i18n   = data.multiLanguage || data.demo;

            //
            //  Save a '.yo-rc.json' config file.
            //  At the very least this marks your project root for sub-generators.
            //
            //  Note that answers to prompts that have `store: true` defined aren't stored here, but in '~/.yo-rc-global.json'.
            //

            this.config.set(
                {
                    'generator-version':    this.pkg.version

                ,   ie8:                    data.ie8
                ,   i18n:                   data.i18n
                }
            );
        }

    ,   writing:
        {
            setupDirectoryStructure: function ()
            {
                var data    = this.templateData
                ,   layout  =
                    [
                        //  App source:

                        'src'

                        //  Backbone:

                    ,   'src/collections'
                    ,   'src/models'
                    ,   'src/views'

                        //  Style and Compass:

                    ,   'src/sass'

                    ,   'src/style'
                    ,   'src/style/images/'
                    ,   'src/style/images/sprites/'

                        //  Testing:

                    ,   'test'

                        //  Third-party, external libraries:

                    ,   'vendor'
                    ]
                ;

                //  Location for 'i' + 'nternationalisatio'.length + 'n' definitions:
                //
                //  https://github.com/marviq/madlib-locale#readme
                //

                if ( data.i18n )
                {
                    layout.push( 'src/i18n' );
                }

                for ( var i=0, l=layout.length; i < l ; i++ )
                {
                    mkdirp.sync( this.destinationPath( layout[ i ] ));
                }
            }

        ,   setupProjectFiles: function()
            {
                var data        = this.templateData
                ,   templates   =
                    [
                        //  Project

                        '@.editorconfig'
                    ,   '@.gitattributes'
                    ,   '@.gitignore'
                    ,   '@.jshintrc'
                    ,   [ '@AUTHORS' ]
                    ,   [ '@Gruntfile.coffee', tpl_tpl_settings ]
                    ,   '@LICENSE'
                    ,   [ '@README.md' ]
                    ,   '@coffeelint.json'

                    ,   [ '@package.json' ]

                        //  Style and Compass:

                    ,   'src/sass/app.sass'
                    ,   'src/sass/_settings.sass'
                    ,   'src/sass/_views.sass'
                    ,   'src/style/images/sprites/check-green.png'
                    ]
                ;

                if ( data.demo )
                {
                    this.composeWith( 'bat:demo' );
                }
                else
                {
                    //
                    //  Do not write these when a demo app is wanted right now; avoids conflicts.
                    //

                    templates.push(

                        //  The app main entry point:

                        [ 'src/app.coffee' ]
                    ,   [ 'src/index.template.html', tpl_tpl_settings ]

                        //  Backbone:

                    ,   [ 'src/router.coffee' ]

                    ,   'src/sass/views/_index.sass'
                    ,   [ 'src/views/index.coffee' ]
                    ,   'src/views/index.hbs'
                    );

                    if ( this.i18n )
                    {
                        templates.push(
                            'src/i18n/en_GB.json'
                        ,   'src/i18n/nl_NL.json'
                        );
                    }
                }

                this._templatesProcess( templates );
            }
        }

    ,   install: function ()
        {
            /* jshint laxbreak: true */

            var data = this.templateData
            ,   deps =
                    [
                        'backbone'
                    ,   ( 'jquery' + ( data.ie8 ? '@<2' : '' ))
                    ,   'madlib-console'
                    ,   'madlib-hostmapping'
                    ,   'madlib-settings'
                    ,   'q'
                    ,   'underscore'
                    ]
            ,   devDeps =
                    [
                        'browserify'
                    ,   'browserify-shim'
                    ,   'chai'
                    ,   'coffeeify'
                    ,   'grunt'
                    ,   'grunt-browserify'
                    ,   'grunt-coffee-jshint'
                    ,   'grunt-coffeelint'
                    ,   'grunt-contrib-clean'
                    ,   'grunt-contrib-compass'
                    ,   'grunt-contrib-compress'
                    ,   'grunt-contrib-copy'
                    ,   'grunt-contrib-uglify'
                    ,   'grunt-contrib-watch'
                    ,   'grunt-contrib-yuidoc'
                    ,   'grunt-mocha-test'
                    ,   'grunt-template'
                    ,   'handlebars'
                    ,   'hbsfy'
                    ]
            ;

            if ( data.i18n )
            {
                deps.push( 'madlib-locale' );
            }

            this.log( chalk.bold(
                '\n'
            +   'Running a number of "'
            +   chalk.yellow( 'npm install ' + chalk.cyan( '<package>' ) + ' --save' + chalk.cyan( '[' ) + '-dev' + chalk.cyan( ']' ))
            +   '"s for you to install required dependencies.'
            ));

            this.npmInstall( deps,      { save:     true } );
            this.npmInstall( devDeps,   { saveDev:  true } );
        }

    ,   end:
        {
            intro: function ()
            {
                /* jshint laxbreak: true */

                this.preReqIssues = 0;

                this.log(
                    '\n'
                +   chalk.bold( 'I\m all done. You may invoke "' + chalk.yellow( 'grunt' ) + chalk.cyan( ' <arg>...' ) + '" now to build your project.' )
                );
            }

        ,   assesGrunt: function ()
            {
                var done    = this.async()
                ,   error   = function ()
                    {
                        /* jshint laxbreak: true */

                        this.log(
                            '\n'
                        +   chalk.red( 'Hang on, it appears that "' + chalk.bold.yellow( 'grunt' ) + '" hasn\'t been installed yet!\n' )
                        +   '\n'
                        +   chalk.gray(
                                'Consider running "'
                            +   chalk.bold.yellow( chalk.cyan( '[' ) + 'sudo ' + chalk.cyan( ']' ) + 'npm install -g grunt-cli' )
                            +   '" first.\n'
                            )
                        );

                        this.preReqIssues++;

                    }.bind( this )
                ;

                this.spawnCommand( 'command', [ '-v', 'grunt' ], { stdio: 'ignore' } )
                    .on( 'exit', function ( exit )
                        {
                            if ( exit ) { error(); }
                            done();
                        }
                    )
                ;
            }

        ,   assesCompass: function ()
            {
                var done    = this.async()
                ,   minver  = '1.0.0'
                ,   version = ''
                ,   compass = chalk.bold.yellow( 'compass' )
                ,   error   = function ( nexist )
                    {
                        /* jshint laxbreak: true */

                        var first = !( this.preReqIssues );

                        this.log(
                            '\n'
                        +   chalk.red(
                                ( first ? 'Hang on,' : 'Oh, and' )
                            +   (   nexist
                                ?   ' it appears that "' + compass + '" hasn\'t been installed ' + ( first ? 'yet' : 'either' ) + '!\n'
                                :   ' your "' + compass + '" version appears outdated' + ( first ? '' : ' as well' ) + '! '
                                +   'I found only ' + chalk.underline( version ) + ' and you\'ll need ' + chalk.underline( minver + ' or newer' ) + '.\n'
                                )
                            )
                        +   '\n'
                        +   chalk.gray(
                                'Consider running "'
                            +   chalk.bold.yellow( chalk.cyan( '[' ) + 'sudo ' + chalk.cyan( ']' ) + 'gem install compass' ) + '" '
                            +   ( first ? 'first' : 'too' ) + '.\n'
                            +   '\n'
                            +   'Or see: ' + chalk.blue( 'http://thesassway.com/beginner/getting-started-with-sass-and-compass#install-sass-and-compass\n' )
                            )
                        );

                        this.preReqIssues++;

                    }.bind( this )
                ;

                this.spawnCommand( 'command', [ 'compass', '-q', '-v' ], { stdio: [ 'ignore', 'pipe', 'ignore' ] } )
                    .on( 'exit', function ( exit )
                        {
                            version = version.trim();

                            if ( exit || !( semver.satisfies( version, '>=' + minver )) ) { error( exit ); }
                            done();
                        }
                    )
                    .stdout.on( 'data', function ( chunk )
                        {
                            version += chunk;
                        }
                    )
                ;
            }

        ,   epilogue: function ()
            {
                /* jshint laxbreak: true */

                this.log(
                    '\n'
                +   ( this.preReqIssues ? 'In any case, h' : 'H' ) + 'ere\'s a quick reminder of common grunt idioms:\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt ' + chalk.cyan( '[' ) + 'default' + chalk.cyan( ']' ) + '     ' ))
                +   '- does a production, non-debugging, all-parts, minified build plus artifacts;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt debug         ' ))
                +   '- does a testing, debugging, all-parts except documentation, as-is build;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt dev           ' ))
                +   '- does a local, debugging, all-parts except documentation, as-is build; and keeps a close\n'
                +   '                          watch on filesystem changes, selectively re-triggering part builds as needed;\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt doc           ' ))
                +   '- will build just the code documentation;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt lint          ' ))
                +   '- will just lint your code;\n'

                +   chalk.bold( '  * ' + chalk.yellow( 'grunt test          ' ))
                +   '- will run your test suite;\n'

                +   '\n'
                +   chalk.bold( '  * ' + chalk.yellow( 'grunt --help        ' ))
                +   '- will show you all of the above and the kitchen sink;\n'
                );
            }
        }
    }
);

_.extend(
    AppGenerator.prototype
,   require( './../../lib/generator.js' )
);

module.exports = AppGenerator;
<|endoftext|>


<commit_before>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const path = require('path');
const _ = require('lodash');
const shelljs = require('shelljs');

module.exports = Generator.extend({
  initializing: function () {
    const done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the minimal ' + chalk.red('Node TypeScript') + ' generator!'
    ));

    this.log(
      chalk.cyan('I simply get down to business of generating, no questions asked!')
      + '\n'
      + chalk.yellow('Libraries you ask? I use npm (or optionally gulp) as task runner and jest for testing.')
      + '\n'
      + chalk.gray('Can you change these? Of course, it\'s your code. I get out of the way after scaffolding.')
    );

    done();
  },

  writing: {
    srcFiles: function () {
      this.fs.copy(
        this.templatePath('src'),
        this.destinationPath('src')
      );
    },

    testFiles: function () {
      if (this.options.mocha || this.options.gulp) {
        // 2.0.0-beta: copying the spec file needs templating due to the ts-node problem on windows
        // this.directory('test', 'test');
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec_mocha.ts'),
          this.destinationPath('test/greeter-spec.ts'),
          { isWindows: process.platform === 'win32' }
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec_mocha.ts'),
          this.destinationPath('test/index-spec.ts'),
          { isWindows: process.platform === 'win32' }
        );
      } else if (this.options.ava) {
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec_ava.ts'),
          this.destinationPath('test/greeter-spec.ts')
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec_ava.ts'),
          this.destinationPath('test/index-spec.ts')
        );
      } else {
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec.ts'),
          this.destinationPath('__tests__/greeter-spec.ts')
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec.ts'),
          this.destinationPath('__tests__/index-spec.ts')
        );
      }
    },

    vsCodeFiles: function () {
      if (this.options.gulp) {
        this.fs.copy(
          this.templatePath('_vscode/tasks_gulp.json'),
          this.destinationPath('.vscode/tasks.json')
        );
      } else {
        this.fs.copy(
          this.templatePath('_vscode/tasks.json'),
          this.destinationPath('.vscode/tasks.json')
        );
      }
      this.fs.copy(
        this.templatePath('_vscode/settings.json'),
        this.destinationPath('.vscode/settings.json')
      );
      if (!(this.options.gulp || this.options.mocha || this.options.ava)) { // copy launch.json only for default jest configuration
        this.fs.copy(
          this.templatePath('_vscode/launch.json'),
          this.destinationPath('.vscode/launch.json')
        );
      }
    },

    rootFiles: function () {
      const today = new Date();

      if (this.options.gulp) { // copy gulp files
        this.fs.copyTpl(
          this.templatePath('_package_gulp.json'),
          this.destinationPath('package.json'),
          { appname: _.kebabCase(path.basename(process.cwd())) }
        );

        this.fs.copy(
          this.templatePath('_gulpfile.js'),
          this.destinationPath('gulpfile.js'),
          { appname: _.kebabCase(path.basename(process.cwd())) }
        );

        this.fs.copy(
          this.templatePath('README_gulp.md'),
          this.destinationPath('README.md')
        );
      } else {
        if (this.options.mocha) { // copy mocha files
          this.fs.copyTpl(
            this.templatePath('_package_mocha.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis_mocha.yml'),
            this.destinationPath('.travis.yml')
          );
        } if (this.options.ava) { // copy ava files
          this.fs.copyTpl(
            this.templatePath('_package_ava.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis_ava.yml'),
            this.destinationPath('.travis.yml')
          );
          this.fs.copy(
            this.templatePath('_tsconfig.test.json'),
            this.destinationPath('tsconfig.test.json')
          );
        } else { // copy files for default jest configuration
          this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis.yml'),
            this.destinationPath('.travis.yml')
          );
        }
        // copy readme for non-gulp configurations
        this.fs.copy(
          this.templatePath('README.md'),
          this.destinationPath('README.md')
        );
      }
      // copy files for default jest configuration
      this.fs.copy(
        this.templatePath('_tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
      this.fs.copy(
        this.templatePath('_tslint.json'),
        this.destinationPath('tslint.json')
      );
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('LICENSE'),
        this.destinationPath('LICENSE'),
        { year: today.getFullYear().toPrecision(4) }
      );
    }
  },

  install: {
    npmInstall: function () {
      const generator = this;
      if (shelljs.which('yarn')) {
        generator.yarnInstall();
      } else {
        generator.npmInstall(null, { skipInstall: this.options['skip-install'] });
      }
    }
  }
});
<commit_msg>add else (#37)<commit_after>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const path = require('path');
const _ = require('lodash');
const shelljs = require('shelljs');

module.exports = Generator.extend({
  initializing: function () {
    const done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the minimal ' + chalk.red('Node TypeScript') + ' generator!'
    ));

    this.log(
      chalk.cyan('I simply get down to business of generating, no questions asked!')
      + '\n'
      + chalk.yellow('Libraries you ask? I use npm (or optionally gulp) as task runner and jest for testing.')
      + '\n'
      + chalk.gray('Can you change these? Of course, it\'s your code. I get out of the way after scaffolding.')
    );

    done();
  },

  writing: {
    srcFiles: function () {
      this.fs.copy(
        this.templatePath('src'),
        this.destinationPath('src')
      );
    },

    testFiles: function () {
      if (this.options.mocha || this.options.gulp) {
        // 2.0.0-beta: copying the spec file needs templating due to the ts-node problem on windows
        // this.directory('test', 'test');
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec_mocha.ts'),
          this.destinationPath('test/greeter-spec.ts'),
          { isWindows: process.platform === 'win32' }
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec_mocha.ts'),
          this.destinationPath('test/index-spec.ts'),
          { isWindows: process.platform === 'win32' }
        );
      } else if (this.options.ava) {
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec_ava.ts'),
          this.destinationPath('test/greeter-spec.ts')
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec_ava.ts'),
          this.destinationPath('test/index-spec.ts')
        );
      } else {
        this.fs.copyTpl(
          this.templatePath('test/greeter-spec.ts'),
          this.destinationPath('__tests__/greeter-spec.ts')
        );
        this.fs.copyTpl(
          this.templatePath('test/index-spec.ts'),
          this.destinationPath('__tests__/index-spec.ts')
        );
      }
    },

    vsCodeFiles: function () {
      if (this.options.gulp) {
        this.fs.copy(
          this.templatePath('_vscode/tasks_gulp.json'),
          this.destinationPath('.vscode/tasks.json')
        );
      } else {
        this.fs.copy(
          this.templatePath('_vscode/tasks.json'),
          this.destinationPath('.vscode/tasks.json')
        );
      }
      this.fs.copy(
        this.templatePath('_vscode/settings.json'),
        this.destinationPath('.vscode/settings.json')
      );
      if (!(this.options.gulp || this.options.mocha || this.options.ava)) { // copy launch.json only for default jest configuration
        this.fs.copy(
          this.templatePath('_vscode/launch.json'),
          this.destinationPath('.vscode/launch.json')
        );
      }
    },

    rootFiles: function () {
      const today = new Date();

      if (this.options.gulp) { // copy gulp files
        this.fs.copyTpl(
          this.templatePath('_package_gulp.json'),
          this.destinationPath('package.json'),
          { appname: _.kebabCase(path.basename(process.cwd())) }
        );

        this.fs.copy(
          this.templatePath('_gulpfile.js'),
          this.destinationPath('gulpfile.js'),
          { appname: _.kebabCase(path.basename(process.cwd())) }
        );

        this.fs.copy(
          this.templatePath('README_gulp.md'),
          this.destinationPath('README.md')
        );
      } else {
        if (this.options.mocha) { // copy mocha files
          this.fs.copyTpl(
            this.templatePath('_package_mocha.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis_mocha.yml'),
            this.destinationPath('.travis.yml')
          );
        } else if (this.options.ava) { // copy ava files
          this.fs.copyTpl(
            this.templatePath('_package_ava.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis_ava.yml'),
            this.destinationPath('.travis.yml')
          );
          this.fs.copy(
            this.templatePath('_tsconfig.test.json'),
            this.destinationPath('tsconfig.test.json')
          );
        } else { // copy files for default jest configuration
          this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            { appname: _.kebabCase(path.basename(process.cwd())) }
          );
          this.fs.copy(
            this.templatePath('travis.yml'),
            this.destinationPath('.travis.yml')
          );
        }
        // copy readme for non-gulp configurations
        this.fs.copy(
          this.templatePath('README.md'),
          this.destinationPath('README.md')
        );
      }
      // copy files for default jest configuration
      this.fs.copy(
        this.templatePath('_tsconfig.json'),
        this.destinationPath('tsconfig.json')
      );
      this.fs.copy(
        this.templatePath('_tslint.json'),
        this.destinationPath('tslint.json')
      );
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copyTpl(
        this.templatePath('LICENSE'),
        this.destinationPath('LICENSE'),
        { year: today.getFullYear().toPrecision(4) }
      );
    }
  },

  install: {
    npmInstall: function () {
      const generator = this;
      if (shelljs.which('yarn')) {
        generator.yarnInstall();
      } else {
        generator.npmInstall(null, { skipInstall: this.options['skip-install'] });
      }
    }
  }
});
<|endoftext|>