<commit_before>var React = require("react")
  , indexJade = require('./index.jade')
  , pellet = require("pellet");

function getData(_this, page, search, next) {
  var api = _this.coordinator('DAL', 'DAL', next?'serialize':void 0);

  if(page < 0) {
    page = 0;
  }

  var limit = 5;
  var offset = limit * page;
  var sql = search ?
      'SELECT title, out(hasGenera).description as genera, first(in(rated)).gender as gender, in(ratings).size() as ratings FROM Movies WHERE title LIKE :search OFFSET :offset' :
      'SELECT title, out(hasGenera).description as genera, first(in(rated)).gender as gender, in(ratings).size() as ratings FROM Movies WHERE OFFSET :offset';

  api.select(sql, {offset:offset, search: '%' + search + '%'}, limit, function(err, movies) {
    if(err) {
      return next(err);
    }

    _this.setState({movies:movies, limit:limit, offset:offset, page:page});
    if(next) {
      next();
    }
  });
}

module.exports = indexPage = pellet.createClass({
  /*
  getInitialState: function() {
    return {};
  },
  componentWillMount: function() {
  },
  componentDidMount: function(nextProps) {
  },
  componentWillReceiveProps: function(nextProps) {
  },
  shouldComponentUpdate: function(nextProps, nextState) {
  },
  componentWillUpdate: function(nextProps, nextState) {
  },
  componentDidUpdate: function(prevProps, prevState) {
  },
  componentWillUnmount: function(nextProps, nextState) {
  },
  */

// layoutTemplate: "{name_of_your_layout_in_the_manifest}",

  routes: ["/", "/index", "/movie/:id"],

  componentConstruction: function(options, next) {
    this.setCanonical('http://pellet.io/demo');
    this.addToHead('meta', {name: 'description', content:'movie database demo'});
    this.addToHead('link', {rel: 'alternate', media:'only screen and (max-width: 640px)', href: 'http://m.pellet.io/demo'});
    this.addToHead('meta', {property: 'og:description', content:'movie database demo'});

    /* Example of redirect and UA logic
    var userAgent = this.getUA();
    if(userAgent && userAgent.device && userAgent.device.type !== "web") {
      this.redirect('http://pellet.io/demo');
    }
    */

    getData(this, 0, this.props.query && this.props.query.search, next);
  },

  componentDidMount: function(nextProps) {
    var _this = this;
    var el = this.refs['search'].getDOMNode();
    pellet.observables.fromEvent(el, "keyup")
      .debounce(300)
      .onValue(function(evt) {
        if(evt.key === 13 || evt.keyCode === 13 || evt.which === 13) {
          el.blur();
        }

        window.history.replaceState(null, null, '/?search=' + encodeURIComponent(el.value));
        getData(_this, 0, (el.value.trim().length > 1) ? el.value : null);
      });
  },

  prev: function() {
    getData(this, this.state.page-1, null);
  },

  next: function() {
    getData(this, this.state.page+1, null);
  },

  setLanguage: function(locale) {
    var _this = this;

    pellet.intl.load(locale, function() {
      _this.setProps({locales: locale});
      pellet.cookie.set('language', locale);
      document.body.setAttribute('locales', locale);
    });
  },

  en: function() {
    this.setLanguage('en-US');
  },

  fr: function() {
    this.setLanguage('fr-FR');
  },

  ja:function() {
    this.setLanguage('ja');
  },

  render: function() {
    return indexJade(this);
  }
});

pellet.setLocaleLookupFn(function(renderOptions, component, options) {
  var loc = renderOptions.http.cookie('language') ||
            renderOptions.http.headers('x-vevo-culture') ||
            pellet.options.locales || 'en-US';
  loc = loc.split('-');
  return loc[0].toLowerCase() + '-' + (loc[1] || loc[0]).toUpperCase();
});<commit_msg>Add basic logging, alerts, timers, etc<commit_after>var React = require("react")
  , indexJade = require('./index.jade')
  , pellet = require("pellet");

function getData(_this, page, search, next) {
  var api = _this.coordinator('DAL', 'DAL', next?'serialize':void 0);

  if(page < 0) {
    page = 0;
  }

  var limit = 5;
  var offset = limit * page;
  var sql = search ?
      'SELECT title, out(hasGenera).description as genera, first(in(rated)).gender as gender, in(ratings).size() as ratings FROM Movies WHERE title LIKE :search OFFSET :offset' :
      'SELECT title, out(hasGenera).description as genera, first(in(rated)).gender as gender, in(ratings).size() as ratings FROM Movies WHERE OFFSET :offset';

  var instrument = pellet.instrumentation.namespace(process.env.SERVER_ENV?'server.movieDBDemo.':'client.movieDBDemo.');

  pellet.instrumentation.log({type:'search', term:search});

  instrument.increment("search");
  var measure = instrument.elapseTimer(false, "select.");

  measure.mark("start");

  api.select(sql, {offset:offset, search: '%' + search + '%'}, limit, function(err, movies) {
    measure.mark("done");
    if(err) {
      instrument.increment("select.error");
      return next(err);
    }

    _this.setState({movies:movies, limit:limit, offset:offset, page:page});
    if(next) {
      next();
    }
  });
}

module.exports = indexPage = pellet.createClass({
  /*
  getInitialState: function() {
    return {};
  },
  componentWillMount: function() {
  },
  componentDidMount: function(nextProps) {
  },
  componentWillReceiveProps: function(nextProps) {
  },
  shouldComponentUpdate: function(nextProps, nextState) {
  },
  componentWillUpdate: function(nextProps, nextState) {
  },
  componentDidUpdate: function(prevProps, prevState) {
  },
  componentWillUnmount: function(nextProps, nextState) {
  },
  */

// layoutTemplate: "{name_of_your_layout_in_the_manifest}",

  routes: ["/", "/index", "/movie/:id"],

  componentConstruction: function(options, next) {
    this.setCanonical('http://pellet.io/demo');
    this.addToHead('meta', {name: 'description', content:'movie database demo'});
    this.addToHead('link', {rel: 'alternate', media:'only screen and (max-width: 640px)', href: 'http://m.pellet.io/demo'});
    this.addToHead('meta', {property: 'og:description', content:'movie database demo'});

    /* Example of redirect and UA logic
    var userAgent = this.getUA();
    if(userAgent && userAgent.device && userAgent.device.type !== "web") {
      this.redirect('http://pellet.io/demo');
    }
    */

    getData(this, 0, this.props.query && this.props.query.search, next);
  },

  componentDidMount: function(nextProps) {
    var _this = this;
    var el = this.refs['search'].getDOMNode();
    pellet.observables.fromEvent(el, "keyup")
      .debounce(300)
      .onValue(function(evt) {
        if(evt.key === 13 || evt.keyCode === 13 || evt.which === 13) {
          el.blur();
        }

        window.history.replaceState(null, null, '/?search=' + encodeURIComponent(el.value));
        getData(_this, 0, (el.value.trim().length > 1) ? el.value : null);
      });
  },

  prev: function() {
    getData(this, this.state.page-1, null);
  },

  next: function() {
    getData(this, this.state.page+1, null);
  },

  setLanguage: function(locale) {
    var _this = this;

    pellet.intl.load(locale, function() {
      _this.setProps({locales: locale});
      pellet.cookie.set('language', locale);
      document.body.setAttribute('locales', locale);
    });
  },

  en: function() {
    this.setLanguage('en-US');
  },

  fr: function() {
    this.setLanguage('fr-FR');
  },

  ja:function() {
    this.setLanguage('ja');
  },

  render: function() {
    return indexJade(this);
  }
});

pellet.setLocaleLookupFn(function(renderOptions, component, options) {
  var loc = renderOptions.http.cookie('language') ||
            renderOptions.http.headers('x-vevo-culture') ||
            pellet.options.locales || 'en-US';
  loc = loc.split('-');
  return loc[0].toLowerCase() + '-' + (loc[1] || loc[0]).toUpperCase();
});<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import _ from 'lodash';

const HostsTable = React.createClass({
  propTypes: {
    hosts: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      cpu: PropTypes.string,
      load: PropTypes.string,
    })),
    source: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      searchTerm: '',
      filteredHosts: this.props.hosts,
      sortDirection: null,
    };
  },

  componentWillReceiveProps(newProps) {
    this.filterHosts(newProps.hosts, this.state.searchTerm);
  },

  filterHosts(allHosts, searchTerm) {
    const hosts = allHosts.filter((h) => h.name.search(searchTerm) !== -1);
    this.setState({searchTerm, filteredHosts: hosts});
  },

  changeSort() {
    if (this.state.sortDirection === 'asc') {
      this.setState({sortDirection: 'desc'});
    } else {
      this.setState({sortDirection: 'asc'});
    }
  },

  sort(hosts, direction) {
    switch (direction) {
      case 'asc':
        return _.sortBy(hosts, (e) => e.name);
      case 'desc':
        return _.sortBy(hosts, (e) => e.name).reverse();
      default:
        return hosts;
    }
  },

  render() {
    const hosts = this.sort(this.state.filteredHosts, this.state.sortDirection);
    const {source} = this.props;

    return (

{this.props.hosts.length} Hosts

          <SearchBar onSearch={_.wrap(this.props.hosts, this.filterHosts)} />

                Hostname
                Status
                CPU
                Load
                Apps

              {
                hosts.map(({name, cpu, load}) => {
                  return (

                      <a href={`/sources/${source.id}/hosts/${name}`}>{name}

                      {`${cpu}%`}
                      {`${load}`}
                      influxdb, ntp, system

                  );
                })
              }

    );
  },
});

const SearchBar = React.createClass({
  propTypes: {
    onSearch: PropTypes.func.isRequired,
  },

  handleChange() {
    this.props.onSearch(this.refs.searchInput.value);
  },

  render() {
    return (

        <input
          type="text"
          className="form-control"
          placeholder="Find host"
          ref="searchInput"
          onChange={this.handleChange}
        />

    );
  },
});

export default HostsTable;
<commit_msg>Copy Tweak<commit_after>import React, {PropTypes} from 'react';
import _ from 'lodash';

const HostsTable = React.createClass({
  propTypes: {
    hosts: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      cpu: PropTypes.string,
      load: PropTypes.string,
    })),
    source: PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      searchTerm: '',
      filteredHosts: this.props.hosts,
      sortDirection: null,
    };
  },

  componentWillReceiveProps(newProps) {
    this.filterHosts(newProps.hosts, this.state.searchTerm);
  },

  filterHosts(allHosts, searchTerm) {
    const hosts = allHosts.filter((h) => h.name.search(searchTerm) !== -1);
    this.setState({searchTerm, filteredHosts: hosts});
  },

  changeSort() {
    if (this.state.sortDirection === 'asc') {
      this.setState({sortDirection: 'desc'});
    } else {
      this.setState({sortDirection: 'asc'});
    }
  },

  sort(hosts, direction) {
    switch (direction) {
      case 'asc':
        return _.sortBy(hosts, (e) => e.name);
      case 'desc':
        return _.sortBy(hosts, (e) => e.name).reverse();
      default:
        return hosts;
    }
  },

  render() {
    const hosts = this.sort(this.state.filteredHosts, this.state.sortDirection);
    const {source} = this.props;

    return (

{this.props.hosts.length} Hosts

          <SearchBar onSearch={_.wrap(this.props.hosts, this.filterHosts)} />

                Hostname
                Status
                CPU
                Load
                Apps

              {
                hosts.map(({name, cpu, load}) => {
                  return (

                      <a href={`/sources/${source.id}/hosts/${name}`}>{name}

                      {`${cpu}%`}
                      {`${load}`}
                      influxdb, ntp, system

                  );
                })
              }

    );
  },
});

const SearchBar = React.createClass({
  propTypes: {
    onSearch: PropTypes.func.isRequired,
  },

  handleChange() {
    this.props.onSearch(this.refs.searchInput.value);
  },

  render() {
    return (

        <input
          type="text"
          className="form-control"
          placeholder="Filter Hosts"
          ref="searchInput"
          onChange={this.handleChange}
        />

    );
  },
});

export default HostsTable;
<|endoftext|>


<commit_before>function strval(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: Comment out the entire switch if you want JS-like behavior instead of PHP behavior
    // -    depends on: gettype
    // *     example 1: strval({red: 1, green: 2, blue: 3, white: 4});
    // *     returns 1: 'Array'

    var type = '';

    if (str === null) return '';

    type = gettype(str);
    switch (type) {
        case 'boolean':
            if (str === true) return '1';
            return '';
        case 'array':
            return 'Array';
        case 'object':
            return 'Object';
    }

    return str+''+type;
}<commit_msg>Fixed strval bug<commit_after>function strval(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir
    // %        note 1: Comment out the entire switch if you want JS-like behavior instead of PHP behavior
    // -    depends on: gettype
    // *     example 1: strval({red: 1, green: 2, blue: 3, white: 4});
    // *     returns 1: 'Array'

    var type = '';

    if (str === null) return '';

    type = gettype(str);
    switch (type) {
        case 'boolean':
            if (str === true) return '1';
            return '';
        case 'array':
            return 'Array';
        case 'object':
            return 'Object';
    }

    return str;
}<|endoftext|>


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

/* Constants use throughout */
const INTERPOLATE_REGEX = constants.INTERPOLATE_REGEX;
const CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
const ANGULAR_DIR = constants.ANGULAR_DIR;
const SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
const TEST_DIR = constants.TEST_DIR;
const SERVER_TEST_SRC_DIR = constants.SERVER_TEST_SRC_DIR;

const SERVER_TEMPLATES_DIR = 'server';
const CLIENT_NG1_TEMPLATES_DIR = 'client/angularjs';
const CLIENT_NG2_TEMPLATES_DIR = 'client/angular';
const CLIENT_I18N_TEMPLATES_DIR = 'client';

/**
 * The default is to use a file path string. It implies use of the template method.
 * For any other config an object { file:.., method:.., template:.. } can be used
 */
const serverFiles = {
    server: [
        {
            condition: generator => generator.contactServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/_PageSetResource.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/${generator.pageSetClass}Resource.java`
                }
            ]
        },
        {
            condition: generator => generator.loadFromServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/vm/_PageLoadVM.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/vm/${generator.pageLoadClass}.java`
                }
            ]
        },
        {
            condition: generator => generator.saveToServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/vm/_PageSaveVM.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/vm/${generator.pageSaveClass}.java`
                }
            ]
        }
    ],
    test: [
        {
            path: SERVER_TEST_SRC_DIR,
            condition: generator => generator.contactServer === true,
            templates: [{
                file: 'package/web/rest/_PageSetResourceIntTest.java',
                options: { context: { randexp, _, chalkRed: chalk.red, fs, SERVER_TEST_SRC_DIR } },
                renameTo: generator => `${generator.packageFolder}/web/rest/${generator.pageSetClass}ResourceIntTest.java`
            }]
        },
        {
            condition: generator => generator.gatlingTests && generator.contactServer === true,
            path: TEST_DIR,
            templates: [{
                file: 'gatling/user-files/simulations/_PageSetGatlingTest.scala',
                options: { interpolate: INTERPOLATE_REGEX },
                renameTo: generator => `gatling/user-files/simulations/${generator.pageSetClass}GatlingTest.scala`
            }]
        }
    ]
};

const angularjsFiles = {
    pageCommon: [
        {
            path: ANGULAR_DIR,
            templates: [
                {
                    file: 'pages/_page-sets.state.js',
                    renameTo: generator => `pages/page-sets.state.js`
                },
                {
                    file: 'pages/_page-set.state.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSetAngularClass}.state.js`
                },
                {
                    file: 'pages/_page.controller.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.controller.js`
                },
                {
                    file: 'pages/_page.html',
                    method: 'processHtml',
                    template: true,
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.html`
                }
            ]
        }
    ],
    pageCommonWithService: [
        {
            path: ANGULAR_DIR,
            condition: generator => generator.contactServer === true,
            templates: [
                {
                    file: 'pages/_page.service.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.service.js`
                }
            ]
        }
    ],

    test: [
        {
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'spec/app/pages/_page.controller.spec.js',
                renameTo: generator => `spec/app/pages/${generator.pageSetFolder}/${generator.pageName}.controller.spec.js`
            }]
        },
        {
            condition: generator => generator.protractorTests,
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'e2e/pages/_page.js',
                renameTo: generator => `e2e/pages/${generator.pageName}.js`
            }]
        }
    ]
};

const angularFiles = {
    client: [
        {
            path: ANGULAR_DIR,
            templates: [
                {
                    condition: generator => generator.pageType !== 'clientOnly',
                    file: 'pages/_page-set.service.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSet}.service.ts`
                },
                {
                    file: 'pages/_page-set.route.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSet}.route.ts`
                },
                {
                    file: `pages/_page-${generator.pageType}.component.html`,
                    method: 'processHtml',
                    template: true,
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.component.html`
                },
                {
                    file: 'pages/_index.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/index.ts`
                },
                {
                    file: 'pages/_page.module.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.module.ts`
                },

                {
                    file: 'pages/_page.model.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.model.ts`
                }
            ]
        }
    ],
    test: [
        {
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: `spec/app/pages/_page-${generator.pageType}.component.spec.ts`,
                renameTo: generator => `spec/app/pages/${generator.pageSetFolder}/${generator.pageName}.component.spec.ts`
            }]
        },
        {
            condition: generator => generator.protractorTests,
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'e2e/pages/_page.spec.ts',
                renameTo: generator => `e2e/pages/${generator.pageName}.spec.ts`
            }]
        }
    ]
};

module.exports = {
    writeFiles,
    serverFiles,
    angularjsFiles,
    angularFiles
};

function writeFiles() {
    return {

        readConf() {

            // read config from .yo-rc.json
            this.baseName = this.jhipsterAppConfig.baseName;
            this.packageName = this.jhipsterAppConfig.packageName;
            this.packageFolder = this.jhipsterAppConfig.packageFolder;
            this.clientFramework = this.jhipsterAppConfig.clientFramework;
            this.clientPackageManager = this.jhipsterAppConfig.clientPackageManager;
            this.buildTool = this.jhipsterAppConfig.buildTool;

            // use function in generator-base.js from generator-jhipster
            this.angularAppName = this.getAngularAppName();

            // use constants from generator-constants.js
            const javaDir = `${constants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
            const resourceDir = constants.SERVER_MAIN_RES_DIR;
            const webappDir = constants.CLIENT_MAIN_SRC_DIR;

            // variable from questions
            //this.message = this.props.pageSet;

            // show all variables
            this.log('\n--- some config read from config ---');
            this.log(`baseName=${this.baseName}`);
            this.log(`packageName=${this.packageName}`);
            this.log(`clientFramework=${this.clientFramework}`);
            this.log(`clientPackageManager=${this.clientPackageManager}`);
            this.log(`buildTool=${this.buildTool}`);

            this.log('\n--- some function ---');
            this.log(`angularAppName=${this.angularAppName}`);

            this.log('\n--- some const ---');
            this.log(`javaDir=${javaDir}`);
            this.log(`resourceDir=${resourceDir}`);
            this.log(`webappDir=${webappDir}`);

            this.log('\n--- variables from questions ---');
            this.log(`\npageSet=${this.pageSet}`);
            this.log(`\nnewPageSet=${this.newPageSet}`);
            this.log(`\npageType=${this.pageType}`);
            this.log(`\npageName=${this.pageName}`);
            this.log(`\nfuck=${this.pageType !== 'clientOnly'}`);

            this.log('------\n');

        },

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

            // write server side files
            this.writeFilesToDisk(serverFiles, this, false, SERVER_TEMPLATES_DIR);
        },

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

            if (this.clientFramework === 'angular1') {
                // write client side files for angular 1.x
                this.writeFilesToDisk(angularjsFiles, this, false, CLIENT_NG1_TEMPLATES_DIR);
            } else {
                // write client side files for angular 2.x +
                this.writeFilesToDisk(angularFiles, this, false, CLIENT_NG2_TEMPLATES_DIR);
            }

            this.addElementToMenu(this.pageSet+'-'+this.pageName, this.pageGlyphIcon, this.enableTranslation, this.clientFramework);

            // Copy for each
            if (this.enableTranslation) {
                const languages = this.languages || this.getAllInstalledLanguages();
                languages.forEach((language) => {
                    try {
                        this.template(`${CLIENT_I18N_TEMPLATES_DIR}/i18n/_page_${language}.json`, `${CLIENT_MAIN_SRC_DIR}i18n/${language}/${this.pageInstance}.json`);
                        this.addEntityTranslationKey(this.pageSetTranslation, this.pageSetClass, language);
                        this.addEntityTranslationKey(this.pageNameTranslationKey, this.pageClass, language);
                    } catch (e) {
                        // An exception is thrown if the folder doesn't exist
                        // do nothing
                    }
                });
            }
        }
    };
}
<commit_msg>fix state uri for navbar<commit_after>/**
 * Copyright 2013-2017 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://jhipster.github.io/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const _ = require('lodash');
const randexp = require('randexp');
const chalk = require('chalk');
const fs = require('fs');
const generator = require('yeoman-generator');
const constants = require('generator-jhipster/generators/generator-constants');

/* Constants use throughout */
const INTERPOLATE_REGEX = constants.INTERPOLATE_REGEX;
const CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
const ANGULAR_DIR = constants.ANGULAR_DIR;
const SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;
const TEST_DIR = constants.TEST_DIR;
const SERVER_TEST_SRC_DIR = constants.SERVER_TEST_SRC_DIR;

const SERVER_TEMPLATES_DIR = 'server';
const CLIENT_NG1_TEMPLATES_DIR = 'client/angularjs';
const CLIENT_NG2_TEMPLATES_DIR = 'client/angular';
const CLIENT_I18N_TEMPLATES_DIR = 'client';

/**
 * The default is to use a file path string. It implies use of the template method.
 * For any other config an object { file:.., method:.., template:.. } can be used
 */
const serverFiles = {
    server: [
        {
            condition: generator => generator.contactServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/_PageSetResource.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/${generator.pageSetClass}Resource.java`
                }
            ]
        },
        {
            condition: generator => generator.loadFromServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/vm/_PageLoadVM.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/vm/${generator.pageLoadClass}.java`
                }
            ]
        },
        {
            condition: generator => generator.saveToServer === true,
            path: SERVER_MAIN_SRC_DIR,
            templates: [
                {
                    file: 'package/web/rest/vm/_PageSaveVM.java',
                    renameTo: generator => `${generator.packageFolder}/web/rest/vm/${generator.pageSaveClass}.java`
                }
            ]
        }
    ],
    test: [
        {
            path: SERVER_TEST_SRC_DIR,
            condition: generator => generator.contactServer === true,
            templates: [{
                file: 'package/web/rest/_PageSetResourceIntTest.java',
                options: { context: { randexp, _, chalkRed: chalk.red, fs, SERVER_TEST_SRC_DIR } },
                renameTo: generator => `${generator.packageFolder}/web/rest/${generator.pageSetClass}ResourceIntTest.java`
            }]
        },
        {
            condition: generator => generator.gatlingTests && generator.contactServer === true,
            path: TEST_DIR,
            templates: [{
                file: 'gatling/user-files/simulations/_PageSetGatlingTest.scala',
                options: { interpolate: INTERPOLATE_REGEX },
                renameTo: generator => `gatling/user-files/simulations/${generator.pageSetClass}GatlingTest.scala`
            }]
        }
    ]
};

const angularjsFiles = {
    pageCommon: [
        {
            path: ANGULAR_DIR,
            templates: [
                {
                    file: 'pages/_page-sets.state.js',
                    renameTo: generator => `pages/page-sets.state.js`
                },
                {
                    file: 'pages/_page-set.state.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSetAngularClass}.state.js`
                },
                {
                    file: 'pages/_page.controller.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.controller.js`
                },
                {
                    file: 'pages/_page.html',
                    method: 'processHtml',
                    template: true,
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.html`
                }
            ]
        }
    ],
    pageCommonWithService: [
        {
            path: ANGULAR_DIR,
            condition: generator => generator.contactServer === true,
            templates: [
                {
                    file: 'pages/_page.service.js',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageAngularName}.service.js`
                }
            ]
        }
    ],

    test: [
        {
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'spec/app/pages/_page.controller.spec.js',
                renameTo: generator => `spec/app/pages/${generator.pageSetFolder}/${generator.pageName}.controller.spec.js`
            }]
        },
        {
            condition: generator => generator.protractorTests,
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'e2e/pages/_page.js',
                renameTo: generator => `e2e/pages/${generator.pageName}.js`
            }]
        }
    ]
};

const angularFiles = {
    client: [
        {
            path: ANGULAR_DIR,
            templates: [
                {
                    condition: generator => generator.pageType !== 'clientOnly',
                    file: 'pages/_page-set.service.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSet}.service.ts`
                },
                {
                    file: 'pages/_page-set.route.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageSet}.route.ts`
                },
                {
                    file: `pages/_page-${generator.pageType}.component.html`,
                    method: 'processHtml',
                    template: true,
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.component.html`
                },
                {
                    file: 'pages/_index.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/index.ts`
                },
                {
                    file: 'pages/_page.module.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.module.ts`
                },

                {
                    file: 'pages/_page.model.ts',
                    renameTo: generator => `pages/${generator.pageSetFolder}/${generator.pageName}.model.ts`
                }
            ]
        }
    ],
    test: [
        {
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: `spec/app/pages/_page-${generator.pageType}.component.spec.ts`,
                renameTo: generator => `spec/app/pages/${generator.pageSetFolder}/${generator.pageName}.component.spec.ts`
            }]
        },
        {
            condition: generator => generator.protractorTests,
            path: CLIENT_TEST_SRC_DIR,
            templates: [{
                file: 'e2e/pages/_page.spec.ts',
                renameTo: generator => `e2e/pages/${generator.pageName}.spec.ts`
            }]
        }
    ]
};

module.exports = {
    writeFiles,
    serverFiles,
    angularjsFiles,
    angularFiles
};

function writeFiles() {
    return {

        readConf() {

            // read config from .yo-rc.json
            this.baseName = this.jhipsterAppConfig.baseName;
            this.packageName = this.jhipsterAppConfig.packageName;
            this.packageFolder = this.jhipsterAppConfig.packageFolder;
            this.clientFramework = this.jhipsterAppConfig.clientFramework;
            this.clientPackageManager = this.jhipsterAppConfig.clientPackageManager;
            this.buildTool = this.jhipsterAppConfig.buildTool;

            // use function in generator-base.js from generator-jhipster
            this.angularAppName = this.getAngularAppName();

            // use constants from generator-constants.js
            const javaDir = `${constants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`;
            const resourceDir = constants.SERVER_MAIN_RES_DIR;
            const webappDir = constants.CLIENT_MAIN_SRC_DIR;

            // variable from questions
            //this.message = this.props.pageSet;

            // show all variables
            this.log('\n--- some config read from config ---');
            this.log(`baseName=${this.baseName}`);
            this.log(`packageName=${this.packageName}`);
            this.log(`clientFramework=${this.clientFramework}`);
            this.log(`clientPackageManager=${this.clientPackageManager}`);
            this.log(`buildTool=${this.buildTool}`);

            this.log('\n--- some function ---');
            this.log(`angularAppName=${this.angularAppName}`);

            this.log('\n--- some const ---');
            this.log(`javaDir=${javaDir}`);
            this.log(`resourceDir=${resourceDir}`);
            this.log(`webappDir=${webappDir}`);

            this.log('\n--- variables from questions ---');
            this.log(`\npageSet=${this.pageSet}`);
            this.log(`\nnewPageSet=${this.newPageSet}`);
            this.log(`\npageType=${this.pageType}`);
            this.log(`\npageName=${this.pageName}`);
            this.log(`\nfuck=${this.pageType !== 'clientOnly'}`);

            this.log('------\n');

        },

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

            // write server side files
            this.writeFilesToDisk(serverFiles, this, false, SERVER_TEMPLATES_DIR);
        },

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

            if (this.clientFramework === 'angular1') {
                // write client side files for angular 1.x
                this.writeFilesToDisk(angularjsFiles, this, false, CLIENT_NG1_TEMPLATES_DIR);
            } else {
                // write client side files for angular 2.x +
                this.writeFilesToDisk(angularFiles, this, false, CLIENT_NG2_TEMPLATES_DIR);
            }

            this.addElementToMenu(this.pageSetRouterState+'-'+this.pageRouterState, this.pageGlyphIcon, this.enableTranslation, this.clientFramework);

            // Copy for each
            if (this.enableTranslation) {
                const languages = this.languages || this.getAllInstalledLanguages();
                languages.forEach((language) => {
                    try {
                        this.template(`${CLIENT_I18N_TEMPLATES_DIR}/i18n/_page_${language}.json`, `${CLIENT_MAIN_SRC_DIR}i18n/${language}/${this.pageInstance}.json`);
                        this.addEntityTranslationKey(this.pageSetTranslation, this.pageSetClass, language);
                        this.addEntityTranslationKey(this.pageNameTranslationKey, this.pageClass, language);
                    } catch (e) {
                        // An exception is thrown if the folder doesn't exist
                        // do nothing
                    }
                });
            }
        }
    };
}
<|endoftext|>


<commit_before>const fountain = require('fountain-generator');
const version = require('../../package.json').version;

module.exports = fountain.Base.extend({
  prompting: {
    fountain() {
      this.options.framework = 'react';
      return this.fountainPrompting();
    },

    sample() {
      this.option('sample', {type: Boolean, required: false});

      const prompts = {
        when: !this.options.sample,
        type: 'list',
        name: 'sample',
        message: 'Do you want a sample app?',
        choices: [
          {name: 'A working landing page', value: 'techs'},
          {name: 'Just a Hello World', value: 'hello'},
          {name: 'Redux TodoMVC', value: 'todoMVC'}
        ]
      };

      return this.prompt(prompts).then(props => {
        Object.assign(this.props, props);
      });
    }
  },

  configuring: {
    config() {
      this.config.set('version', version);
      this.config.set('props', this.props);
    },

    pkg() {
      this.mergeJson('package.json', {
        dependencies: {
          'react': '^15.0.1',
          'react-dom': '^15.0.1'
        }
      });

      this.mergeJson('package.json', {
        devDependencies: {
          'react-addons-test-utils': '^15.0.1'
        }
      });
    },

    babel() {
      if (this.props.js !== 'typescript') {
        this.mergeJson('.babelrc', {
          presets: ['react']
        });
      }
    }
  },

  composing() {
    const options = {
      framework: this.props.framework,
      modules: this.props.modules,
      js: this.props.js,
      css: this.props.css,
      sample: this.props.sample
    };

    const modules = this.props.sample === 'todoMVC' ? `/${this.props.modules === 'inject' ? 'inject' : 'modules'}` : '';

    this.composeWith(`fountain-react:${this.props.sample}`, {options}, {
      local: require.resolve(`../${this.props.sample}${modules}`)
    });
    this.composeWith('fountain-gulp', {options}, {
      local: require.resolve('generator-fountain-gulp/generators/app')
    });
  },

  writing() {
    this.copyTemplate('src/index.html', 'src/index.html');
  }
});
<commit_msg>Add router option in prompt and deps<commit_after>const fountain = require('fountain-generator');
const version = require('../../package.json').version;

module.exports = fountain.Base.extend({
  prompting: {
    fountain() {
      this.options.framework = 'react';
      return this.fountainPrompting();
    },

    sample() {
      this.option('sample', {type: Boolean, required: false});

      const prompts = [{
        when: !this.options.sample,
        type: 'list',
        name: 'sample',
        message: 'Do you want a sample app?',
        choices: [
          {name: 'A working landing page', value: 'techs'},
          {name: 'Just a Hello World', value: 'hello'},
          {name: 'Redux TodoMVC', value: 'todoMVC'}
        ]
      }, {
        when: !this.options.router,
        type: 'list',
        name: 'router',
        message: 'Would you like a router?',
        choices: [
          {name: 'React router', value: 'router'},
          {name: 'None', value: 'none'}
        ]
      }];

      return this.prompt(prompts).then(props => {
        Object.assign(this.props, props);
      });
    }
  },

  configuring: {
    config() {
      this.config.set('version', version);
      this.config.set('props', this.props);
    },

    pkg() {
      this.mergeJson('package.json', {
        dependencies: {
          'react': '^15.0.1',
          'react-dom': '^15.0.1'
        }
      });

      if (this.props.router === 'router') {
        if (this.props.modules === 'inject') {
          this.mergeJson('package.json', {
            dependencies: {
              'react-router': 'https://cdnjs.cloudflare.com/ajax/libs/react-router/2.4.1/ReactRouter.min.js'
            }
          });
        } else {
          this.mergeJson('package.json', {
            dependencies: {
              'react-router': '^2.4.0'
            }
          });
        }
      }

      this.mergeJson('package.json', {
        devDependencies: {
          'react-addons-test-utils': '^15.0.1'
        }
      });
    },

    babel() {
      if (this.props.js !== 'typescript') {
        this.mergeJson('.babelrc', {
          presets: ['react']
        });
      }
    }
  },

  composing() {
    const options = {
      framework: this.props.framework,
      modules: this.props.modules,
      js: this.props.js,
      css: this.props.css,
      router: this.props.router,
      sample: this.props.sample
    };

    const modules = this.props.sample === 'todoMVC' ? `/${this.props.modules === 'inject' ? 'inject' : 'modules'}` : '';

    this.composeWith(`fountain-react:${this.props.sample}`, {options}, {
      local: require.resolve(`../${this.props.sample}${modules}`)
    });
    this.composeWith('fountain-gulp', {options}, {
      local: require.resolve('generator-fountain-gulp/generators/app')
    });
  },

  writing() {
    this.copyTemplate('src/index.html', 'src/index.html');
  }
});
<|endoftext|>


<commit_before>'use strict';

const fountain = require('fountain-generator');

module.exports = fountain.Base.extend({
  prompting() {
    this.options.modules = 'inject';
    this.fountainPrompting();
  },

  configuring: {
    pkg() {
      let dependencies;
      let devDependencies = {};

      this.updateJson('package.json', function (packageJson) {
        dependencies = packageJson.dependencies;
        delete packageJson.dependencies;
        return packageJson;
      });

      const pkg = {
        devDependencies: {
          'gulp-inject': '^3.0.0',
          'main-bower-files': '^2.9.0',
          wiredep: '^2.2.2'
        }
      };

      if (this.props.framework === 'angular1') {
        pkg.devDependencies['gulp-angular-filesort'] = '^1.1.1';
      }

      if (this.props.js === 'babel' || this.props.js === 'js' && this.props.framework === 'react') {
        pkg.devDependencies['gulp-babel'] = '^6.1.0';
      }

      if (this.props.js === 'typescript') {
        pkg.devDependencies['gulp-typescript'] = '^2.10.0';
      }

      this.mergeJson('package.json', pkg);

      if (this.props.framework === 'react') {
        delete dependencies['react-dom'];
      }

      if (this.props.framework === 'angular1') {
        devDependencies['angular-mocks'] = dependencies.angular;
      }

      this.mergeJson('bower.json', {
        name: 'fountain-inject',
        version: '0.0.1',
        dependencies: dependencies,
        devDependencies: devDependencies
      });
    }
  },

  writing: {
    gulp() {
      this.copyTemplate(
        this.templatePath('gulp_tasks'),
        this.destinationPath('gulp_tasks'),
        { css: this.props.css }
      );
    },

    indexHtml() {
      this.replaceInFile('src/index-head.html', 'src/index.html', /<\/head>/);
      this.replaceInFile('src/index-footer.html', 'src/index.html', /<\/html>/);
    }
  },

  installing() {
    this.bowerInstall();
  }
});
<commit_msg>add regex transformations to simplify module management in sources<commit_after>'use strict';

const fountain = require('fountain-generator');
const path = require('path');

module.exports = fountain.Base.extend({
  prompting() {
    this.options.modules = 'inject';
    this.fountainPrompting();
  },

  configuring: {
    pkg() {
      let dependencies;
      let devDependencies = {};

      this.updateJson('package.json', function (packageJson) {
        dependencies = packageJson.dependencies;
        delete packageJson.dependencies;
        return packageJson;
      });

      const pkg = {
        devDependencies: {
          'gulp-inject': '^3.0.0',
          'main-bower-files': '^2.9.0',
          wiredep: '^2.2.2'
        }
      };

      if (this.props.framework === 'angular1') {
        pkg.devDependencies['gulp-angular-filesort'] = '^1.1.1';
      }

      if (this.props.js === 'babel' || this.props.js === 'js' && this.props.framework === 'react') {
        pkg.devDependencies['gulp-babel'] = '^6.1.0';
      }

      if (this.props.js === 'typescript') {
        pkg.devDependencies['gulp-typescript'] = '^2.10.0';
      }

      this.mergeJson('package.json', pkg);

      if (this.props.framework === 'react') {
        delete dependencies['react-dom'];
      }

      if (this.props.framework === 'angular1') {
        devDependencies['angular-mocks'] = dependencies.angular;
      }

      this.mergeJson('bower.json', {
        name: 'fountain-inject',
        version: '0.0.1',
        dependencies: dependencies,
        devDependencies: devDependencies
      });
    }
  },

  writing: {
    transforms() {
      this.replaceInFiles('src/**/*.js', (content, fileName) => {
        const baseName = path.basename(fileName, '.js');
        const componentName = baseName.substr(0, 1).toUpperCase() + baseName.substr(1);
        // remove es2015 imports
        let result = content.replace(/import .*\n\n?/g, '');
        // remove commonjs requires
        result = result.replace(/.*require\(.*\);\n\n?/g, '');
        // remove exports of es2015 React components
        result = result.replace(
          /export class ([^\s]*) extends Component/g,
          'class $1 extends React.Component'
        );
        // remove exports of createClass React components
        result = result.replace(
          /module\.exports = React\.createClass/,
          `window.${componentName} = React.createClass`
        );
        return result;
      });
    },

    gulp() {
      this.copyTemplate(
        this.templatePath('gulp_tasks'),
        this.destinationPath('gulp_tasks'),
        { css: this.props.css }
      );
    },

    indexHtml() {
      this.replaceInFileWithTemplate(
        'src/index-head.html',
        'src/index.html',
        /<\/head>/
      );
      this.replaceInFileWithTemplate(
        'src/index-footer.html',
        'src/index.html',
        /<\/html>/
      );
    }
  },

  installing() {
    this.bowerInstall();
  }
});
<|endoftext|>


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

module.exports = yeoman.Base.extend({
  initializing: function () {
    //
    // Get command-line argument, if any
    //
    this.argument('arg', {type: String, required: false});

    //
    // Get name of current directory
    //
    this.dir = path.basename(process.cwd());
  },

  prompting: function () {
    this.log(yosay(
      'Welcome to the ' + chalk.green('angular-modsmith') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'argName',
        message: chalk.yellow('Package name :'),
        default: this.arg || this.dir
      },
      {
        type: 'input',
        name: 'argDesc',
        message: chalk.yellow('Package description:'),
        default: 'TODO: Add package description.'
      },
      {
        type: 'input',
        name: 'argVersion',
        message: chalk.yellow('Package version:'),
        default: '0.0.1'
      },
      {
        type: 'input',
        name: 'argRepo',
        message: chalk.yellow('Package Repository:')
      },
      {
        type: 'list',
        name: 'argLicense',
        choices : [
          {
            name  : 'Apache License 2.0',
            value : 'Apache-2.0',
            short : 'Apache-2.0'
          },
          {
            name  : 'BSD 2-clause "Simplified" License',
            value : 'BSD-2-Clause',
            short : 'BSD-2-Clause'
          },
          {
            name  : 'BSD 3-clause "New" or "Revised" License',
            value : 'BSD-3-Clause',
            short : 'BSD-3-Clause'
          },
          {
            name  : 'GNU General Public License v2.0 only',
            value : 'GPL-2.0',
            short : 'GPL-2.0'
          },
          {
            name  : 'GNU General Public License v3.0 only',
            value : 'GPL-3.0',
            short : 'GPL-3.0'
          },
          {
            name  : 'GNU Lesser General Public License v2.1 only',
            value : 'LGPL-2.1',
            short : 'LGPL-2.1'
          },
          {
            name  : 'GNU Lesser General Public License v3.0 only',
            value : 'LGPL-3.0',
            short : 'LGPL-3.0'
          },
          {
            name  : 'MIT License',
            value : 'MIT',
            short : 'MIT'
          },
          {
            name  : 'Other License',
            value : 'Other',
            short : 'Other'
          }
        ],
        message: chalk.yellow('Select applicable license:')
      },
      {
        type: 'input',
        name: 'argKeywords',
        message: chalk.yellow('Package keywords [comma-separated]:'),
        filter: function (str) {
          return str
                  .trim()
                  .replace(/\s*,\s*/g, ',')   // Remove space around commas
                  .replace(/,+/g, ',')        // Remove consecutive commas
                  .replace(/(^,)|(,$)/g, '')  // Remove leading & trailing commas
                  .split(/,/g);
        }
      },
      {
        type: 'input',
        name: 'argAuthorName',
        message: chalk.yellow('Author\'s name:'),
        default: this.user.git.name
      },
      {
        type: 'input',
        name: 'argAuthorEmail',
        message: chalk.yellow('Author\'s email:'),
        default: this.user.git.email
      },
      {
        type: 'input',
        name: 'argAuthorHome',
        message: chalk.yellow('Author\'s homepage:')
      }
    ];

    return this.prompt(prompts).then(function (props) {
      this.props = {
        pkg : {
          name  : {
            orig    : props.argName,
            slug    : to.slug(props.argName),
            camel   : to.camel(props.argName)
          },
          desc      : props.argDesc,
          version   : props.argVersion,
          repo      : props.argRepo,
          license   : props.argLicense,
          keywords  : props.argKeywords
        },
        author  : {
          name  : props.argAuthorName,
          email : props.argAuthorEmail,
          url   : props.argAuthorHome
        }
      };
    }.bind(this));
  },

  writing: {
    //
    // Copy base configuration files
    //
    base: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_npmignore'),
        this.destinationPath('.npmignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gitattributes'),
        this.destinationPath('.gitattributes'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_editorconfig'),
        this.destinationPath('.editorconfig'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_eslintignore'),
        this.destinationPath('.eslintignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_eslintrc.js'),
        this.destinationPath('.eslintrc.js'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js'),
        this.props);
    },

    //
    // Copy LICENSE
    //
    license: function () {
      var licenseTpl = '';

      switch (this.props.pkg.license) {
        case 'Apache-2.0':
          licenseTpl = 'licenses/LICENSE_APACHE_2_0';
          break;

        case 'BSD-2-Clause':
          licenseTpl = 'licenses/LICENSE_BSD_2_CLAUSE';
          break;

        case 'BSD-3-Clause':
          licenseTpl = 'licenses/LICENSE_BSD_3_CLAUSE';
          break;

        case 'GPL-2.0':
          licenseTpl = 'licenses/LICENSE_GPL_2_0';
          break;

        case 'GPL-3.0':
          licenseTpl = 'licenses/LICENSE_GPL_3_0';
          break;

        case 'LGPL-2.1':
          licenseTpl = 'licenses/LICENSE_LGPL_2_1';
          break;

        case 'LGPL-3.0':
          licenseTpl = 'licenses/LICENSE_LGPL_3_0';
          break;

        case 'MIT':
          licenseTpl = 'licenses/LICENSE_MIT';
          break;

        default:
          licenseTpl = 'licenses/LICENSE_OTHER';
          break;
      }

      this.fs.copyTpl(
        this.templatePath(licenseTpl),
        this.destinationPath('LICENSE'),
        this.props);
    }
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>gen: install: Save configuration<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var to = require('to-case');

module.exports = yeoman.Base.extend({
  initializing: function () {
    //
    // Get command-line argument, if any
    //
    this.argument('arg', {type: String, required: false});

    //
    // Get name of current directory
    //
    this.dir = path.basename(process.cwd());
  },

  prompting: function () {
    this.log(yosay(
      'Welcome to the ' + chalk.green('angular-modsmith') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'argName',
        message: chalk.yellow('Package name :'),
        default: this.arg || this.dir
      },
      {
        type: 'input',
        name: 'argDesc',
        message: chalk.yellow('Package description:'),
        default: 'TODO: Add package description.'
      },
      {
        type: 'input',
        name: 'argVersion',
        message: chalk.yellow('Package version:'),
        default: '0.0.1'
      },
      {
        type: 'input',
        name: 'argRepo',
        message: chalk.yellow('Package Repository:')
      },
      {
        type: 'list',
        name: 'argLicense',
        choices : [
          {
            name  : 'Apache License 2.0',
            value : 'Apache-2.0',
            short : 'Apache-2.0'
          },
          {
            name  : 'BSD 2-clause "Simplified" License',
            value : 'BSD-2-Clause',
            short : 'BSD-2-Clause'
          },
          {
            name  : 'BSD 3-clause "New" or "Revised" License',
            value : 'BSD-3-Clause',
            short : 'BSD-3-Clause'
          },
          {
            name  : 'GNU General Public License v2.0 only',
            value : 'GPL-2.0',
            short : 'GPL-2.0'
          },
          {
            name  : 'GNU General Public License v3.0 only',
            value : 'GPL-3.0',
            short : 'GPL-3.0'
          },
          {
            name  : 'GNU Lesser General Public License v2.1 only',
            value : 'LGPL-2.1',
            short : 'LGPL-2.1'
          },
          {
            name  : 'GNU Lesser General Public License v3.0 only',
            value : 'LGPL-3.0',
            short : 'LGPL-3.0'
          },
          {
            name  : 'MIT License',
            value : 'MIT',
            short : 'MIT'
          },
          {
            name  : 'Other License',
            value : 'Other',
            short : 'Other'
          }
        ],
        message: chalk.yellow('Select applicable license:')
      },
      {
        type: 'input',
        name: 'argKeywords',
        message: chalk.yellow('Package keywords [comma-separated]:'),
        filter: function (str) {
          return str
                  .trim()
                  .replace(/\s*,\s*/g, ',')   // Remove space around commas
                  .replace(/,+/g, ',')        // Remove consecutive commas
                  .replace(/(^,)|(,$)/g, '')  // Remove leading & trailing commas
                  .split(/,/g);
        }
      },
      {
        type: 'input',
        name: 'argAuthorName',
        message: chalk.yellow('Author\'s name:'),
        default: this.user.git.name
      },
      {
        type: 'input',
        name: 'argAuthorEmail',
        message: chalk.yellow('Author\'s email:'),
        default: this.user.git.email
      },
      {
        type: 'input',
        name: 'argAuthorHome',
        message: chalk.yellow('Author\'s homepage:')
      }
    ];

    return this.prompt(prompts).then(function (props) {
      this.props = {
        pkg : {
          name  : {
            orig    : props.argName,
            slug    : to.slug(props.argName),
            camel   : to.camel(props.argName)
          },
          desc      : props.argDesc,
          version   : props.argVersion,
          repo      : props.argRepo,
          license   : props.argLicense,
          keywords  : props.argKeywords
        },
        author  : {
          name  : props.argAuthorName,
          email : props.argAuthorEmail,
          url   : props.argAuthorHome
        }
      };
    }.bind(this));
  },

  writing: {
    //
    // Copy base configuration files
    //
    base: function () {
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_npmignore'),
        this.destinationPath('.npmignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gitattributes'),
        this.destinationPath('.gitattributes'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('README.md'),
        this.destinationPath('README.md'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_editorconfig'),
        this.destinationPath('.editorconfig'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_eslintignore'),
        this.destinationPath('.eslintignore'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_eslintrc.js'),
        this.destinationPath('.eslintrc.js'),
        this.props);

      this.fs.copyTpl(
        this.templatePath('_gulpfile.js'),
        this.destinationPath('gulpfile.js'),
        this.props);
    },

    //
    // Copy LICENSE
    //
    license: function () {
      var licenseTpl = '';

      switch (this.props.pkg.license) {
        case 'Apache-2.0':
          licenseTpl = 'licenses/LICENSE_APACHE_2_0';
          break;

        case 'BSD-2-Clause':
          licenseTpl = 'licenses/LICENSE_BSD_2_CLAUSE';
          break;

        case 'BSD-3-Clause':
          licenseTpl = 'licenses/LICENSE_BSD_3_CLAUSE';
          break;

        case 'GPL-2.0':
          licenseTpl = 'licenses/LICENSE_GPL_2_0';
          break;

        case 'GPL-3.0':
          licenseTpl = 'licenses/LICENSE_GPL_3_0';
          break;

        case 'LGPL-2.1':
          licenseTpl = 'licenses/LICENSE_LGPL_2_1';
          break;

        case 'LGPL-3.0':
          licenseTpl = 'licenses/LICENSE_LGPL_3_0';
          break;

        case 'MIT':
          licenseTpl = 'licenses/LICENSE_MIT';
          break;

        default:
          licenseTpl = 'licenses/LICENSE_OTHER';
          break;
      }

      this.fs.copyTpl(
        this.templatePath(licenseTpl),
        this.destinationPath('LICENSE'),
        this.props);
    }
  },

  install: function () {
    this.config.set('pkg', this.props.pkg);
    this.config.set('author', this.props.author);

    this.installDependencies();
  }
});
<|endoftext|>


<commit_before>var generators = require('yeoman-generator'),
    glob = require('glob');

module.exports = generators.Base.extend({

  initializing: {

    init: function() {
      this.params = this.params || {};
    }

  },

  prompting: {

    appName: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'appName',
        message: 'Your project name',
        default: this.appname
      }, function(answers) {
        this.params.appName = answers.appName;
        done();
      }.bind(this));
    },

    description: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'description',
        message: 'Your project description',
        default: 'Project description'
      }, function(answers) {
        this.params.description = answers.description;
        done();
      }.bind(this));
    },

    tags: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'tags',
        message: 'Your project tags',
        default: this.params.appName + ', angular, corbel, devialab'
      }, function(answers) {
        this.params.tags = answers.tags;
        done();
      }.bind(this));
    },

    corbelDomain: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'domain',
        message: 'corbel.io domain',
        default: this.params.appName
      }, function(answers) {
        this.params.domain = answers.domain;
        done();
      }.bind(this));
    },

    corbelClientId: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'clientId',
        message: 'corbel.io clientId',
        default: 'clientId'
      }, function(answers) {
        this.params.clientId = answers.clientId;
        done();
      }.bind(this));
    },

    corbelClientSecret: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'clientSecret',
        message: 'corbel.io clientSecret',
        default: 'clientSecret'
      }, function(answers) {
        this.params.clientSecret = answers.clientSecret;
        done();
      }.bind(this));
    }

  },

  configuring: {

  },

  default: {

  },

  writing: {

    /**
     * Write all templates files (*.tpl) using `prompting` params phase
     */
    writeTemplates: function() {
      glob(this.templatePath('**/*.tpl'), function (er, files) {

        files.forEach(function(file) {

          var src = file.split('app/templates/');
          src = src[1];

          this.fs.copyTpl(
            this.templatePath(src),
            this.destinationPath(src.replace('.tpl', '')),
            this.params
          );

        }.bind(this));

      }.bind(this));

    },

    /**
     * Copy all normal files to target folder
     */
    copyScaffolding: function() {

      var ncp = require('ncp').ncp;

      ncp.limit = 16;
      var done = this.async();
      ncp(this.sourceRoot(), this.destinationRoot(), {
        filter: function(fileName) {
          return !fileName.endsWith('.tpl');
        }
      }, function(err) {
        if (err) {
          return console.error(err);
        }
        console.log('done!');
        done();
      });

    }

  },

  conflicts: {

  },

  install: {

    npm: function() {
      this.npmInstall();
    },

    bower: function() {
      this.bowerInstall();
    }

  },

  end: {

  }

});
<commit_msg>check undefined<commit_after>var generators = require('yeoman-generator'),
    glob = require('glob');

module.exports = generators.Base.extend({

  initializing: {

    init: function() {
      this.params = this.params || {};
    }

  },

  prompting: {

    appName: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'appName',
        message: 'Your project name',
        default: this.appname
      }, function(answers) {
        this.params.appName = answers.appName;
        done();
      }.bind(this));
    },

    description: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'description',
        message: 'Your project description',
        default: 'Project description'
      }, function(answers) {
        this.params.description = answers.description;
        done();
      }.bind(this));
    },

    tags: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'tags',
        message: 'Your project tags',
        default: this.params.appName + ', angular, corbel, devialab'
      }, function(answers) {
        this.params.tags = answers.tags;
        done();
      }.bind(this));
    },

    corbelDomain: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'domain',
        message: 'corbel.io domain',
        default: this.params.appName
      }, function(answers) {
        this.params.domain = answers.domain;
        done();
      }.bind(this));
    },

    corbelClientId: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'clientId',
        message: 'corbel.io clientId',
        default: 'clientId'
      }, function(answers) {
        this.params.clientId = answers.clientId;
        done();
      }.bind(this));
    },

    corbelClientSecret: function() {
      var done = this.async();
      this.prompt({
        type: 'input',
        name: 'clientSecret',
        message: 'corbel.io clientSecret',
        default: 'clientSecret'
      }, function(answers) {
        this.params.clientSecret = answers.clientSecret;
        done();
      }.bind(this));
    }

  },

  configuring: {

  },

  default: {

  },

  writing: {

    /**
     * Write all templates files (*.tpl) using `prompting` params phase
     */
    writeTemplates: function() {
      glob(this.templatePath('**/*.tpl'), function (er, files) {

        files.forEach(function(file) {

          var src = file.split('app/templates/');
          src = src[1];

          this.fs.copyTpl(
            this.templatePath(src),
            this.destinationPath(src.replace('.tpl', '')),
            this.params
          );

        }.bind(this));

      }.bind(this));

    },

    /**
     * Copy all normal files to target folder
     */
    copyScaffolding: function() {

      var ncp = require('ncp').ncp;

      ncp.limit = 16;
      var done = this.async();
      ncp(this.sourceRoot(), this.destinationRoot(), {
        filter: function(fileName) {
          return fileName && fileName.endsWith && !fileName.endsWith('.tpl');
        }
      }, function(err) {
        if (err) {
          return console.error(err);
        }
        console.log('done!');
        done();
      });

    }

  },

  conflicts: {

  },

  install: {

    npm: function() {
      this.npmInstall();
    },

    bower: function() {
      this.bowerInstall();
    }

  },

  end: {

  }

});
<|endoftext|>


<commit_before>'use strict';

var util = require('util'),
  path = require('path'),
  chalk = require('chalk'),
  yeoman = require('yeoman-generator'),
  yosay = require('yosay'),
  _ = require('lodash-node'),
  prompts = require('../prompts.js');

// Extend Base generator
var FactoryComponentGenerator = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);
    this.argument('componentName', { type: String, required: true });
    this.componentName = this.componentName;
  },
  info: function () {
    this.log(chalk.yellow(
      'Out of the box I create a self-contained component,\n' +
      'with html, css, & js placeholder files.\n'
    ));
  },
  promptUser: function () {

    var done = this.async();
    // Retrieved from command line arguments
    this.componentDir = this.componentName;

    this.prompt(prompts, function (props) {
      this.props = props;
      this.hasContexts = _.includes(props.folders, 'contextsDir');

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

  },
  confirmInfo: function () {
    var msg = '';

    for (var key in this.props) {
      msg += '\n' + _.startCase(key) + ':\t' + this.props[key];
    }

    this.log(chalk.yellow(
      '\n---- DETAILS----',
      '\nComponent Name:\t', this.componentDir,
      msg, '\n'
    ));

  },
  createFolders: function () {

    // Make base component folder
    this.mkdir(this.componentDir);

    if (_.includes(this.props.folders, 'mediaDir')) {
      this.mkdir(this.componentDir + '/media');
    }

    if (this.hasContexts) {
      this.mkdir(this.componentDir + '/' + this.props.contextFolderName);
    }
  },
  createFiles: function () {
    var data,
        contextsDirs,
        componentDir = this.componentDir,
        contextsDir = componentDir + '/' + this.props.contextFolderName + '/',
        singleFolderPath = contextsDir + this.props.contextName;

    data = {
      componentName: this.componentDir,
      desktopOnlyDisplay: this.props.desktopOnlyDisplay,
      controllerName: _.capitalize(_.camelCase(this.componentDir)),
      tag: this.props.containerTag
    };

    // Files that must be created
    this.template('_index.html', componentDir + '/' + this.props.markupFilename, data);
    this.template('_index.js', componentDir + '/index.js', data);
    this.template('_print.css', componentDir + '/print.css', data);
    this.log(chalk.blue('Basic Files Created.'));

    if (this.props.numOfContextFolders > 1) {
      contextsDirs = this.props.contextNames.split(',');

      for (var folder in contextsDirs) {
        var dir = contextsDir + contextsDirs[folder];
        createCss(this, dir, data);
      }
      this.log('Created Contexts:\t', chalk.underline.blue(contextsDirs));
    } else if (this.props.numOfContextFolders == 1) {
      createCss(this, singleFolderPath, data);
      this.log(chalk.blue('Context Needed.'));
    } else {
      createCss(this, componentDir, data);
      this.log(chalk.blue('No Context Needed.'));
    }
  }

});

// Creates Css files for the specified ranges
function createCss(self, dir, data) {
  var newData = (data.desktopOnlyDisplay) ? _.omit(data, 'desktopOnlyDisplay') : data;

  if (self.props.mediaQuery) {
    self.template('_all.css', dir + '/' + '0-' + self.props.mobileRange + '.css', newData);
    self.template('_all.css', dir + '/' + self.props.mobileRange + '-' + self.props.tabletRange + '.css', newData);
    self.template('_all.css', dir + '/' + self.props.tabletRange + '+' + '.css', data);
  } else if (dir !== 'undefined') {
    // No media queries required but context required
    self.template('_all.css', dir + '/all.css', data);
  } else {
    // No media queries required
    self.template('_all.css', self.componentDir + '/all.css', data);
  }

}

module.exports = FactoryComponentGenerator;
<commit_msg>Changed `index.js` to `client.js`<commit_after>'use strict';

var util = require('util'),
  path = require('path'),
  chalk = require('chalk'),
  yeoman = require('yeoman-generator'),
  yosay = require('yosay'),
  _ = require('lodash-node'),
  prompts = require('../prompts.js');

// Extend Base generator
var FactoryComponentGenerator = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);
    this.argument('componentName', { type: String, required: true });
    this.componentName = this.componentName;
  },
  info: function () {
    this.log(chalk.yellow(
      'Out of the box I create a self-contained component,\n' +
      'with html, css, & js placeholder files.\n'
    ));
  },
  promptUser: function () {

    var done = this.async();
    // Retrieved from command line arguments
    this.componentDir = this.componentName;

    this.prompt(prompts, function (props) {
      this.props = props;
      this.hasContexts = _.includes(props.folders, 'contextsDir');

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

  },
  confirmInfo: function () {
    var msg = '';

    for (var key in this.props) {
      msg += '\n' + _.startCase(key) + ':\t' + this.props[key];
    }

    this.log(chalk.yellow(
      '\n---- DETAILS----',
      '\nComponent Name:\t', this.componentDir,
      msg, '\n'
    ));

  },
  createFolders: function () {

    // Make base component folder
    this.mkdir(this.componentDir);

    if (_.includes(this.props.folders, 'mediaDir')) {
      this.mkdir(this.componentDir + '/media');
    }

    if (this.hasContexts) {
      this.mkdir(this.componentDir + '/' + this.props.contextFolderName);
    }
  },
  createFiles: function () {
    var data,
        contextsDirs,
        componentDir = this.componentDir,
        contextsDir = componentDir + '/' + this.props.contextFolderName + '/',
        singleFolderPath = contextsDir + this.props.contextName;

    data = {
      componentName: this.componentDir,
      desktopOnlyDisplay: this.props.desktopOnlyDisplay,
      controllerName: _.capitalize(_.camelCase(this.componentDir)),
      tag: this.props.containerTag
    };

    // Files that must be created
    this.template('_index.html', componentDir + '/' + this.props.markupFilename, data);
    this.template('_index.js', componentDir + '/client.js', data);
    this.template('_print.css', componentDir + '/print.css', data);
    this.log(chalk.blue('Basic Files Created.'));

    if (this.props.numOfContextFolders > 1) {
      contextsDirs = this.props.contextNames.split(',');

      for (var folder in contextsDirs) {
        var dir = contextsDir + contextsDirs[folder];
        createCss(this, dir, data);
      }
      this.log('Created Contexts:\t', chalk.underline.blue(contextsDirs));
    } else if (this.props.numOfContextFolders == 1) {
      createCss(this, singleFolderPath, data);
      this.log(chalk.blue('Context Needed.'));
    } else {
      createCss(this, componentDir, data);
      this.log(chalk.blue('No Context Needed.'));
    }
  }

});

// Creates Css files for the specified ranges
function createCss(self, dir, data) {
  var newData = (data.desktopOnlyDisplay) ? _.omit(data, 'desktopOnlyDisplay') : data;

  if (self.props.mediaQuery) {
    self.template('_all.css', dir + '/' + '0-' + self.props.mobileRange + '.css', newData);
    self.template('_all.css', dir + '/' + self.props.mobileRange + '-' + self.props.tabletRange + '.css', newData);
    self.template('_all.css', dir + '/' + self.props.tabletRange + '+' + '.css', data);
  } else if (dir !== 'undefined') {
    // No media queries required but context required
    self.template('_all.css', dir + '/all.css', data);
  } else {
    // No media queries required
    self.template('_all.css', self.componentDir + '/all.css', data);
  }

}

module.exports = FactoryComponentGenerator;
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var bootplate = require('../../common/bootplate-utils.js');
var chalk = require('chalk');

var EnyoGenerator = yeoman.generators.Base.extend({
	constructor: function () {
		this.cwd = process.cwd();
		try {
			yeoman.generators.Base.apply(this, arguments);
			this.options.namespace = "enyo";
			this.argument("path", {
				desc:"Project directory",
				type: String,
				required: true
			});
			this.option("mode", {
				alias: "m",
				desc: "Configuration mode of bootplate (onyx, moonstone, sunstone, garnet, or sampler)",
				type: String
			});
			this.option("build", {
				alias: "b",
				desc: "Version of bootplate and libraries to use (eg: --build=2.4.0)",
				type: String
			});
			this.option("latest", {
				alias: "l",
				desc: "Use the latest version of bootplate and libraries",
				type: Boolean
			});
			this.option("cordova", {
				desc: "Encapsulate bootplate within a Cordova project layer",
				type: Boolean
			});
			this.option("config", {
				alias: "c",
				desc: "Specify a JSON file which adds to or overrides build settings",
				type: String
			});
		} catch(e) {
			this.log(chalk.red(e));
			process.exit(1);
		}
	},

	initializing: function() {
		process.chdir(this.cwd);
		var valStrOpt = function(arg) {
			if(arg && typeof arg==="string") {
				return arg;
			} else {
				return undefined;
			}
		};
		this.param = {
			path: this.path,
			mode: valStrOpt(this.options["mode"]) || valStrOpt(this.options["m"]),
			version: valStrOpt(this.options["build"]) || valStrOpt(this.options["b"]),
			latest: this.options["latest"] || this.options["l"]
		};
		if(this.param.version==="latest" || this.param.version==="edge"
				 || this.param.version==="nightly") {
			//resolve keywords to latest boolean
			this.param.latest = true;
		}
		var conf = valStrOpt(this.options["config"]) || valStrOpt(this.options["c"]);
		if(conf) {
			try {
				var txt = fs.readFileSync(conf, {encoding:"utf8"});
				var obj = JSON.parse(txt);
				this.param.config = obj;
			} catch(e) {
				this.log(chalk.red("Unable to read/parse config JSON."));
				process.exit(2);
			}
		}
		this.action = "create";
		if(this.options["cordova"]) {
			this.action = "cordova";
		}
	},

	welcome: function() {
		// Have Yeoman greet the user.
		this.log(yosay(
			'Welcome to the Enyo bootplate generator!'
		));
	},

	writing: function() {
		var log = this.log;
		var done = this.async();
		bootplate[this.action](this.param, function(err, opts) {
			log(" ");
			if(err) {
				if(err.message) {
					log(err.message + "\n");
				}
				log(chalk.red("Error: Bootplate generation failed."));
			} else {
				log(chalk.green("Bootplate generation completed successfully"));
				log("Project available at " + path.resolve(opts.project || opts.path));
			}
			done();
		});
	}
});

module.exports = EnyoGenerator;
<commit_msg>NPM install if bootplate has a package.json<commit_after>'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var bootplate = require('../../common/bootplate-utils.js');
var chalk = require('chalk');

var EnyoGenerator = yeoman.generators.Base.extend({
	constructor: function () {
		this.cwd = process.cwd();
		try {
			yeoman.generators.Base.apply(this, arguments);
			this.options.namespace = "enyo";
			this.argument("path", {
				desc:"Project directory",
				type: String,
				required: true
			});
			this.option("mode", {
				alias: "m",
				desc: "Configuration mode of bootplate (onyx, moonstone, sunstone, garnet, or sampler)",
				type: String
			});
			this.option("build", {
				alias: "b",
				desc: "Version of bootplate and libraries to use (eg: --build=2.4.0)",
				type: String
			});
			this.option("latest", {
				alias: "l",
				desc: "Use the latest version of bootplate and libraries",
				type: Boolean
			});
			this.option("cordova", {
				desc: "Encapsulate bootplate within a Cordova project layer",
				type: Boolean
			});
			this.option("config", {
				alias: "c",
				desc: "Specify a JSON file which adds to or overrides build settings",
				type: String
			});
		} catch(e) {
			this.log(chalk.red(e));
			process.exit(1);
		}
	},

	initializing: function() {
		process.chdir(this.cwd);
		var valStrOpt = function(arg) {
			if(arg && typeof arg==="string") {
				return arg;
			} else {
				return undefined;
			}
		};
		this.param = {
			path: this.path,
			mode: valStrOpt(this.options["mode"]) || valStrOpt(this.options["m"]),
			version: valStrOpt(this.options["build"]) || valStrOpt(this.options["b"]),
			latest: this.options["latest"] || this.options["l"]
		};
		if(this.param.version==="latest" || this.param.version==="edge"
				 || this.param.version==="nightly") {
			//resolve keywords to latest boolean
			this.param.latest = true;
		}
		var conf = valStrOpt(this.options["config"]) || valStrOpt(this.options["c"]);
		if(conf) {
			try {
				var txt = fs.readFileSync(conf, {encoding:"utf8"});
				var obj = JSON.parse(txt);
				this.param.config = obj;
			} catch(e) {
				this.log(chalk.red("Unable to read/parse config JSON."));
				process.exit(2);
			}
		}
		this.action = "create";
		if(this.options["cordova"]) {
			this.action = "cordova";
		}
	},

	welcome: function() {
		// Have Yeoman greet the user.
		this.log(yosay(
			'Welcome to the Enyo bootplate generator!'
		));
	},

	writing: function() {
		var self = this;
		var done = this.async();
		bootplate[this.action](this.param, function(err, opts) {
			self.log(" ");
			if(err) {
				if(err.message) {
					self.log(err.message + "\n");
				}
				self.log(chalk.red("Error: Bootplate generation failed."));
				done();
			} else {
				var project = path.resolve(opts.project || opts.path);
				var success = function() {
					self.log(chalk.green("Bootplate generation completed successfully"));
					self.log("Project available at " + project);
					done();
				}
				if(fs.existsSync(path.join(project, "package.json"))) {
					self.installDependencies({
						bower: false,
						npm: true,
						callback: success
					});
				} else {
					success();
				}
			}
		});
	}
});

module.exports = EnyoGenerator;
<|endoftext|>


<commit_before>function toggleClass() {
    var theme = document.getElementById("theme-area");
    theme.classList.toggle("active");
}
function setTheme(btn) {
    var newTheme = "cld-video-player-skin-" + btn.value;
    var oldTheme = "cld-video-player-skin-";
    var pagination = document.getElementById("video-pagination");
    if(btn.value == "dark") {
        oldTheme += "light";
        pagination.classList.remove("style01");
    }
    else {
        oldTheme += "dark";
        pagination.classList.add("style01");
    }
    var vplayers = document.getElementsByClassName("cld-video-player");
    for(var i = 0; i < vplayers.length; i++) {
        vplayers[i].classList.remove(oldTheme);
        vplayers[i].classList.add(newTheme);
    }
    toggleClass();
}

window.addEventListener('scroll',checkPosition,false);
function checkPosition()
{
    var themeArea = document.getElementById("theme-area");
    if(window.scrollY > 50)
    {
        themeArea.classList.add("scrolling");
    } else {
        themeArea.classList.remove("scrolling");
    }
}

function playerSizeChange(input) {
  var area = document.getElementById("video-area-adaptive");
  var border = document.getElementById("player-border");
  var val = input.value + "%";
  area.style.width = val;
  border.style.width = val;
  var pwidth = document.getElementById("player-width");
  pwidth.innerHTML = area.clientWidth;
}
function updateOnResize() {
  var width = demoplayer.videojs.videoWidth();
  var current = document.getElementById(width);
  var oldactive = document.getElementsByClassName("range-info active");
  for (var i = 0; i < oldactive.length; i++) {
    oldactive[i].setAttribute("class","range-info");
  }
  current.setAttribute("class","range-info active");
}
function requestResolution(btn) {
  console.log("requestResolution() ",btn.id, safari);
  if(!safari)
  {
    document.getElementById("checkbox").checked = false;
    document.getElementById("checkboxLabel").classList.add("disabled");
    for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (Number(btn.id) == qualityLevels[i].width);
    }
  }
}
function requestAuto(auto) {
  console.log("requestAuto() ",auto.checked);
  if(auto.checked) {
    for (var i = 0; i < qualityLevels.length; i++) {
        qualityLevels[i].enabled = true;
    }
  }
  document.getElementById("checkboxLabel").classList.toggle("disabled");
}

function changeOfResolution() {
  var index = qualityLevels.selectedIndex;
  var res = document.getElementById(qualityLevels[index].width);
  var old = document.getElementsByClassName("range-info second-hover");
  for (var i = 0; i < old.length; i++) {
    old[i].setAttribute("class","range-info");
  }
  res.setAttribute("class","range-info second-hover");
}

function setProfile(profile) {
  var elements = document.getElementsByClassName('range-info');
  var i = elements.length;

    while(i--) {
      console.log(elements[i].getElementsByClassName(profile.value).length);
        if(elements[i].getElementsByClassName(profile.value).length > 0)
          elements[i].setAttribute("class","range-info");
        else
          elements[i].setAttribute("class","range-info out-of-range");

    }
  document.getElementById("checkbox").checked = true;
  document.getElementById("checkboxLabel").classList.remove("disabled");
  demoplayer.source("kayak", { sourceTypes: ['hls'], transformation: {streaming_profile: profile.value } }).play();
}

var chrome   = navigator.userAgent.indexOf('Chrome') > -1;
var safari   = navigator.userAgent.indexOf("Safari") > -1;
if ((chrome) && (safari)) safari = false;

if(safari)
  document.getElementById("checkbox").disabled = true;

playerSizeChange(document.getElementById("player-slider"));

var cld = cloudinary.Cloudinary.new({ cloud_name: 'demo' });

var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);

var demoplayer = cld.videoPlayer('demo-adaptive-player');

var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });

demoplayer.source('kayak',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'full_hd' } });

function updateOnEvent(eventStr,automatic) {
  var list = document.getElementById('events-list');
  var entry = document.createElement('li');
  if(automatic)
      entry.className = "orange";
  entry.appendChild(document.createTextNode(eventStr));
  list.appendChild(entry);
  list.scrollTop = list.scrollHeight;
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var autoEventTypes = ['sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

var manualEventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek'];

autoEventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr,true);
      })
    });

manualEventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr,false);
      })
    });

 eventplayer.source('forest_bike',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'full_hd' } });

function playMe(btn) {
    var val = parseInt(btn.value);
    plistplayer.playlist().playAtIndex(val);
  }

  function updateOnSrc() {
    var plist = plistplayer.playlist();
    var playing = plist.currentIndex();
    var loop = plist.length();
    for(var i=0; i<loop; i++) {
      var label = "plist"+i;
      var btn = document.getElementById(label);
      if(i == playing)
        btn.setAttribute("class", "active");
      else
        btn.setAttribute("class", " ");
  }
  console.log("updateOnSrc", playing, loop);
}
var plistplayer = cld.videoPlayer('demo-playlist-player');
plistplayer.on('sourcechanged', updateOnSrc);
plistplayer.playlist(
  [{ publicId: 'snow_horses', sourceTypes: ['dash'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'snow_deer', sourceTypes: ['dash'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'sea_turtle', sourceTypes: ['dash'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'elephants', sourceTypes: ['dash'], transformation: {streaming_profile: 'full_hd'}}],
   { autoAdvance: 0, repeat: true });

 plistplayer.source('snow_horses',{ sourceTypes: ['dash'], transformation: {streaming_profile: 'full_hd' } });

var recplayer = cld.videoPlayer('demo-recommendation-player',{ autoShowRecommendations: true });

var source1 = { publicId: 'snow_deer_short', info: { title: 'Snow Deer', subtitle: 'Snow Deer Movie' } };
var source2 = { publicId: 'snow_horses', info: { title: 'Snow Horses', subtitle: 'Snow Horses Movie' } };
var source3 = { publicId: 'sea_turtle', info: { title: 'Sea Turtle', subtitle: 'Sea Turtle Movie' } };
var source4 = { publicId: 'elephants', info: { title: 'Elephants', subtitle: 'Elephants' } };
var source5 = { publicId: 'marmots', info: { title: 'Marmots', subtitle: 'Marmots' } };
source1.recommendations = [source2, source3, source4, source5];
source2.recommendations = [source3];
source3.recommendations = [source4];
source4.recommendations = [source5];
source5.recommendations = [source2, source3, source4, source1];
recplayer.source(source1);

<commit_msg>Update draft.js<commit_after>function toggleClass() {
    var theme = document.getElementById("theme-area");
    theme.classList.toggle("active");
}
function setTheme(btn) {
    var newTheme = "cld-video-player-skin-" + btn.value;
    var oldTheme = "cld-video-player-skin-";
    var pagination = document.getElementById("video-pagination");
    if(btn.value == "dark") {
        oldTheme += "light";
        pagination.classList.remove("style01");
    }
    else {
        oldTheme += "dark";
        pagination.classList.add("style01");
    }
    var vplayers = document.getElementsByClassName("cld-video-player");
    for(var i = 0; i < vplayers.length; i++) {
        vplayers[i].classList.remove(oldTheme);
        vplayers[i].classList.add(newTheme);
    }
    toggleClass();
}

window.addEventListener('scroll',checkPosition,false);
function checkPosition()
{
    var themeArea = document.getElementById("theme-area");
    if(window.scrollY > 50)
    {
        themeArea.classList.add("scrolling");
    } else {
        themeArea.classList.remove("scrolling");
    }
}

function playerSizeChange(input) {
  var area = document.getElementById("video-area-adaptive");
  var border = document.getElementById("player-border");
  var val = input.value + "%";
  area.style.width = val;
  border.style.width = val;
  var pwidth = document.getElementById("player-width");
  pwidth.innerHTML = area.clientWidth;
}
function updateOnResize() {
  var width = demoplayer.videojs.videoWidth();
  var current = document.getElementById(width);
  var oldactive = document.getElementsByClassName("range-info active");
  for (var i = 0; i < oldactive.length; i++) {
    oldactive[i].setAttribute("class","range-info");
  }
  current.setAttribute("class","range-info active");
}
function requestResolution(btn) {
  console.log("requestResolution() ",btn.id, safari);
  if(!safari)
  {
    document.getElementById("checkbox").checked = false;
    document.getElementById("checkboxLabel").classList.add("disabled");
    for (var i = 0; i < qualityLevels.length; i++) {
      qualityLevels[i].enabled = (Number(btn.id) == qualityLevels[i].width);
    }
  }
}
function requestAuto(auto) {
  console.log("requestAuto() ",auto.checked);
  if(auto.checked) {
    for (var i = 0; i < qualityLevels.length; i++) {
        qualityLevels[i].enabled = true;
    }
  }
  document.getElementById("checkboxLabel").classList.toggle("disabled");
}

function changeOfResolution() {
  var index = qualityLevels.selectedIndex;
  var res = document.getElementById(qualityLevels[index].width);
  var old = document.getElementsByClassName("range-info second-hover");
  for (var i = 0; i < old.length; i++) {
    old[i].setAttribute("class","range-info");
  }
  res.setAttribute("class","range-info second-hover");
}

function setProfile(profile) {
  var elements = document.getElementsByClassName('range-info');
  var i = elements.length;

    while(i--) {
      console.log(elements[i].getElementsByClassName(profile.value).length);
        if(elements[i].getElementsByClassName(profile.value).length > 0)
          elements[i].setAttribute("class","range-info");
        else
          elements[i].setAttribute("class","range-info out-of-range");

    }
  document.getElementById("checkbox").checked = true;
  document.getElementById("checkboxLabel").classList.remove("disabled");
  demoplayer.source("kayak", { sourceTypes: ['hls'], transformation: {streaming_profile: profile.value } }).play();
}

var chrome   = navigator.userAgent.indexOf('Chrome') > -1;
var safari   = navigator.userAgent.indexOf("Safari") > -1;
if ((chrome) && (safari)) safari = false;

if(safari)
  document.getElementById("checkbox").disabled = true;

playerSizeChange(document.getElementById("player-slider"));

var cld = cloudinary.Cloudinary.new({ cloud_name: 'demo' });

var adaptive = document.getElementById("adaptive");
document.getElementById("demo-adaptive-player").addEventListener('resize',updateOnResize, false);

var demoplayer = cld.videoPlayer('demo-adaptive-player');

var qualityLevels = demoplayer.videojs.qualityLevels();
qualityLevels.on('change', changeOfResolution);
qualityLevels.on('addqualitylevel', function(event) { console.log(event.qualityLevel.width); });

demoplayer.source('kayak',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'full_hd' } });

function updateOnEvent(eventStr,automatic) {
  var list = document.getElementById('events-list');
  var entry = document.createElement('li');
  if(automatic)
      entry.className = "orange";
  entry.appendChild(document.createTextNode(eventStr));
  list.appendChild(entry);
  list.scrollTop = list.scrollHeight;
}

function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        return (h + ":" + m + ":" + s);
}

var eventplayer = cld.videoPlayer('demo-events-player', { playedEventTimes: [3, 10] });

var autoEventTypes = ['sourcechanged', 'timeplayed', 'percentsplayed', 'ended'];

var manualEventTypes = ['play', 'pause', 'volumechange', 'mute', 'unmute', 'fullscreenchange',
      'seek'];

autoEventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr,true);
      })
    });

manualEventTypes.forEach(function(eventType) {
      eventplayer.on(eventType, function(event) {
        var eventStr = startTime() + " " + eventType;
        if (event.eventData) {
          eventStr = eventStr + ": " + JSON.stringify(event.eventData)
        }
        updateOnEvent(eventStr,false);
      })
    });

 eventplayer.source('forest_bike',{ sourceTypes: ['hls'],
                              transformation: {streaming_profile: 'full_hd' } });

function playMe(btn) {
    var val = parseInt(btn.value);
    plistplayer.playlist().playAtIndex(val);
  }

  function updateOnSrc() {
    var plist = plistplayer.playlist();
    var playing = plist.currentIndex();
    var loop = plist.length();
    for(var i=0; i<loop; i++) {
      var label = "plist"+i;
      var btn = document.getElementById(label);
      if(i == playing)
        btn.setAttribute("class", "active");
      else
        btn.setAttribute("class", " ");
  }
  console.log("updateOnSrc", playing, loop);
}
var plistplayer = cld.videoPlayer('demo-playlist-player');
plistplayer.on('sourcechanged', updateOnSrc);
plistplayer.playlist(
  [{ publicId: 'snow_horses', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'snow_deer', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'sea_turtle', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}},
   { publicId: 'elephants', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}}],
   { autoAdvance: 0, repeat: true });

 plistplayer.source('snow_horses',{ sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd' } });

var recplayer = cld.videoPlayer('demo-recommendation-player',{ autoShowRecommendations: true });

var source1 = { publicId: 'snow_deer_short', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}, info: { title: 'Snow Deer', subtitle: 'Snow Deer Movie' } };
var source2 = { publicId: 'snow_horses', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}, info: { title: 'Snow Horses', subtitle: 'Snow Horses Movie' } };
var source3 = { publicId: 'sea_turtle', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}, info: { title: 'Sea Turtle', subtitle: 'Sea Turtle Movie' } };
var source4 = { publicId: 'elephants', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}, info: { title: 'Elephants', subtitle: 'Elephants' } };
var source5 = { publicId: 'marmots', sourceTypes: ['hls'], transformation: {streaming_profile: 'full_hd'}, info: { title: 'Marmots', subtitle: 'Marmots' } };
source1.recommendations = [source2, source3, source4, source5];
source2.recommendations = [source3];
source3.recommendations = [source4];
source4.recommendations = [source5];
source5.recommendations = [source2, source3, source4, source1];
recplayer.source(source1);

<|endoftext|>