<commit_before>/* Copyright 2015 Open Ag Data Alliance
 *
 * 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.
 */

'use strict';

var generators = require('yeoman-generator');
var encrypt = require('travis-encrypt');
var is = require('is_js');
var objectAssign = require('object-assign');
var mkdirp = require('mkdirp');

var npmconf = require('npmconf');
var gitconf = require('git-config');

var testDir = 'test';
var jsonSpaces = 4;

module.exports = generators.Base.extend({
    initializing: {
        default: function() {
            this.conf = {
                main: 'index.js',
                version: '0.0.0'
            };
        },
        dir: function() {
            this.conf.libName =
                    this.destinationPath().match(/\/([^\/]+\/?)$/)[1] ||
                    this.conf.libName;
        },
        gitConfig: function() {
            var done = this.async();
            var generator = this;

            gitconf(function(err, conf) {
                if (err) {
                    generator.log(err);
                    return done();
                }

                generator.conf.name = conf.user.name || generator.conf.name;
                generator.conf.email = conf.user.email || generator.conf.email;

                done();
            });
        },
        npmConfig: function() {
            var done = this.async();
            var generator = this;

            npmconf.load(function(err, conf) {
                if (err) {
                    generator.log(err);
                    return done();
                }

                generator.conf.name = conf.get('name') || generator.conf.name;
                generator.conf.email = conf.get('email') ||
                        generator.conf.email;
                generator.conf.url = conf.get('url') || generator.conf.url;
                generator.conf.npmKey = conf.get('_auth') ||
                        generator.conf.npmKey;

                done();
            });
        },
        packageJson: function() {
            try {
                var json = this.fs.readJSON(
                    this.destinationPath('package.json'),
                    {}
                );

                this.conf.name = (json.author && json.author.name) ||
                            this.conf.name;
                if (typeof json.author === 'object') {
                    this.conf.email = json.author.email || this.conf.email;
                    this.conf.url = json.author.url || this.conf.url;
                }

                this.conf.libName =
                        (json.repository && json.repository.url &&
                            json.repository.url.match(/\/([^\/]+).git$/)[1]) ||
                        json.name || this.conf.libName;
                this.conf.version = json.version || this.conf.version;
                this.conf.main = json.main || this.conf.main;
                this.conf.libDesc = json.description || this.conf.libDesc;
            } catch (err) {
                this.log(err);
            }
        }
    },

    prompting: {
        general: function() {
            var done = this.async();
            var generator = this;

            var prompts = [
                {
                    store: false,
                    name: 'libName',
                    type: 'input',
                    default: this.conf.libName,
                    message: 'What do you want to call your lib?'
                },
                {
                    store: true,
                    name: 'libDesc',
                    type: 'input',
                    default: this.conf.libDesc,
                    message: 'Describe your library:'
                },
                {
                    store: true,
                    name: 'authorName',
                    type: 'input',
                    default: this.conf.name,
                    message: 'What is the Author\'s name?'
                },
                {
                    store: true,
                    name: 'authorEmail',
                    type: 'input',
                    default: this.conf.email,
                    message: 'What is the Author\'s email?',
                    validate: is.email
                },
                {
                    store: true,
                    name: 'authorUrl',
                    type: 'input',
                    default: this.conf.url,
                    message: 'What is the Author\'s URL (optional)?',
                    validate: function(str) {return !str || is.url(str);}
                },
                {
                    store: false,
                    name: 'copyrightYear',
                    type: 'input',
                    message: 'What year is the copyright?',
                    default: function() {
                        return generator.config.get('copyrightYear') ||
                                (new Date(Date.now())).getFullYear();
                    },
                    validate: function(str) {return is.number(+str);},
                    filter: function(year) {
                        generator.config.set('copyrightYear', year);
                        return year;
                    }
                },
                {
                    store: true,
                    name: 'gulpfile',
                    type: 'confirm',
                    default: 'true',
                    message: 'Use gulp?'
                },
                {
                    store: true,
                    name: 'browser',
                    type: 'confirm',
                    default: true,
                    message: 'Test your code in browser (browserify)?'
                },
                {
                    store: true,
                    name: 'promises',
                    type: 'confirm',
                    default: true,
                    message: 'Use promises (bluebird)?'
                }
            ];

            this.prompt(prompts, function(ans) {
                this.context = objectAssign({}, this.conf, ans);

                this.context.repoName = ans.libName;
                this.context.packageName = ans.libName
                        .replace(/^node-/, '')
                        .replace(/[.-]?js$/, '');
                this.context.varName = this.context.packageName
                        .replace(/[-_.](.)/g, function(m, p) {
                            return p.toUpperCase();
                        });

                this.context.authorJSON = JSON.stringify(
                        {
                            name: ans.authorName,
                            email: ans.authorEmail,
                            url: ans.authorUrl || undefined
                        },
                        null,
                        2
                    ).replace(/\n/g, '\n  ');
                this.context.authorStr = ans.authorName +
                    ' <' + ans.authorEmail + '>' +
                    (ans.authorUrl && (' (' + ans.authorUrl + ')'));

                done();
            }.bind(this));
        },
        genNpmKey: function() {
            var done = this.async();
            var generator = this;

            this.prompt([
                    {
                        store: false,
                        name: 'genNpmKey',
                        type: 'confirm',
                        default: false,
                        message: 'Regenerate Travis NPM API key?',
                        when: function() {
                            return !!generator.config.get('travisNpmKey');
                        },
                    },
                    {
                        store: false,
                        name: 'npmApiKey',
                        type: 'input',
                        default: generator.conf.npmKey,
                        message: 'Enter NPM API key, or username:password.',
                        when: function(ans) {
                            return ans.genNpmKey ||
                                !generator.config.get('travisNpmKey');
                        },
                        filter: function(str) {
                            return str.indexOf(':') === -1 ? str :
                                    (new Buffer(str)).toString('base64');
                        }
                    }
                ],
                function(ans) {
                    if (!ans.npmApiKey) {return done();}
                    encrypt(
                        'OADA/' + generator.context.repoName,
                        ans.npmApiKey,
                        undefined, undefined,
                        function(err, blob) {
                            if (err) {
                                generator.log(err);
                            } else {
                                generator.config.set('travisNpmKey', blob);
                            }

                            done();
                        }
                    );
                }.bind(this)
            );
        }
    },

    configuring: {
        license: function() {
            this.fs.copy(
                this.templatePath('_LICENSE'),
                this.destinationPath('LICENSE')
            );
            this.fs.copyTpl(
                this.templatePath('_AUTHORS'),
                this.destinationPath('AUTHORS'),
                this.context
            );
            this.fs.copyTpl(
                this.templatePath('_NOTICE'),
                this.destinationPath('NOTICE'),
                this.context
            );
        },
        readme: function() {
            this.fs.copyTpl(
                this.templatePath('_README.md'),
                this.destinationPath('README.md'),
                this.context
            );
        },
        editorconfig: function() {
            this.fs.copy(
                this.templatePath('editorconfig'),
                this.destinationPath('.editorconfig')
            );
        },
        ack: function() {
            this.fs.copy(
                this.templatePath('ackrc'),
                this.destinationPath('.ackrc')
            );
        },
        jshint: function() {
            this.fs.copy(
                this.templatePath('jshintrc'),
                this.destinationPath('.jshintrc')
            );
            this.fs.copy(
                this.templatePath('jshintignore'),
                this.destinationPath('.jshintignore')
            );
        },
        jscs: function() {
            this.fs.copy(
                this.templatePath('jscsrc'),
                this.destinationPath('.jscsrc')
            );
        },
        gulp: function() {
            if (!this.context.gulpfile) {
                return;
            }

            this.fs.copyTpl(
                this.templatePath('_gulpfile.js'),
                this.destinationPath('gulpfile.js'),
                this.context
            );
        },
        karma: function() {
            if (!this.context.browser) {
                return;
            }

            this.fs.copyTpl(
                this.templatePath('_karma.conf.js'),
                this.destinationPath('karma.conf.js'),
                this.context
            );
        },
        mocha: function() {
            this.fs.copy(
                this.templatePath('test/mocha.opts'),
                this.destinationPath(testDir + '/mocha.opts')
            );
            this.fs.copyTpl(
                this.templatePath('test/setup.js'),
                this.destinationPath('test/setup.js'),
                this.context
            );
            this.fs.writeJSON(
                this.destinationPath(testDir + '/.jshintrc'),
                objectAssign(
                    this.fs.readJSON(this.templatePath('jshintrc')),
                    this.fs.readJSON(this.templatePath('test/jshintrc-mocha'))
                ),
                null,
                jsonSpaces
            );
        },
        istanbul: function() {
            this.fs.copy(
                this.templatePath('istanbul.yml'),
                this.destinationPath('.istanbul.yml')
            );
        },
        npm: function() {
            this.fs.copyTpl(
                this.templatePath('_package.json'),
                this.destinationPath('package.json'),
                this.context
            );
        },
        git: function() {
            this.fs.copy(
                this.templatePath('gitignore'),
                this.destinationPath('.gitignore')
            );
        },
        travis: function() {
            this.context.travisNpmKey = this.config.get('travisNpmKey');
            this.fs.copyTpl(
                this.templatePath('travis.yml'),
                this.destinationPath('.travis.yml'),
                this.context
            );
        }
    },

    writing: {
        main: function() {
            this.fs.copyTpl(
                this.templatePath('index.js'),
                this.destinationPath(this.context.main),
                this.context
            );
        },
        test: function() {
            this.fs.copyTpl(
                this.templatePath('test/test.js'),
                this.destinationPath(
                    testDir + '/' + this.context.packageName + '.test.js'),
                this.context
            );
        }
    },

    install: {
        promises: function() {
            if (!this.context.promises) {
                return;
            }

            this.npmInstall(['bluebird'], {save: true});
        },
        istanbul: function() {
            this.npmInstall(['istanbul'], {saveDev: true});
        },
        mocha: function() {
            this.npmInstall(['mocha'], {saveDev: true});
        },
        chai: function() {
            this.npmInstall(['chai'], {saveDev: true});

            if (this.context.promises) {
                this.npmInstall(['chai-as-promised'], {saveDev: true});
            }
        },

        jshint: function() {
            this.npmInstall(['jshint', 'jshint-stylish'], {saveDev: true});
        },
        jscs: function() {
            this.npmInstall(['jscs'], {saveDev: true});
        },
        precommit: function() {
            var done = this.async();
            mkdirp(this.destinationPath('.git/hooks'), function(err) {
                if (err) { this.log(err); }
                this.npmInstall(['pre-commit'], {saveDev: true});
                done();
            }.bind(this));
        },
        gulp: function() {
            if (!this.context.gulpfile) {
                return;
            }

            this.npmInstall(['gulp', 'gulp-jshint', 'gulp-jscs'],
                    {saveDev: true});
        },
        karma: function() {
            if (!this.context.browser) {
                return;
            }

            this.npmInstall([
                'karma',
                'yargs',
                'karma-browserify',
                'browserify-istanbul',
                'brfs',
                'karma-coverage@0.2.6',
                'karma-mocha',
                'karma-mocha-reporter',
                'karma-phantomjs-launcher',
                'karma-phantomjs-shim'
                ], {
                    saveDev: true
                });
        }
    }
});
<commit_msg>Don't overwrite real project files<commit_after>/* Copyright 2015 Open Ag Data Alliance
 *
 * 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.
 */

'use strict';

var generators = require('yeoman-generator');
var encrypt = require('travis-encrypt');
var is = require('is_js');
var objectAssign = require('object-assign');
var mkdirp = require('mkdirp');

var npmconf = require('npmconf');
var gitconf = require('git-config');

var testDir = 'test';
var jsonSpaces = 4;

module.exports = generators.Base.extend({
    initializing: {
        default: function() {
            this.conf = {
                main: 'index.js',
                version: '0.0.0'
            };
        },
        dir: function() {
            this.conf.libName =
                    this.destinationPath().match(/\/([^\/]+\/?)$/)[1] ||
                    this.conf.libName;
        },
        gitConfig: function() {
            var done = this.async();
            var generator = this;

            gitconf(function(err, conf) {
                if (err) {
                    generator.log(err);
                    return done();
                }

                generator.conf.name = conf.user.name || generator.conf.name;
                generator.conf.email = conf.user.email || generator.conf.email;

                done();
            });
        },
        npmConfig: function() {
            var done = this.async();
            var generator = this;

            npmconf.load(function(err, conf) {
                if (err) {
                    generator.log(err);
                    return done();
                }

                generator.conf.name = conf.get('name') || generator.conf.name;
                generator.conf.email = conf.get('email') ||
                        generator.conf.email;
                generator.conf.url = conf.get('url') || generator.conf.url;
                generator.conf.npmKey = conf.get('_auth') ||
                        generator.conf.npmKey;

                done();
            });
        },
        packageJson: function() {
            try {
                var json = this.fs.readJSON(
                    this.destinationPath('package.json'),
                    {}
                );

                this.conf.name = (json.author && json.author.name) ||
                            this.conf.name;
                if (typeof json.author === 'object') {
                    this.conf.email = json.author.email || this.conf.email;
                    this.conf.url = json.author.url || this.conf.url;
                }

                this.conf.libName =
                        (json.repository && json.repository.url &&
                            json.repository.url.match(/\/([^\/]+).git$/)[1]) ||
                        json.name || this.conf.libName;
                this.conf.version = json.version || this.conf.version;
                this.conf.main = json.main || this.conf.main;
                this.conf.libDesc = json.description || this.conf.libDesc;
            } catch (err) {
                this.log(err);
            }
        }
    },

    prompting: {
        general: function() {
            var done = this.async();
            var generator = this;

            var prompts = [
                {
                    store: false,
                    name: 'libName',
                    type: 'input',
                    default: this.conf.libName,
                    message: 'What do you want to call your lib?'
                },
                {
                    store: true,
                    name: 'libDesc',
                    type: 'input',
                    default: this.conf.libDesc,
                    message: 'Describe your library:'
                },
                {
                    store: true,
                    name: 'authorName',
                    type: 'input',
                    default: this.conf.name,
                    message: 'What is the Author\'s name?'
                },
                {
                    store: true,
                    name: 'authorEmail',
                    type: 'input',
                    default: this.conf.email,
                    message: 'What is the Author\'s email?',
                    validate: is.email
                },
                {
                    store: true,
                    name: 'authorUrl',
                    type: 'input',
                    default: this.conf.url,
                    message: 'What is the Author\'s URL (optional)?',
                    validate: function(str) {return !str || is.url(str);}
                },
                {
                    store: false,
                    name: 'copyrightYear',
                    type: 'input',
                    message: 'What year is the copyright?',
                    default: function() {
                        return generator.config.get('copyrightYear') ||
                                (new Date(Date.now())).getFullYear();
                    },
                    validate: function(str) {return is.number(+str);},
                    filter: function(year) {
                        generator.config.set('copyrightYear', year);
                        return year;
                    }
                },
                {
                    store: true,
                    name: 'gulpfile',
                    type: 'confirm',
                    default: 'true',
                    message: 'Use gulp?'
                },
                {
                    store: true,
                    name: 'browser',
                    type: 'confirm',
                    default: true,
                    message: 'Test your code in browser (browserify)?'
                },
                {
                    store: true,
                    name: 'promises',
                    type: 'confirm',
                    default: true,
                    message: 'Use promises (bluebird)?'
                }
            ];

            this.prompt(prompts, function(ans) {
                this.context = objectAssign({}, this.conf, ans);

                this.context.repoName = ans.libName;
                this.context.packageName = ans.libName
                        .replace(/^node-/, '')
                        .replace(/[.-]?js$/, '');
                this.context.varName = this.context.packageName
                        .replace(/[-_.](.)/g, function(m, p) {
                            return p.toUpperCase();
                        });

                this.context.authorJSON = JSON.stringify(
                        {
                            name: ans.authorName,
                            email: ans.authorEmail,
                            url: ans.authorUrl || undefined
                        },
                        null,
                        2
                    ).replace(/\n/g, '\n  ');
                this.context.authorStr = ans.authorName +
                    ' <' + ans.authorEmail + '>' +
                    (ans.authorUrl && (' (' + ans.authorUrl + ')'));

                done();
            }.bind(this));
        },
        genNpmKey: function() {
            var done = this.async();
            var generator = this;

            this.prompt([
                    {
                        store: false,
                        name: 'genNpmKey',
                        type: 'confirm',
                        default: false,
                        message: 'Regenerate Travis NPM API key?',
                        when: function() {
                            return !!generator.config.get('travisNpmKey');
                        },
                    },
                    {
                        store: false,
                        name: 'npmApiKey',
                        type: 'input',
                        default: generator.conf.npmKey,
                        message: 'Enter NPM API key, or username:password.',
                        when: function(ans) {
                            return ans.genNpmKey ||
                                !generator.config.get('travisNpmKey');
                        },
                        filter: function(str) {
                            return str.indexOf(':') === -1 ? str :
                                    (new Buffer(str)).toString('base64');
                        }
                    }
                ],
                function(ans) {
                    if (!ans.npmApiKey) {return done();}
                    encrypt(
                        'OADA/' + generator.context.repoName,
                        ans.npmApiKey,
                        undefined, undefined,
                        function(err, blob) {
                            if (err) {
                                generator.log(err);
                            } else {
                                generator.config.set('travisNpmKey', blob);
                            }

                            done();
                        }
                    );
                }.bind(this)
            );
        }
    },

    configuring: {
        license: function() {
            this.fs.copy(
                this.templatePath('_LICENSE'),
                this.destinationPath('LICENSE')
            );
            this.fs.copyTpl(
                this.templatePath('_NOTICE'),
                this.destinationPath('NOTICE'),
                this.context
            );
        },
        editorconfig: function() {
            this.fs.copy(
                this.templatePath('editorconfig'),
                this.destinationPath('.editorconfig')
            );
        },
        ack: function() {
            this.fs.copy(
                this.templatePath('ackrc'),
                this.destinationPath('.ackrc')
            );
        },
        jshint: function() {
            this.fs.copy(
                this.templatePath('jshintrc'),
                this.destinationPath('.jshintrc')
            );
            this.fs.copy(
                this.templatePath('jshintignore'),
                this.destinationPath('.jshintignore')
            );
        },
        jscs: function() {
            this.fs.copy(
                this.templatePath('jscsrc'),
                this.destinationPath('.jscsrc')
            );
        },
        gulp: function() {
            if (!this.context.gulpfile) {
                return;
            }

            this.fs.copyTpl(
                this.templatePath('_gulpfile.js'),
                this.destinationPath('gulpfile.js'),
                this.context
            );
        },
        karma: function() {
            if (!this.context.browser) {
                return;
            }

            this.fs.copyTpl(
                this.templatePath('_karma.conf.js'),
                this.destinationPath('karma.conf.js'),
                this.context
            );
        },
        mocha: function() {
            this.fs.copy(
                this.templatePath('test/mocha.opts'),
                this.destinationPath(testDir + '/mocha.opts')
            );
            this.fs.copyTpl(
                this.templatePath('test/setup.js'),
                this.destinationPath('test/setup.js'),
                this.context
            );
            this.fs.writeJSON(
                this.destinationPath(testDir + '/.jshintrc'),
                objectAssign(
                    this.fs.readJSON(this.templatePath('jshintrc')),
                    this.fs.readJSON(this.templatePath('test/jshintrc-mocha'))
                ),
                null,
                jsonSpaces
            );
        },
        istanbul: function() {
            this.fs.copy(
                this.templatePath('istanbul.yml'),
                this.destinationPath('.istanbul.yml')
            );
        },
        npm: function() {
            this.fs.copyTpl(
                this.templatePath('_package.json'),
                this.destinationPath('package.json'),
                this.context
            );
        },
        git: function() {
            this.fs.copy(
                this.templatePath('gitignore'),
                this.destinationPath('.gitignore')
            );
        },
        travis: function() {
            this.context.travisNpmKey = this.config.get('travisNpmKey');
            this.fs.copyTpl(
                this.templatePath('travis.yml'),
                this.destinationPath('.travis.yml'),
                this.context
            );
        }
    },

    writing: {
        readme: function() {
            var dest = this.destinationPath('README.md');
            if (this.fs.exists(dest)) { return; }

            this.fs.copyTpl(
                this.templatePath('_README.md'),
                dest,
                this.context
            );
        },
        authors: function() {
            var dest = this.destinationPath('AUTHORS');
            if (this.fs.exists(dest)) { return; }

            this.fs.copyTpl(
                this.templatePath('_AUTHORS'),
                dest,
                this.context
            );
        },
        main: function() {
            var dest = this.destinationPath(this.context.main);
            if (this.fs.exists(dest)) { return; }

            this.fs.copyTpl(
                this.templatePath('index.js'),
                dest,
                this.context
            );
        },
        test: function() {
            var dest = this.destinationPath(
                testDir + '/' + this.context.packageName + '.test.js'
            );
            if (this.fs.exists(dest)) { return; }

            this.fs.copyTpl(
                this.templatePath('test/test.js'),
                dest,
                this.context
            );
        }
    },

    install: {
        promises: function() {
            if (!this.context.promises) {
                return;
            }

            this.npmInstall(['bluebird'], {save: true});
        },
        istanbul: function() {
            this.npmInstall(['istanbul'], {saveDev: true});
        },
        mocha: function() {
            this.npmInstall(['mocha'], {saveDev: true});
        },
        chai: function() {
            this.npmInstall(['chai'], {saveDev: true});

            if (this.context.promises) {
                this.npmInstall(['chai-as-promised'], {saveDev: true});
            }
        },

        jshint: function() {
            this.npmInstall(['jshint', 'jshint-stylish'], {saveDev: true});
        },
        jscs: function() {
            this.npmInstall(['jscs'], {saveDev: true});
        },
        precommit: function() {
            var done = this.async();
            mkdirp(this.destinationPath('.git/hooks'), function(err) {
                if (err) { this.log(err); }
                this.npmInstall(['pre-commit'], {saveDev: true});
                done();
            }.bind(this));
        },
        gulp: function() {
            if (!this.context.gulpfile) {
                return;
            }

            this.npmInstall(['gulp', 'gulp-jshint', 'gulp-jscs'],
                    {saveDev: true});
        },
        karma: function() {
            if (!this.context.browser) {
                return;
            }

            this.npmInstall([
                'karma',
                'yargs',
                'karma-browserify',
                'browserify-istanbul',
                'brfs',
                'karma-coverage@0.2.6',
                'karma-mocha',
                'karma-mocha-reporter',
                'karma-phantomjs-launcher',
                'karma-phantomjs-shim'
                ], {
                    saveDev: true
                });
        }
    }
});
<|endoftext|>


<commit_before>(function() {

    'use strict';

    var util = require('util'),
        path = require('path'),
        slug = require('slug'),
        fs = require('fs'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    var ScaffoldGenerator = module.exports = function ScaffoldGenerator(args, options) {
        var _this = this;

        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function() {
            this.installDependencies({
                skipInstall: options['skipInstall'],
                callback: function() {
                    var command = _this.spawnCommand('npm', ['install', 'glob']);

                    command.on('exit', function() {
                        _this.log(chalk.cyan(' \n \n All done and no errors! Enjoy! \n \n'));
                    });
                }
            });
        });

        this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
    };

    util.inherits(ScaffoldGenerator, yeoman.generators.Base);

    ScaffoldGenerator.prototype.init = function init() {
        var cb = this.async();

        this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
        this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
        this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
        this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_|'));

        this.log('\n');

        this.log(chalk.cyan('\t \t [ Welcome to Scaffold Generator ] \n \n'));
        this.log(chalk.green('I will guide you to generate your best workflow. Come with me... \n \n'));

        cb();
    };

    ScaffoldGenerator.prototype.askFor = function askFor() {
        var cb = this.async(),
            _this = this,
            attempts = {
                name: 0,
                description: 0,
                members: 0
            },
            prompts = [{
                name: 'projectName',
                message: 'What is the name of your project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name === 0) {
                            attempts.name = 1;
                            done('Hey dude! You forgot to enter the project name!');
                        } else if (attempts.name === 1) {
                            attempts.name = 2;

                            done('Come on. Just write the name of the project.');
                        } else if (attempts.name === 2) {
                            attempts.name = 3;

                            done('Alright. No problem. I\'ll wait here.');
                        } else if (attempts.name === 3) {
                            attempts.name = 4;

                            done('Come on buddy! Write that name. NOW!');
                        } else {
                            done('Ok! :(');
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectDescription',
                message: 'What is the description?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name > 0) {
                            done('You also forgot the description.');
                        } else {
                            if (attempts.description === 0) {
                                attempts.description = 1;

                                done('You forgot the description. Write here.');
                            } else if (attempts.description === 1) {
                                done('You forgot the description again! Just write.');
                            }
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectMember',
                message: 'What are people going to work on this project? (Separated by commas)',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name > 0 && attempts.description > 0) {
                            done('Forgot again? :/ Who will work with you on this? Write separating the names with commas.');
                        } else {
                            if (attempts.members === 0) {
                                attempts.members = 1;

                                done('Hey man. Who will work with you on this? Write separating the names with commas.');
                            } else if (attempts.members === 1) {
                                done('Type the name of who will work with you, separated by commas.');
                            }
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                type: 'list',
                name: 'projectType',
                message: 'What kind of project?',
                choices: ['Mobile Only', 'Web Only', 'Responsive'],
                default: 0
            }, {
                type: 'confirm',
                name: 'jquery',
                message: 'Want to include jQuery?',
                default: 0
            }];

        this.prompt(prompts, function(props) {
            for(var item in props) {
                this[item] = props[item];
            }

            this.log(chalk.red(' \n \n Good! Now I will download everything you need. Time to take a coffee! \n \n'));

            cb();
        }.bind(this));
    };

    ScaffoldGenerator.prototype.getScaffoldCore = function getScaffoldCore() {
        var cb = this.async();

        this.log(chalk.green('\n \n Downloading core of scaffold'));
        this.tarball('https://github.com/marcosmoura/scaffold/archive/v2.zip', '.', cb);
    };

    ScaffoldGenerator.prototype.processPackage = function processPackage() {
        var cb = this.async(),
            pkgPath = path.join(this.env.cwd, 'package.json'),
            pkg = JSON.parse(this.readFileAsString(pkgPath));

        pkg.projectName = this.projectName;
        pkg.name = slug(this.projectName.toLowerCase());
        pkg.description = this.projectDescription;
        pkg.developers = this.projectMember;

        var dev = this.projectMember.split(','),
            devList = [];

        for(var member in dev) {
            devList.push({
                'name': dev[member].trim()
            });
        }

        pkg.author = devList;

        fs.unlink(pkgPath);

        this.write(pkgPath, JSON.stringify(pkg, null, 2));

        cb();
    };

    ScaffoldGenerator.prototype.processGruntFile = function processGruntFile() {
        var cb = this.async();

        if(this.projectType === 'Mobile Only') {
            this.log(chalk.green('\n \n Downloading mobile version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        } else if(this.projectType === 'Web Only') {
            this.log(chalk.green('\n \n Downloading web version'));
            this.tarball('https://github.com/marcosmoura/scaffold-web/archive/master.zip', 'dev/', cb);
        } else if(this.projectType === 'Responsive') {
            this.log(chalk.green('\n \n Downloading responsive version'));
            this.tarball('https://github.com/marcosmoura/scaffold-responsive/archive/master.zip', 'dev/', cb);
        }
    };

    ScaffoldGenerator.prototype.garbageRemoval = function garbageRemoval() {
        var cb = this.async(),
            devPath = path.join(this.env.cwd, 'dev');

        this.log(chalk.red('\n \n Removing garbage and temporary files'));

        fs.unlink(path.join(devPath, 'LICENSE'));
        fs.unlink(path.join(devPath, 'README.md'));

        this.log(chalk.green('\n \n Now I will install the dependencies. This may take a while. Time to go to the bathroom! \n \n '));

        cb();
    };

})();
<commit_msg>Remove some dependencies based on user options<commit_after>(function() {

    'use strict';

    var util = require('util'),
        path = require('path'),
        slug = require('slug'),
        fs = require('fs'),
        yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    var ScaffoldGenerator = module.exports = function ScaffoldGenerator(args, options) {
        var _this = this;

        yeoman.generators.Base.apply(this, arguments);

        this.on('end', function() {
            this.installDependencies({
                skipInstall: options['skipInstall'],
                callback: function() {
                    var command = _this.spawnCommand('npm', ['install', 'glob']);

                    command.on('exit', function() {
                        _this.log(chalk.cyan(' \n \n All done and no errors! Enjoy! \n \n'));
                    });
                }
            });
        });

        this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
    };

    util.inherits(ScaffoldGenerator, yeoman.generators.Base);

    ScaffoldGenerator.prototype.init = function init() {
        var cb = this.async();

        this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
        this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
        this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
        this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_|'));

        this.log('\n');

        this.log(chalk.cyan('\t \t [ Welcome to Scaffold Generator ] \n \n'));
        this.log(chalk.green('I will guide you to generate your best workflow. Come with me... \n \n'));

        cb();
    };

    ScaffoldGenerator.prototype.askFor = function askFor() {
        var cb = this.async(),
            _this = this,
            attempts = {
                name: 0,
                description: 0,
                members: 0
            },
            prompts = [{
                name: 'projectName',
                message: 'What is the name of your project?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name === 0) {
                            attempts.name = 1;
                            done('Hey dude! You forgot to enter the project name!');
                        } else if (attempts.name === 1) {
                            attempts.name = 2;

                            done('Come on. Just write the name of the project.');
                        } else if (attempts.name === 2) {
                            attempts.name = 3;

                            done('Alright. No problem. I\'ll wait here.');
                        } else if (attempts.name === 3) {
                            attempts.name = 4;

                            done('Come on buddy! Write that name. NOW!');
                        } else {
                            done('Ok! :(');
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectDescription',
                message: 'What is the description?',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name > 0) {
                            done('You also forgot the description.');
                        } else {
                            if (attempts.description === 0) {
                                attempts.description = 1;

                                done('You forgot the description. Write here.');
                            } else if (attempts.description === 1) {
                                done('You forgot the description again! Just write.');
                            }
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                name: 'projectMember',
                message: 'What are people going to work on this project? (Separated by commas)',
                validate: function(input) {
                    var done = this.async();

                    if (input.trim() === '') {
                        if (attempts.name > 0 && attempts.description > 0) {
                            done('Forgot again? :/ Who will work with you on this? Write separating the names with commas.');
                        } else {
                            if (attempts.members === 0) {
                                attempts.members = 1;

                                done('Hey man. Who will work with you on this? Write separating the names with commas.');
                            } else if (attempts.members === 1) {
                                done('Type the name of who will work with you, separated by commas.');
                            }
                        }

                        return;
                    }

                    done(true);
                }
            }, {
                type: 'list',
                name: 'projectType',
                message: 'What kind of project?',
                choices: ['Mobile Only', 'Web Only', 'Responsive'],
                default: 0
            }, {
                type: 'confirm',
                name: 'jquery',
                message: 'Want to include jQuery?',
                default: 0
            }];

        this.prompt(prompts, function(props) {
            for(var item in props) {
                this[item] = props[item];
            }

            this.log(chalk.red(' \n \n Good! Now I will download everything you need. Time to take a coffee! \n \n'));

            cb();
        }.bind(this));
    };

    ScaffoldGenerator.prototype.getScaffoldCore = function getScaffoldCore() {
        var cb = this.async();

        this.log(chalk.green('\n \n Downloading core of scaffold'));
        this.tarball('https://github.com/marcosmoura/scaffold/archive/v2.zip', '.', cb);
    };

    ScaffoldGenerator.prototype.processPackage = function processPackage() {
        var cb = this.async(),
            pkgPath = path.join(this.env.cwd, 'package.json'),
            pkg = JSON.parse(this.readFileAsString(pkgPath));

        pkg.projectName = this.projectName;
        pkg.name = slug(this.projectName.toLowerCase());
        pkg.description = this.projectDescription;
        pkg.developers = this.projectMember;

        var dev = this.projectMember.split(','),
            devList = [];

        for(var member in dev) {
            devList.push({
                'name': dev[member].trim()
            });
        }

        pkg.author = devList;

        fs.unlink(pkgPath);

        this.write(pkgPath, JSON.stringify(pkg, null, 2));

        cb();
    };

    ScaffoldGenerator.prototype.processBower = function processBower() {
        var cb = this.async(),
            bowerJson = path.join(this.env.cwd, 'bower.json'),
            bower = JSON.parse(this.readFileAsString(bowerJson));

        if (this.projectType === 'Web Only') {
            delete bower.dependencies.fastclick;
        }

        if (!this.jquery) {
            delete bower.dependencies.jquery;
        }

        fs.unlink(bowerJson);

        this.write(bowerJson, JSON.stringify(bower, null, 2));

        cb();
    };

    ScaffoldGenerator.prototype.getScaffoldVersion = function getScaffoldVersion() {
        var cb = this.async();

        if(this.projectType === 'Mobile Only') {
            this.log(chalk.green('\n \n Downloading mobile version'));
            this.tarball('https://github.com/marcosmoura/scaffold-mobile/archive/master.zip', 'dev/', cb);
        } else if(this.projectType === 'Web Only') {
            this.log(chalk.green('\n \n Downloading web version'));
            this.tarball('https://github.com/marcosmoura/scaffold-web/archive/master.zip', 'dev/', cb);
        } else if(this.projectType === 'Responsive') {
            this.log(chalk.green('\n \n Downloading responsive version'));
            this.tarball('https://github.com/marcosmoura/scaffold-responsive/archive/master.zip', 'dev/', cb);
        }
    };

    ScaffoldGenerator.prototype.garbageRemoval = function garbageRemoval() {
        var cb = this.async(),
            devPath = path.join(this.env.cwd, 'dev');

        this.log(chalk.red('\n \n Removing garbage and temporary files'));

        fs.unlink(path.join(devPath, 'LICENSE'));
        fs.unlink(path.join(devPath, 'README.md'));

        this.log(chalk.green('\n \n Now I will install the dependencies. This may take a while. Time to go to the bathroom! \n \n '));

        cb();
    };

})();
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var childProcess = require('child_process');
var spawn = childProcess.spawn;
var exec = childProcess.exec;
var yeoman = require('yeoman-generator');
var DRUPAL = 'Drupal';
var WORDPRESS = 'Wordpress';
var fs = require('fs');
var STATIC = 'Static';
var themeFolder;
var promptData = {
  templateType: null,
  publisherName: null,
  publicationName: null
};
var appDir;
var _ = require('lodash');

var writeBuildXML = function writeBuildXML( template ) {
  fs.writeFile('build.xml', template({
    publisher: promptData.publisherName,
    publication: promptData.publicationName
  }), function (err) {
    if ( err !== null ) {
      console.log( 'Write file error: ' + err );
    }
    console.log('build.xml created');
  });
};

var generateBuildXML = function generateBuildXML() {

  var templateType = promptData.templateType,
    buildTemplateFile;

  if (templateType === DRUPAL) {
    buildTemplateFile = 'buildutils/template-build-drupal_and_static.xml';
  } else if (templateType === WORDPRESS) {
    buildTemplateFile = 'buildutils/template-build-wordpress_and_static.xml';
  } else if (templateType === STATIC) {
    buildTemplateFile = 'buildutils/template-build-static.xml';
  }

  fs.readFile(buildTemplateFile, {
    encoding: 'utf8',
  }, function(err, data) {
    if (err !== null) {
      console.log( 'Read file error: ' + err );
    } else {

      var buildTemplate = _.template( data );

      writeBuildXML( buildTemplate );

    }
  });

};

var addGitSubmodules = function addGitSubmodules() {
  exec('git submodule add git@bitbucket.org:kaldorgroup/kaldor-build-utils.git buildutils', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    if (stderr) {
      console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('exec error: ' + error);
    } else {
      generateBuildXML();
    }
  });
};

var initGit = function initGit() {
  var init = spawn('git', ['init']);

  init.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  init.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  init.on('close', function () {
    addGitSubmodules();
  });
};

var PugpigGenerator = module.exports = function PugpigGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    process.chdir(themeFolder);
    this.installDependencies({ skipInstall: options['skip-install'] });
    process.chdir('../../');
    initGit.call( this );
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));

};

util.inherits(PugpigGenerator, yeoman.generators.Base);

PugpigGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.pugpig);

  var prompts = [{
    type: 'list',
    name: 'templateType',
    choices: ['Static', 'Drupal', 'Wordpress'],
    message: 'What type of Pugpig template would you like to create?'
  },
  {
    type: 'input',
    name: 'publisherName',
    message: 'What is the name of the publisher?'
  },
  {
    type: 'input',
    name: 'publicationName',
    message: 'What is the name of the publication?'
  }];

  this.prompt(prompts, function (props) {

    promptData.templateType = props.templateType;
    promptData.publisherName = props.publisherName;
    promptData.publicationName = props.publicationName;

    cb();
  }.bind(this));
};

PugpigGenerator.prototype.appStructure = function appStructure() {

  var projectName = promptData.publisherName + '-' + promptData.publicationName + '-Server',
    projectData = {
      projectName: projectName
    },
    templateType = promptData.templateType,
    modulesFolder;

  themeFolder = 'themes/' + promptData.publicationName.toLowerCase() + '/';
  appDir = themeFolder + 'app/';

  this.mkdir('themes');
  this.mkdir(themeFolder);

  if (templateType === DRUPAL) {
    modulesFolder = 'modules';
  } else if (templateType === WORDPRESS) {
    modulesFolder = 'plugins';
  }

  if ( modulesFolder ) {
    this.mkdir(modulesFolder);
    this.mkdir(modulesFolder + '/pugpig-' + promptData.publicationName.toLowerCase());
  }

  if (templateType === DRUPAL) {
    this.template('drupal/theme.info', appDir + promptData.publicationName.toLowerCase() + '.info', {
      publication: promptData.publicationName
    });
    this.copy('drupal/template.php', appDir + 'template.php');
  } else if (templateType === WORDPRESS) {
    this.template('wordpress/plugins.php', modulesFolder + '/pugpig-' + promptData.publicationName.toLowerCase() + '/pugpig_' + promptData.publicationName.toLowerCase() + '.php', {
      publicationCapitalized: promptData.publicationName,
      publicationLowercase: promptData.publicationName.toLowerCase()
    });
    this.template('wordpress/style.css', appDir + 'style.css', {
      publicationName: promptData.publicationName
    });
  }

  this.mkdir(appDir);

  this.directory('static', appDir + 'static');
  this.directory('styles', appDir + 'styles');

  this.mkdir(appDir + 'static/images');
  this.mkdir(appDir + 'styles/components');

  this.template('index.html', appDir + 'static/index.html', projectData);

  this.template('Gruntfile.js', themeFolder + 'Gruntfile.js', {
    publication: promptData.publicationName.toLowerCase(),
    pkg: this.pkg,
    templateType: promptData.templateType
  });

  this.template('_package.json', themeFolder + 'package.json', projectData);

  this.template('_bower.json', themeFolder + 'bower.json', projectData);
  this.copy('bowerrc', themeFolder + '.bowerrc');

};

PugpigGenerator.prototype.createImagesDir = function createImagesDir() {
  this.mkdir(appDir + 'images');
};

PugpigGenerator.prototype.createScriptsDir = function createScriptsDir() {
  this.mkdir(appDir + 'scripts');
};

PugpigGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', themeFolder + '.editorconfig');
  this.copy('jshintrc', themeFolder + '.jshintrc');
};

PugpigGenerator.prototype.gitFiles = function gitFiles() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitmodules', '.gitmodules');
};

PugpigGenerator.prototype.compassFiles = function compassFiles() {
  this.copy('compass.rb', themeFolder + '.compass.rb');
};
<commit_msg>Be consistent with 'dir' variables containing or not containing the trailing slash<commit_after>'use strict';
var util = require('util');
var path = require('path');
var childProcess = require('child_process');
var spawn = childProcess.spawn;
var exec = childProcess.exec;
var yeoman = require('yeoman-generator');
var DRUPAL = 'Drupal';
var WORDPRESS = 'Wordpress';
var fs = require('fs');
var STATIC = 'Static';
var themeFolder;
var promptData = {
  templateType: null,
  publisherName: null,
  publicationName: null
};
var appDir;
var _ = require('lodash');

var writeBuildXML = function writeBuildXML( template ) {
  fs.writeFile('build.xml', template({
    publisher: promptData.publisherName,
    publication: promptData.publicationName
  }), function (err) {
    if ( err !== null ) {
      console.log( 'Write file error: ' + err );
    }
    console.log('build.xml created');
  });
};

var generateBuildXML = function generateBuildXML() {

  var templateType = promptData.templateType,
    buildTemplateFile;

  if (templateType === DRUPAL) {
    buildTemplateFile = 'buildutils/template-build-drupal_and_static.xml';
  } else if (templateType === WORDPRESS) {
    buildTemplateFile = 'buildutils/template-build-wordpress_and_static.xml';
  } else if (templateType === STATIC) {
    buildTemplateFile = 'buildutils/template-build-static.xml';
  }

  fs.readFile(buildTemplateFile, {
    encoding: 'utf8',
  }, function(err, data) {
    if (err !== null) {
      console.log( 'Read file error: ' + err );
    } else {

      var buildTemplate = _.template( data );

      writeBuildXML( buildTemplate );

    }
  });

};

var addGitSubmodules = function addGitSubmodules() {
  exec('git submodule add git@bitbucket.org:kaldorgroup/kaldor-build-utils.git buildutils', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    if (stderr) {
      console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('exec error: ' + error);
    } else {
      generateBuildXML();
    }
  });
};

var initGit = function initGit() {
  var init = spawn('git', ['init']);

  init.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  init.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  init.on('close', function () {
    addGitSubmodules();
  });
};

var PugpigGenerator = module.exports = function PugpigGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    process.chdir(themeFolder);
    this.installDependencies({ skipInstall: options['skip-install'] });
    process.chdir('../../');
    initGit.call( this );
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));

};

util.inherits(PugpigGenerator, yeoman.generators.Base);

PugpigGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.pugpig);

  var prompts = [{
    type: 'list',
    name: 'templateType',
    choices: ['Static', 'Drupal', 'Wordpress'],
    message: 'What type of Pugpig template would you like to create?'
  },
  {
    type: 'input',
    name: 'publisherName',
    message: 'What is the name of the publisher?'
  },
  {
    type: 'input',
    name: 'publicationName',
    message: 'What is the name of the publication?'
  }];

  this.prompt(prompts, function (props) {

    promptData.templateType = props.templateType;
    promptData.publisherName = props.publisherName;
    promptData.publicationName = props.publicationName;

    cb();
  }.bind(this));
};

PugpigGenerator.prototype.appStructure = function appStructure() {

  var projectName = promptData.publisherName + '-' + promptData.publicationName + '-Server',
    projectData = {
      projectName: projectName
    },
    templateType = promptData.templateType,
    modulesFolder;

  themeFolder = 'themes/' + promptData.publicationName.toLowerCase() + '/';
  appDir = themeFolder + 'app/';

  this.mkdir('themes');
  this.mkdir(themeFolder);

  if (templateType === DRUPAL) {
    modulesFolder = 'modules/';
  } else if (templateType === WORDPRESS) {
    modulesFolder = 'plugins/';
  }

  if ( modulesFolder ) {
    this.mkdir(modulesFolder);
    this.mkdir(modulesFolder + 'pugpig-' + promptData.publicationName.toLowerCase());
  }

  if (templateType === DRUPAL) {
    this.template('drupal/theme.info', appDir + promptData.publicationName.toLowerCase() + '.info', {
      publication: promptData.publicationName
    });
    this.copy('drupal/template.php', appDir + 'template.php');
  } else if (templateType === WORDPRESS) {
    this.template('wordpress/plugins.php', modulesFolder + 'pugpig-' + promptData.publicationName.toLowerCase() + '/pugpig_' + promptData.publicationName.toLowerCase() + '.php', {
      publicationCapitalized: promptData.publicationName,
      publicationLowercase: promptData.publicationName.toLowerCase()
    });
    this.template('wordpress/style.css', appDir + 'style.css', {
      publicationName: promptData.publicationName
    });
  }

  this.mkdir(appDir);

  this.directory('static', appDir + 'static');
  this.directory('styles', appDir + 'styles');

  this.mkdir(appDir + 'static/images');
  this.mkdir(appDir + 'styles/components');

  this.template('index.html', appDir + 'static/index.html', projectData);

  this.template('Gruntfile.js', themeFolder + 'Gruntfile.js', {
    publication: promptData.publicationName.toLowerCase(),
    pkg: this.pkg,
    templateType: promptData.templateType
  });

  this.template('_package.json', themeFolder + 'package.json', projectData);

  this.template('_bower.json', themeFolder + 'bower.json', projectData);
  this.copy('bowerrc', themeFolder + '.bowerrc');

};

PugpigGenerator.prototype.createImagesDir = function createImagesDir() {
  this.mkdir(appDir + 'images');
};

PugpigGenerator.prototype.createScriptsDir = function createScriptsDir() {
  this.mkdir(appDir + 'scripts');
};

PugpigGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', themeFolder + '.editorconfig');
  this.copy('jshintrc', themeFolder + '.jshintrc');
};

PugpigGenerator.prototype.gitFiles = function gitFiles() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitmodules', '.gitmodules');
};

PugpigGenerator.prototype.compassFiles = function compassFiles() {
  this.copy('compass.rb', themeFolder + '.compass.rb');
};
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var spaw = require('child_process').spaw;
var chalk = require('chalk');
var globule = require('globule');
var shelljs = require('shelljs');
var yeoman = require('yeoman-generator');
var bundle = false;
var errr = chalk.bold.red;

var MilagroGenerator = module.exports = function MilagroGenerator(args, options, config) {

  var dependenciesInstalled = ['bundle', 'ruby'].every(function (depend) {
    return shelljs.which(depend);
  });

  if (dependenciesInstalled) {
    console.log(errr('Erro!') + ' Certifique-se de ter instalado: ' + chalk.white('Ruby') + ' e ' +chalk.white('Bundler (gem)') + '.');
    shelljs.exit(1);
  }

  yeoman.generators.Base.apply(this, arguments);

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
  this.appname = path.basename(process.cwd());
  this.gitInfo = {
    name: this.user.git.username,
    email: this.user.git.email,
  };

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });

    if (bundle === false) {
      console.log(errr('Erro! Bundle install failed!') + 'Execute o comando manualmente, \'gem install bundle\'');
    }
  });
};

util.inherits(MilagroGenerator, yeoman.generators.Base);

MilagroGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    type: 'confirm',
    name: 'someOption',
    message: 'Would you like to enable this option?',
    default: true
  }];

  this.prompt(prompts, function (props) {
    this.someOption = props.someOption;

    cb();
  }.bind(this));
};

MilagroGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/templates');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
};

MilagroGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Adding askForProject on index.js<commit_after>'use strict';
var util = require('util');
var path = require('path');
var spaw = require('child_process').spaw;
var chalk = require('chalk');
var globule = require('globule');
var shelljs = require('shelljs');
var yeoman = require('yeoman-generator');
var bundle = false;
var errr = chalk.bold.red;

var MilagroGenerator = module.exports = function MilagroGenerator(args, options, config) {

  var dependenciesInstalled = ['bundle', 'ruby'].every(function (depend) {
    return shelljs.which(depend);
  });

  if (dependenciesInstalled) {
    console.log(errr('Erro!') + ' Certifique-se de ter instalado: ' + chalk.white('Ruby') + ' e ' +chalk.white('Bundler (gem)') + '.');
    shelljs.exit(1);
  }

  yeoman.generators.Base.apply(this, arguments);

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
  this.appname = path.basename(process.cwd());
  this.gitInfo = {
    name: this.user.git.username,
    email: this.user.git.email,
  };

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });

    if (bundle === false) {
      console.log(errr('Erro! Bundle install failed!') + 'Execute o comando manualmente, \'gem install bundle\'');
    }
  });
};

util.inherits(MilagroGenerator, yeoman.generators.Base);

// Questions!
MilagroGenerator.prototype.askForProject = function askForProject() {
  var cb = this.async();
  var prompts = [{
    name: 'project',
    message: 'Nome do projeto: '
  },
  {
    name: 'client',
    message: 'Nome do cliente'
  }];

  this.prompt(prompts, function (props) {

    this.project = props.project;
    this.client = props.client;

    cb();
  }.bind(this));
};

// MilagroGenerator.prototype.askFor = function askFor() {
//   var cb = this.async();

//   // have Yeoman greet the user.
//   console.log(this.yeoman);

//   var prompts = [{
//     type: 'confirm',
//     name: 'someOption',
//     message: 'Would you like to enable this option?',
//     default: true
//   }];

//   this.prompt(prompts, function (props) {
//     this.someOption = props.someOption;

//     cb();
//   }.bind(this));
// };

// MilagroGenerator.prototype.app = function app() {
//   this.mkdir('app');
//   this.mkdir('app/templates');

//   this.copy('_package.json', 'package.json');
//   this.copy('_bower.json', 'bower.json');
// };

// MilagroGenerator.prototype.projectfiles = function projectfiles() {
//   this.copy('editorconfig', '.editorconfig');
//   this.copy('jshintrc', '.jshintrc');
// };
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { ThemeProvider } from 'glamorous';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import configureStore, { sagaMiddleware } from './store/configureStore';
import Light from './assets/LM_Font/LeroyMerlinSansOfficeLight-Italic.ttf';

import routes from './routes';
import rootSaga from './sagas/sagas';
import initializeIdleTimer from './utils/initialize-idle-timer';
import './app.global.css';

const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store, {
  selectLocationState(state) {
    return state.get('routing').toJS();
  }
});
injectTapEventPlugin();
sagaMiddleware.run(rootSaga);
initializeIdleTimer(store);

const muiTheme = getMuiTheme({
  slider: {
    selectionColor: '#67cb33',
    rippleColor: '#67cb33',
    handleSize: 20
  }
});

const theme = {
  '@fontFace': {
    fontFamily: 'LeroyMerlinSans Light',
    src: `url(${Light})`
  }
};

render(
  <Provider store={store}>
    <ThemeProvider theme={theme}>
      <MuiThemeProvider muiTheme={muiTheme}>
        <Router
          onUpdate={() => window.scrollTo(0, 0)}
          history={history}
          routes={routes}
        />
      </MuiThemeProvider>
    </ThemeProvider>
  </Provider>,
  document.getElementById('root')
);
<commit_msg>change overlay's backgroundColor<commit_after>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { ThemeProvider } from 'glamorous';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import configureStore, { sagaMiddleware } from './store/configureStore';
import Light from './assets/LM_Font/LeroyMerlinSansOfficeLight-Italic.ttf';

import routes from './routes';
import rootSaga from './sagas/sagas';
import initializeIdleTimer from './utils/initialize-idle-timer';
import './app.global.css';

const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store, {
  selectLocationState(state) {
    return state.get('routing').toJS();
  }
});
injectTapEventPlugin();
sagaMiddleware.run(rootSaga);
initializeIdleTimer(store);

const muiTheme = getMuiTheme({
  slider: {
    selectionColor: '#67cb33',
    rippleColor: '#67cb33',
    handleSize: 20
  },
  overlay: {
    backgroundColor: 'rgba(51, 51, 51, 0.8)'
  }
});

const theme = {
  '@fontFace': {
    fontFamily: 'LeroyMerlinSans Light',
    src: `url(${Light})`
  }
};

render(
  <Provider store={store}>
    <ThemeProvider theme={theme}>
      <MuiThemeProvider muiTheme={muiTheme}>
        <Router onUpdate={() => window.scrollTo(0, 0)} history={history} routes={routes} />
      </MuiThemeProvider>
    </ThemeProvider>
  </Provider>,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var MyappGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();
    this.log(this.yeoman);
    this.log(chalk.magenta('You\'re using the fantastic mobileApp generator.'));

    var prompts = [{
      name: 'appTitle',
      message: 'Enter an app name: ',
      default: 'testApp'
    },
      {
        type: 'checkbox',
        name: 'bowerPackages',
        message: 'Choose the libraries you need: ',
        choices: [
          {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }, {
            name: 'jQuery',
            value: 'includeJQuery',
            checked: true
          }, {
            name: 'Angular JS',
            value: 'includeAngular',
            checked: false
          }
        ]
      }];

    this.prompt(prompts, function (features) {
      function includedBowerFeature(f) {
        return bower.indexOf(f) !== -1;
      }

      var bower = features.bowerPackages;
      this.appTitle = features.appTitle;

      this.bootstrap = includedBowerFeature("includeBootstrap");
      this.jQuery = includedBowerFeature("includeJQuery");
      this.angular = includedBowerFeature("includeAngular");

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('img');
    this.mkdir('css');
    this.mkdir('js');
    this.mkdir('vendor');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', 'index.html');
    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.template('sass/style.sass', 'css/style.sass');
    this.template('sass/reset.sass', 'css/reset.sass');
    this.template('js/main.js', 'js/main.js');

    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
  }
});

module.exports = MyappGenerator;<commit_msg>added test directory<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');

var MyappGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();
    this.log(this.yeoman);
    this.log(chalk.magenta('You\'re using the fantastic mobileApp generator.'));

    var prompts = [{
      name: 'appTitle',
      message: 'Enter an app name: ',
      default: 'testApp'
    },
      {
        type: 'checkbox',
        name: 'bowerPackages',
        message: 'Choose the libraries you need: ',
        choices: [
          {
            name: 'Bootstrap',
            value: 'includeBootstrap',
            checked: false
          }, {
            name: 'jQuery',
            value: 'includeJQuery',
            checked: true
          }, {
            name: 'Angular JS',
            value: 'includeAngular',
            checked: false
          }
        ]
      }];

    this.prompt(prompts, function (features) {
      function includedBowerFeature(f) {
        return bower.indexOf(f) !== -1;
      }

      var bower = features.bowerPackages;
      this.appTitle = features.appTitle;

      this.bootstrap = includedBowerFeature("includeBootstrap");
      this.jQuery = includedBowerFeature("includeJQuery");
      this.angular = includedBowerFeature("includeAngular");

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('img');
    this.mkdir('css');
    this.mkdir('js');
    this.mkdir('vendor');
    this.mkdir('test');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', 'index.html');
    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.template('sass/style.sass', 'css/style.sass');
    this.template('sass/reset.sass', 'css/reset.sass');
    this.template('js/main.js', 'js/main.js');
    this.template('test/testSpec.js', 'test/testSpec.js');

    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
  },

  projectfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
  }
});

module.exports = MyappGenerator;<|endoftext|>


<commit_before>/**
 * @author oldj
 * @blog http://oldj.net
 */

"use strict";

const config = require('../config');
const $ = require('jquery');
const Vue = require('vue');
//Vue.config.debug = true;
Vue.use(require('./dnd'));
const CodeMirror = require('codemirror');
//require('codemirror/mode/shell/shell');
require('./cm_hl');
const cf = require('./cf');
const lang = require('./lang').getLang(navigator.language);
let my_codemirror;

const app = new Vue({
    el: '#sh-app',
    data: {
        lang: lang,
        hosts: cf.getData({
            VERSION: config.VERSION
        }),
        is_prompt_show: false,
        is_edit_show: false,
        is_pswd_show: false,
        current_host: {
            content: cf.getSysHosts(),
            is_sys: true,
            is_editable: false
        },
        on_after_permission: [],
        could_tmp_clean_on: true,
        current_edit_host: {},
        add_or_edit: '',
        sudo_pswd: ''
    },
    watch: {
        'current_host': function (host) {
            my_codemirror.getDoc().setValue(host.content || '');
            if (host.is_editable === false) {
                my_codemirror.setOption('readOnly', true);
            } else {
                my_codemirror.setOption('readOnly', false);
            }

            host._just_switch = 1;
        },
        'current_host.content': function () {
            let host = this.current_host;
            if (host._just_switch) {
                host._just_switch = 0;
                return;
            }
            this.doSave();
            if (host.on) {
                this.caculateHosts(host);
            }
        }
    },
    methods: {
        add: function () {
            this.is_prompt_show = true;
            this.is_edit_show = true;
            this.current_edit_host = {};
            this.add_or_edit = 'add';
            //this.chkHostTitle();

            setTimeout(() => $('#ipt-host-title').focus(), 100);
        },
        edit: function (host) {
            this.is_prompt_show = true;
            this.is_edit_show = true;
            this.current_edit_host = host;
            this.add_or_edit = 'edit';

            setTimeout(() => $('#ipt-host-title').focus(), 100);
        },
        chkHostTitle: function () {
            let host_title = this.current_edit_host.title.replace(/^\s+|\s+$/g, '');
            if (!host_title) {
                this.current_edit_host.title_inform = this.lang.host_title_cant_be_empty;
                $('#ipt-host-title').focus();
                return false;
            } else {
                this.current_edit_host.title_inform = '';
                this.host_title = host_title;
                return true;
            }
        },
        toSave: function () {
            if (!this.chkHostTitle()) {
                return;
            }
            let host;

            //if (this.hosts.list.indexOf(this.current_edit_host) > -1) {
            if (this.add_or_edit == 'edit') {
                // edit
            } else {
                // add new
                host = {
                    title: this.current_edit_host.title,
                    content: `# ${this.current_edit_host.title}`,
                    on: false
                };
                this.hosts.list.push(host);
                this.selectHost(host);
            }

            this.doSave(true);
            this.closePrompt();
        },
        doSave: function (now) {
            clearTimeout(this._t_save);
            this._t_save = setTimeout(() => cf.saveData(this.hosts), now ? 0 : 1000);
        },
        closePrompt: function (action) {
            this.is_prompt_show = false;
            this.is_edit_show = false;
            this.is_pswd_show = false;

            if (action == 'pswd') {
                //    this._to_switch_host.on = !this._to_switch_host.on;
                this.sudo_pswd = '';
                //this.tmpRecover();
                this._on_hosts && this._on_hosts.map((host) => {
                    host.on = true;
                });
                this._on_hosts = [];
            }
        },
        selectHost: function (host) {
            this.current_host = host;
        },
        switchHost: function (host) {
            if (!host) return;
            this._to_switch_host = host;
            if (!host.is_sys) {
                this.could_tmp_clean_on = true;
            }

            this.caculateHosts(host, (err) => {
                if (err) {
                } else {
                    host.on = !host.on;
                    this.doSave();
                }
                this._to_switch_host = null;
            });
        },
        updateHost: function (host) {
            this.doSave();
        },
        showSysHost: function () {
            this.current_host = {
                content: cf.getSysHosts(),
                is_sys: true,
                is_editable: false
            };
        },
        delHost: function (host) {
            if (!confirm(this.lang.confirm_del)) {
                return;
            }

            let i = this.hosts.list.indexOf(host);
            if (i > -1) {
                this.hosts.list.splice(i, 1);
                this.current_edit_host = {};
                this.closePrompt();
                this.doSave();
            }
        },
        caculateHosts: function (host, callback) {
            let on_hosts = [];
            host = host || this.current_host;
            this.hosts.list.map((host) => {
                if ((host.on && host != this._to_switch_host) || (!host.on && host == this._to_switch_host)) {
                    on_hosts.push(host.content);
                }
            });

            let s_hosts = on_hosts.join('\n\n# --------------------\n\n');
            s_hosts = `# SwitchHosts!\n${s_hosts}`;
            cf.saveHost(s_hosts, this.sudo_pswd, (err) => {
                if (err) {
                    console.log(err);
                    if (err.message.indexOf('EACCES') > -1 || err.message.indexOf('permission denied') > -1) {
                        // get permission
                        this.askForPermission(() => {
                            this.caculateHosts(host, callback)
                        });
                    } else if (err.message.indexOf('Command failed') > -1) {
                        // todo show inform
                        this.sudo_pswd = '';
                    }
                    return;
                }
                callback && callback.call(this);
                if (this.current_host.is_sys) {
                    this.showSysHost();
                }
            });
        },
        askForPermission: function (callback) {
            this.is_prompt_show = true;
            this.is_pswd_show = true;
            this.sudo_pswd = '';
            callback && this.on_after_permission.push(callback);

            setTimeout(() => $('#ipt-pswd').focus(), 100);
        },
        chkPswd: function () {
            //this.switchHost(this._to_switch_host);
            this.closePrompt();
            //this._to_switch_host = null;

            let f;
            while (f = this.on_after_permission.shift()) {
                f && f.call(this);
            }
        },
        tmpClean: function () {
            this.could_tmp_clean_on = false;
            this._to_switch_host = null;
            this._on_hosts = [];
            this.hosts.list.map((host) => {
                if (host.on) {
                    this._on_hosts.push(host);
                    host.on = false;
                }
            });
            this.caculateHosts();
            this.doSave(true);
        },
        tmpRecover: function () {
            this.could_tmp_clean_on = true;
            if (!this._on_hosts) return;

            this._on_hosts.map((host) => {
                host.on = true;
            });
            this._on_hosts = [];
            this.caculateHosts();
            this.doSave(1);
        },
        sort: function (list, id, tag, data) {
            let tmp = list[data.index];
            list.splice(data.index, 1);
            list.splice(id, 0, tmp);

            this.doSave(1);
        },
        move: function (from, to, id, tag, data) {
            let tmp = from[data.index];
            from.splice(data.index, 1);
            to.splice(id, 0, tmp);
        },
        remove: function (from, tag, data) {
            from.splice(data.index, 1);
        },
        log: function (obj) {
            console.log(obj);
            return 1;
        }
    }
});

function resize() {
    let wh = window.innerHeight;
    let h = wh - $('#sys-list').height() - 20;
    $('#custom-list').css('height', h);
    my_codemirror.setSize('100%', wh);
}

$(document).ready(function () {
    let el_textarea = $('#host-code');
    //el_textarea.css('height', window.innerHeight - 8);

    my_codemirror = CodeMirror.fromTextArea(el_textarea[0], {
        lineNumbers: true,
        readOnly: true,
        mode: 'host'
    });

    my_codemirror.on('change', function (a, b) {
        app.current_host.content = a.getDoc().getValue();
    });

    my_codemirror.on('gutterClick', function (cm, n) {
        if (app.current_host.is_editable === false) return;

        let info = cm.lineInfo(n);
        //cm.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
        let ln = info.text;
        if (/^\s*$/.test(ln)) return;

        let new_ln;
        if (/^#/.test(ln)) {
            new_ln = ln.replace(/^#\s*/, '');
        } else {
            new_ln = '# ' + ln;
        }
        my_codemirror.getDoc().replaceRange(new_ln, {line: info.line, ch: 0}, {line: info.line, ch: ln.length});
        //app.caculateHosts();
    });

    resize();
    $(window).resize(resize);
});
<commit_msg>在 windows 下不尝试请求 sudo 密码。<commit_after>/**
 * @author oldj
 * @blog http://oldj.net
 */

"use strict";

const config = require('../config');
const $ = require('jquery');
const Vue = require('vue');
//Vue.config.debug = true;
Vue.use(require('./dnd'));
const CodeMirror = require('codemirror');
//require('codemirror/mode/shell/shell');
require('./cm_hl');
const cf = require('./cf');
const lang = require('./lang').getLang(navigator.language);
const is_win = process.platform == 'win32';
let my_codemirror;

const app = new Vue({
    el: '#sh-app',
    data: {
        lang: lang,
        hosts: cf.getData({
            VERSION: config.VERSION
        }),
        is_prompt_show: false,
        is_edit_show: false,
        is_pswd_show: false,
        current_host: {
            content: cf.getSysHosts(),
            is_sys: true,
            is_editable: false
        },
        on_after_permission: [],
        could_tmp_clean_on: true,
        current_edit_host: {},
        add_or_edit: '',
        sudo_pswd: ''
    },
    watch: {
        'current_host': function (host) {
            my_codemirror.getDoc().setValue(host.content || '');
            if (host.is_editable === false) {
                my_codemirror.setOption('readOnly', true);
            } else {
                my_codemirror.setOption('readOnly', false);
            }

            host._just_switch = 1;
        },
        'current_host.content': function () {
            let host = this.current_host;
            if (host._just_switch) {
                host._just_switch = 0;
                return;
            }
            this.doSave();
            if (host.on) {
                this.caculateHosts(host);
            }
        }
    },
    methods: {
        add: function () {
            this.is_prompt_show = true;
            this.is_edit_show = true;
            this.current_edit_host = {};
            this.add_or_edit = 'add';
            //this.chkHostTitle();

            setTimeout(() => $('#ipt-host-title').focus(), 100);
        },
        edit: function (host) {
            this.is_prompt_show = true;
            this.is_edit_show = true;
            this.current_edit_host = host;
            this.add_or_edit = 'edit';

            setTimeout(() => $('#ipt-host-title').focus(), 100);
        },
        chkHostTitle: function () {
            let host_title = this.current_edit_host.title.replace(/^\s+|\s+$/g, '');
            if (!host_title) {
                this.current_edit_host.title_inform = this.lang.host_title_cant_be_empty;
                $('#ipt-host-title').focus();
                return false;
            } else {
                this.current_edit_host.title_inform = '';
                this.host_title = host_title;
                return true;
            }
        },
        toSave: function () {
            if (!this.chkHostTitle()) {
                return;
            }
            let host;

            //if (this.hosts.list.indexOf(this.current_edit_host) > -1) {
            if (this.add_or_edit == 'edit') {
                // edit
            } else {
                // add new
                host = {
                    title: this.current_edit_host.title,
                    content: `# ${this.current_edit_host.title}`,
                    on: false
                };
                this.hosts.list.push(host);
                this.selectHost(host);
            }

            this.doSave(true);
            this.closePrompt();
        },
        doSave: function (now) {
            clearTimeout(this._t_save);
            this._t_save = setTimeout(() => cf.saveData(this.hosts), now ? 0 : 1000);
        },
        closePrompt: function (action) {
            this.is_prompt_show = false;
            this.is_edit_show = false;
            this.is_pswd_show = false;

            if (action == 'pswd') {
                //    this._to_switch_host.on = !this._to_switch_host.on;
                this.sudo_pswd = '';
                //this.tmpRecover();
                this._on_hosts && this._on_hosts.map((host) => {
                    host.on = true;
                });
                this._on_hosts = [];
            }
        },
        selectHost: function (host) {
            this.current_host = host;
        },
        switchHost: function (host) {
            if (!host) return;
            this._to_switch_host = host;
            if (!host.is_sys) {
                this.could_tmp_clean_on = true;
            }

            this.caculateHosts(host, (err) => {
                if (err) {
                } else {
                    host.on = !host.on;
                    this.doSave();
                }
                this._to_switch_host = null;
            });
        },
        updateHost: function (host) {
            this.doSave();
        },
        showSysHost: function () {
            this.current_host = {
                content: cf.getSysHosts(),
                is_sys: true,
                is_editable: false
            };
        },
        delHost: function (host) {
            if (!confirm(this.lang.confirm_del)) {
                return;
            }

            let i = this.hosts.list.indexOf(host);
            if (i > -1) {
                this.hosts.list.splice(i, 1);
                this.current_edit_host = {};
                this.closePrompt();
                this.doSave();
            }
        },
        caculateHosts: function (host, callback) {
            let on_hosts = [];
            host = host || this.current_host;
            this.hosts.list.map((host) => {
                if ((host.on && host != this._to_switch_host) || (!host.on && host == this._to_switch_host)) {
                    on_hosts.push(host.content);
                }
            });

            let s_hosts = on_hosts.join('\n\n# --------------------\n\n');
            s_hosts = `# SwitchHosts!\n${s_hosts}`;
            cf.saveHost(s_hosts, this.sudo_pswd, (err) => {
                if (err) {
                    console.log(err);
                    if (!is_win) {
                        // mac & linux
                        if (err.message.indexOf('EACCES') > -1 || err.message.indexOf('permission denied') > -1) {
                            // get permission
                            this.askForPermission(() => {
                                this.caculateHosts(host, callback)
                            });
                        } else if (err.message.indexOf('Command failed') > -1) {
                            // todo show inform
                            this.sudo_pswd = '';
                        } else {
                            alert(err);
                        }
                    } else {
                        // windows
                        alert(err);
                    }
                    return;
                }
                callback && callback.call(this);
                if (this.current_host.is_sys) {
                    this.showSysHost();
                }
            });
        },
        askForPermission: function (callback) {
            this.is_prompt_show = true;
            this.is_pswd_show = true;
            this.sudo_pswd = '';
            callback && this.on_after_permission.push(callback);

            setTimeout(() => $('#ipt-pswd').focus(), 100);
        },
        chkPswd: function () {
            //this.switchHost(this._to_switch_host);
            this.closePrompt();
            //this._to_switch_host = null;

            let f;
            while (f = this.on_after_permission.shift()) {
                f && f.call(this);
            }
        },
        tmpClean: function () {
            this.could_tmp_clean_on = false;
            this._to_switch_host = null;
            this._on_hosts = [];
            this.hosts.list.map((host) => {
                if (host.on) {
                    this._on_hosts.push(host);
                    host.on = false;
                }
            });
            this.caculateHosts();
            this.doSave(true);
        },
        tmpRecover: function () {
            this.could_tmp_clean_on = true;
            if (!this._on_hosts) return;

            this._on_hosts.map((host) => {
                host.on = true;
            });
            this._on_hosts = [];
            this.caculateHosts();
            this.doSave(1);
        },
        sort: function (list, id, tag, data) {
            let tmp = list[data.index];
            list.splice(data.index, 1);
            list.splice(id, 0, tmp);

            this.doSave(1);
        },
        move: function (from, to, id, tag, data) {
            let tmp = from[data.index];
            from.splice(data.index, 1);
            to.splice(id, 0, tmp);
        },
        remove: function (from, tag, data) {
            from.splice(data.index, 1);
        },
        log: function (obj) {
            console.log(obj);
            return 1;
        }
    }
});

function resize() {
    let wh = window.innerHeight;
    let h = wh - $('#sys-list').height() - 20;
    $('#custom-list').css('height', h);
    my_codemirror.setSize('100%', wh);
}

$(document).ready(function () {
    let el_textarea = $('#host-code');
    //el_textarea.css('height', window.innerHeight - 8);

    my_codemirror = CodeMirror.fromTextArea(el_textarea[0], {
        lineNumbers: true,
        readOnly: true,
        mode: 'host'
    });

    my_codemirror.on('change', function (a, b) {
        app.current_host.content = a.getDoc().getValue();
    });

    my_codemirror.on('gutterClick', function (cm, n) {
        if (app.current_host.is_editable === false) return;

        let info = cm.lineInfo(n);
        //cm.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
        let ln = info.text;
        if (/^\s*$/.test(ln)) return;

        let new_ln;
        if (/^#/.test(ln)) {
            new_ln = ln.replace(/^#\s*/, '');
        } else {
            new_ln = '# ' + ln;
        }
        my_codemirror.getDoc().replaceRange(new_ln, {line: info.line, ch: 0}, {line: info.line, ch: ln.length});
        //app.caculateHosts();
    });

    resize();
    $(window).resize(resize);
});
<|endoftext|>