<commit_before>'use strict';

var yeoman = require('yeoman-generator');
var greetings = require('./greetings');
var parser = require('iniparser');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({

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

    // Have Yeoman greet the user.
    this.log(greetings);

    // `homeDir` will be used to find the `.gitconfig` file.
    var homeDir;
    // `currentDir` will be used as a default in case of user not inserting.
    // a project name
    var currentDir = path.basename(process.cwd());
    // `user` will store username and email from GIT information.
    var user;

    // Discover homeDir based on the OS
    if (process.platform === 'win32') {
      homeDir = process.env.USERPROFILE;
    } else {
      homeDir = process.env.HOME || process.env.HOMEPATH;
    }

    var gitConfigFile = path.join(homeDir, '.gitconfig');

    if (fs.existsSync(gitConfigFile)) {
      user = parser.parseSync(gitConfigFile).user;
    } else {
      user = {
        name: 'Matheus Brasil',
        email: 'matheus.brasil10@gmail.com'
      };
    }

    // Things that should be asked the user.
    var prompts = [
      {
        name: 'pkgName',
        message: 'What\'s the package name?',
        default: currentDir
      },
      {
        name: 'pkgDescription',
        message: 'What\'s your package all about?',
        default: 'An awesome OCaml module.'
      },
      {
        name: 'pkgVersion',
        message: 'What\'s the package version?',
        default: '0.1.0'
      },
      {
        name: 'authorName',
        message: 'What\'s your name?',
        default: user.name || ''
      },
      {
        name: 'authorEmail',
        message: 'What\'s your email?',
        default: user.email || ''
      },
      {
        name: 'userName',
        message: 'What\'s your Github username?',
        default: 'mabrasil'
      },
      {
        type: 'list',
        name: 'license',
        message: 'Choose your license type',
        choices: ['APACHE', 'BSD', 'GPLv3', 'MIT'],
        default: 'MIT'
      },
      {
        type: 'confirm',
        name: 'confirm',
        message: 'Continue?',
        default: false
      }
    ];

    // Do some work around properties (SlugName, Date etc.)
    this.prompt(prompts, function (props) {
      this.props = props;
      this.props.pkgSlugName = s.slugify(this.props.pkgName);
      this.props.pkgCapitalizedName = s.capitalize(this.props.pkgName);
      var d = new Date();
      this.props.year = d.getFullYear();
      this.props.date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      if (!this.props.confirm) {
        return process.exit(0);
      }
      done();
    }.bind(this));

  },

  configuring: {

    enforceFolderName: function () {
      if (this.props.pkgSlugName !== _.last(this.destinationRoot().split(path.sep))) {
        this.destinationRoot(this.props.pkgSlugName);
      }
      this.config.save();
    }
  },

  // Things that should be generated in the boilerplate
  writing: {

    // Main project files (OCaml files, testing files, OASIS spec etc.)
    app: function () {

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

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

      this.fs.copyTpl(
        this.templatePath('lib/_pkgName.ml'),
        this.destinationPath('lib/' + this.props.pkgSlugName + '.ml'),
        this.props
      );

      this.fs.copyTpl(
        this.templatePath('test/_pkgName_test.ml'),
        this.destinationPath('test/' + this.props.pkgSlugName + '_test.ml'),
        this.props
      );

    },

    // Docs-related files (README, LICENSE, CHANGELOG etc.)
    docs: function () {

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

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

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

      if (this.props.license === 'APACHE') {
        this.fs.copyTpl(
          this.templatePath('_LICENSE_APACHE.md'),
          this.destinationPath('LICENSE.md'),
          this.props
        );
      } else if (this.props.license === 'BSD') {
        this.fs.copyTpl(
          this.templatePath('_LICENSE_BSD.md'),
          this.destinationPath('LICENSE.md'),
          this.props
        );
      } else if (this.props.license === 'GPLv3') {
        this.fs.copyTpl(
          this.templatePath('_LICENSE_GPLv3.md'),
          this.destinationPath('LICENSE.md'),
          this.props
        );
      } else {
        this.fs.copyTpl(
          this.templatePath('_LICENSE_MIT.md'),
          this.destinationPath('LICENSE.md'),
          this.props
        );
      }
    },

    // (Git-related files and CI information)
    general: function () {

      this.fs.copyTpl(
        this.templatePath('travis.yml'),
        this.destinationPath('.travis.yml'),
        this.props
      );

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

      this.fs.copyTpl(
        this.templatePath('gitattributes'),
        this.destinationPath('.gitattributes'),
        this.props
      );
    }
  }
});
<commit_msg>Simplified source<commit_after>'use strict';

var yeoman = require('yeoman-generator');
var greetings = require('./greetings');
var parser = require('iniparser');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({

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

    // Have Yeoman greet the user.
    this.log(greetings);

    // `homeDir` will be used to find the `.gitconfig` file.
    var homeDir;
    // `currentDir` will be used as a default in case of user not inserting.
    // a project name
    var currentDir = path.basename(process.cwd());
    // `user` will store username and email from GIT information.
    var user;

    // Discover homeDir based on the OS
    homedir = process.platform === 'win32'
      ? /* then      */ process.env.USERPROFILE
      : /* otherwise */ process.env.HOME || process.env.HOMEPATH;

    var gitConfigFile = path.join(homeDir, '.gitconfig');

    // `user` will store username and email from GIT information.
    user = fs.existSync(gitConfigFile)
      ? /* then      */ parser.parseSync(gitConfigFile).user
      : /* otherwise */ {
        name: 'Matheus Brasil',
        email: 'matheus.brasil10@gmail.com'
      };

    // Things that should be asked the user.
    var prompts = [
      {
        name: 'pkgName',
        message: 'What\'s the package name?',
        default: currentDir
      },
      {
        name: 'pkgDescription',
        message: 'What\'s your package all about?',
        default: 'An awesome OCaml module.'
      },
      {
        name: 'pkgVersion',
        message: 'What\'s the package version?',
        default: '0.1.0'
      },
      {
        name: 'authorName',
        message: 'What\'s your name?',
        default: user.name || ''
      },
      {
        name: 'authorEmail',
        message: 'What\'s your email?',
        default: user.email || ''
      },
      {
        name: 'userName',
        message: 'What\'s your Github username?',
        default: 'mabrasil'
      },
      {
        type: 'list',
        name: 'license',
        message: 'Choose your license type',
        choices: ['APACHE', 'BSD', 'GPLv3', 'MIT'],
        default: 'MIT'
      },
      {
        type: 'confirm',
        name: 'confirm',
        message: 'Continue?',
        default: false
      }
    ];

    // Do some work around properties (SlugName, Date etc.)
    this.prompt(prompts, function (props) {
      var d = new Date();

      this.props = props;
      this.props.pkgSlugName = s.slugify(this.props.pkgName);
      this.props.pkgCapitalizedName = s.capitalize(this.props.pkgName);
      this.props.year = d.getFullYear();
      this.props.date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      if (!this.props.confirm) {
        return process.exit(0);
      }
      done();
    }.bind(this));

  },

  configuring: {
    enforceFolderName: function () {
      if (this.props.pkgSlugName !== _.last(this.destinationRoot().split(path.sep))) {
        this.destinationRoot(this.props.pkgSlugName);
      }
      this.config.save();
    }
  },

  // Things that should be generated in the boilerplate
  writing: {
    // Main project files (OCaml files, testing files, OASIS spec etc.)
    app: function () {

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

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

      this.fs.copyTpl(
        this.templatePath('lib/_pkgName.ml'),
        this.destinationPath('lib/' + this.props.pkgSlugName + '.ml'),
        this.props
      );

      this.fs.copyTpl(
        this.templatePath('test/_pkgName_test.ml'),
        this.destinationPath('test/' + this.props.pkgSlugName + '_test.ml'),
        this.props
      );
    },

    // Docs-related files (README, LICENSE, CHANGELOG etc.)
    docs: function () {
      this.fs.copyTpl(
        this.templatePath('_README.md'),
        this.destinationPath('README.md'),
        this.props
      );

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

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

      // License copying
      var licenses = ['APACHE', 'BSD', 'GPLv3'];

      this.fs.copyTpl(
        this.templatePath(
          licenses.indexOf(this.props.license) !== -1
            ? /* then      */ '_LICENSE_' + this.props.license + '.md'
            : /* otherwise */ '_LICENSE.md'
        ),
        this.destinationPath('LICENSE.md'),
        this.props
      );
    },

    // (Git-related files and CI information)
    general: function () {
      this.fs.copyTpl(
        this.templatePath('travis.yml'),
        this.destinationPath('.travis.yml'),
        this.props
      );

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

      this.fs.copyTpl(
        this.templatePath('gitattributes'),
        this.destinationPath('.gitattributes'),
        this.props
      );
    }
  }
});
<|endoftext|>


<commit_before><commit_msg>refacotry modal<commit_after><|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>

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.
*/

import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import { _t } from '../../../languageHandler';
import AccessibleTooltipButton from "./AccessibleTooltipButton";
import Modal from "../../../Modal";
import * as sdk from "../../../index";
import {Key} from "../../../Keyboard";
import FocusLock from "react-focus-lock";
import MemberAvatar from "../avatars/MemberAvatar";
import {ContextMenuTooltipButton} from "../../../accessibility/context_menu/ContextMenuTooltipButton";
import MessageContextMenu from "../context_menus/MessageContextMenu";
import {aboveLeftOf, ContextMenu} from '../../structures/ContextMenu';
import MessageTimestamp from "../messages/MessageTimestamp";
import SettingsStore from "../../../settings/SettingsStore";
import {formatFullDate} from "../../../DateUtils";
import dis from '../../../dispatcher/dispatcher';

const MIN_ZOOM = 100;
const MAX_ZOOM = 300;

export default class ImageView extends React.Component {
    static propTypes = {
        src: PropTypes.string.isRequired, // the source of the image being displayed
        name: PropTypes.string, // the main title ('name') for the image
        link: PropTypes.string, // the link (if any) applied to the name of the image
        width: PropTypes.number, // width of the image src in pixels
        height: PropTypes.number, // height of the image src in pixels
        fileSize: PropTypes.number, // size of the image src in bytes
        onFinished: PropTypes.func.isRequired, // callback when the lightbox is dismissed

        // the event (if any) that the Image is displaying. Used for event-specific stuff like
        // redactions, senders, timestamps etc.  Other descriptors are taken from the explicit
        // properties above, which let us use lightboxes to display images which aren't associated
        // with events.
        mxEvent: PropTypes.object,
        permalinkCreator: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = {
            rotation: 0,
            zoom: 100,
            translationX: 0,
            translationY: 0,
            moving: false,
            contextMenuDisplayed: false,
        };
    }

    contextMenuButton = createRef();
    initX = 0;
    initY = 0;
    lastX = 0;
    lastY = 0;

    componentDidMount() {
        // We have to use addEventListener() because the listener
        // needs to be passive in order to work with Chromium
        this.focusLock.addEventListener('wheel', this.onWheel, { passive: false });
    }

    componentWillUnmount() {
        this.focusLock.removeEventListener('wheel', this.onWheel);
    }

    onKeyDown = (ev) => {
        if (ev.key === Key.ESCAPE) {
            ev.stopPropagation();
            ev.preventDefault();
            this.props.onFinished();
        }
    };

    onWheel = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();
        const newZoom =this.state.zoom - ev.deltaY;

        if (newZoom <= MIN_ZOOM) {
            this.setState({
                zoom: MIN_ZOOM,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        if (newZoom >= MAX_ZOOM) {
            this.setState({zoom: MAX_ZOOM});
            return;
        }

        this.setState({
            zoom: newZoom,
        });
    }

    onRotateCounterClockwiseClick = (ev) => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur - 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onRotateClockwiseClick = (ev) => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur + 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onZoomInClick = (ev) => {
        if (this.state.zoom >= MAX_ZOOM) {
            this.setState({zoom: MAX_ZOOM});
            return;
        }

        this.setState({
            zoom: this.state.zoom + 10,
        });
    };

    onZoomOutClick = (ev) => {
        if (this.state.zoom <= MIN_ZOOM) {
            this.setState({
                zoom: MIN_ZOOM,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        this.setState({
            zoom: this.state.zoom - 10,
        });
    }

    onDownloadClick = (ev) => {
        const a = document.createElement("a");
        a.href = this.props.src;
        a.download = this.props.name;
        a.click();
    }

    onOpenContextMenu = (ev) => {
        this.setState({
            contextMenuDisplayed: true,
        });
    }

    onCloseContextMenu = () => {
        this.setState({
            contextMenuDisplayed: false,
        });
    }

    onPermalinkClicked = e => {
        // This allows the permalink to be opened in a new tab/window or copied as
        // matrix.to, but also for it to enable routing within Element when clicked.
        e.preventDefault();
        dis.dispatch({
            action: 'view_room',
            event_id: this.props.mxEvent.getId(),
            highlighted: true,
            room_id: this.props.mxEvent.getRoomId(),
        });
        this.props.onFinished();
    };

    onStartMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        this.setState({moving: true});
        this.initX = ev.pageX - this.lastX;
        this.initY = ev.pageY - this.lastY;
    }

    onMoving = ev => {
        ev.stopPropagation();
        ev.preventDefault();

        if (!this.state.moving) return false;

        this.lastX = ev.pageX - this.initX;
        this.lastY = ev.pageY - this.initY;
        this.setState({
            translationX: this.lastX,
            translationY: this.lastY,
        });
    }

    onEndMoving = ev => {
        this.setState({moving: false});
    }

    renderContextMenu() {
        let contextMenu = null;
        if (this.state.contextMenuDisplayed) {
            contextMenu = (
                <ContextMenu
                    {...aboveLeftOf(this.contextMenuButton.current.getBoundingClientRect())}
                    onFinished={this.onCloseContextMenu}
                >
                    <MessageContextMenu
                        mxEvent={this.props.mxEvent}
                        permalinkCreator={this.props.permalinkCreator}
                        onFinished={this.onCloseContextMenu}
                    />
                </ContextMenu>
            );
        }

        return (
            <React.Fragment>
                { contextMenu }
            </React.Fragment>
        );
    }

    render() {
        const showEventMeta = !!this.props.mxEvent;

        const rotationDegrees = this.state.rotation + "deg";
        const zoomPercentage = this.state.zoom/100;
        const translatePixelsX = this.state.translationX + "px";
        const translatePixelsY = this.state.translationY + "px";
        // The order of the values is important!
        // First, we translate and only then we rotate, otherwise
        // we would apply the translation to an already rotated
        // image causing it translate in the wrong direction.
        const style = {
            cursor: this.state.moving ? "grabbing" : "grab",
            transform: `translateX(${translatePixelsX})
                        translateY(${translatePixelsY})
                        scale(${zoomPercentage})
                        rotate(${rotationDegrees})`,
        };

        let info;
        if (showEventMeta) {
            const mxEvent = this.props.mxEvent;
            const showTwelveHour = SettingsStore.getValue("showTwelveHourTimestamps");
            let permalink = "#";
            if (this.props.permalinkCreator) {
                permalink = this.props.permalinkCreator.forEvent(this.props.mxEvent.getId());
            }

            const senderName = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
            const messageTimestamp = (

                    <MessageTimestamp showFullDate={true} showTwelveHour={showTwelveHour} ts={mxEvent.getTs()} />

            );
            const avatar = (
                <MemberAvatar
                    member={mxEvent.sender}
                    width={32} height={32}
                    viewUserOnClick={true}
                />
            );

            info = (

                    {avatar}

                        {senderName}
                        {messageTimestamp}

            );
        } else {
            // If there is no event - we're viewing an avatar, we set
            // an empty div here, since the panel uses space-between
            // and we want the same placement of elements
            info = (

            );
        }

        return (
            <FocusLock
                returnFocus={true}
                lockProps={{
                    onKeyDown: this.onKeyDown,
                    role: "dialog",
                }}
                className="mx_ImageView"
                ref={ref => this.focusLock = ref}
            >

                        {info}

                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_rotateCW"
                                    title={_t("Rotate Right")}
                                    onClick={this.onRotateClockwiseClick}>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_rotateCCW"
                                    title={_t("Rotate Left")}
                                    onClick={ this.onRotateCounterClockwiseClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_zoomOut"
                                    title={_t("Zoom out")}
                                    onClick={ this.onZoomOutClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_zoomIn"
                                    title={_t("Zoom in")}
                                    onClick={ this.onZoomInClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_download"
                                    title={_t("Download")}
                                    onClick={ this.onDownloadClick }>
                                </AccessibleTooltipButton>
                                <ContextMenuTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_more"
                                    title={_t("Options")}
                                    onClick={this.onOpenContextMenu}
                                    inputRef={this.contextMenuButton}
                                />
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_close"
                                    title={_t("Close")}
                                    onClick={ this.props.onFinished }>
                                </AccessibleTooltipButton>
                                {this.renderContextMenu()}

                        <img
                            src={this.props.src}
                            title={this.props.name}
                            style={style}
                            className="mx_ImageView_image"
                            draggable={true}
                            onMouseDown={this.onStartMoving}
                            onMouseMove={this.onMoving}
                            onMouseUp={this.onEndMoving}
                            onMouseLeave={this.onEndMoving}
                        />

            </FocusLock>
        );
    }
}
<commit_msg>Consistent evs<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>

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.
*/

import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import {MatrixClientPeg} from "../../../MatrixClientPeg";
import { _t } from '../../../languageHandler';
import AccessibleTooltipButton from "./AccessibleTooltipButton";
import Modal from "../../../Modal";
import * as sdk from "../../../index";
import {Key} from "../../../Keyboard";
import FocusLock from "react-focus-lock";
import MemberAvatar from "../avatars/MemberAvatar";
import {ContextMenuTooltipButton} from "../../../accessibility/context_menu/ContextMenuTooltipButton";
import MessageContextMenu from "../context_menus/MessageContextMenu";
import {aboveLeftOf, ContextMenu} from '../../structures/ContextMenu';
import MessageTimestamp from "../messages/MessageTimestamp";
import SettingsStore from "../../../settings/SettingsStore";
import {formatFullDate} from "../../../DateUtils";
import dis from '../../../dispatcher/dispatcher';

const MIN_ZOOM = 100;
const MAX_ZOOM = 300;

export default class ImageView extends React.Component {
    static propTypes = {
        src: PropTypes.string.isRequired, // the source of the image being displayed
        name: PropTypes.string, // the main title ('name') for the image
        link: PropTypes.string, // the link (if any) applied to the name of the image
        width: PropTypes.number, // width of the image src in pixels
        height: PropTypes.number, // height of the image src in pixels
        fileSize: PropTypes.number, // size of the image src in bytes
        onFinished: PropTypes.func.isRequired, // callback when the lightbox is dismissed

        // the event (if any) that the Image is displaying. Used for event-specific stuff like
        // redactions, senders, timestamps etc.  Other descriptors are taken from the explicit
        // properties above, which let us use lightboxes to display images which aren't associated
        // with events.
        mxEvent: PropTypes.object,
        permalinkCreator: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = {
            rotation: 0,
            zoom: 100,
            translationX: 0,
            translationY: 0,
            moving: false,
            contextMenuDisplayed: false,
        };
    }

    contextMenuButton = createRef();
    initX = 0;
    initY = 0;
    lastX = 0;
    lastY = 0;

    componentDidMount() {
        // We have to use addEventListener() because the listener
        // needs to be passive in order to work with Chromium
        this.focusLock.addEventListener('wheel', this.onWheel, { passive: false });
    }

    componentWillUnmount() {
        this.focusLock.removeEventListener('wheel', this.onWheel);
    }

    onKeyDown = (ev) => {
        if (ev.key === Key.ESCAPE) {
            ev.stopPropagation();
            ev.preventDefault();
            this.props.onFinished();
        }
    };

    onWheel = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();
        const newZoom =this.state.zoom - ev.deltaY;

        if (newZoom <= MIN_ZOOM) {
            this.setState({
                zoom: MIN_ZOOM,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        if (newZoom >= MAX_ZOOM) {
            this.setState({zoom: MAX_ZOOM});
            return;
        }

        this.setState({
            zoom: newZoom,
        });
    }

    onRotateCounterClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur - 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onRotateClockwiseClick = () => {
        const cur = this.state.rotation;
        const rotationDegrees = (cur + 90) % 360;
        this.setState({ rotation: rotationDegrees });
    };

    onZoomInClick = () => {
        if (this.state.zoom >= MAX_ZOOM) {
            this.setState({zoom: MAX_ZOOM});
            return;
        }

        this.setState({
            zoom: this.state.zoom + 10,
        });
    };

    onZoomOutClick = () => {
        if (this.state.zoom <= MIN_ZOOM) {
            this.setState({
                zoom: MIN_ZOOM,
                translationX: 0,
                translationY: 0,
            });
            return;
        }
        this.setState({
            zoom: this.state.zoom - 10,
        });
    }

    onDownloadClick = () => {
        const a = document.createElement("a");
        a.href = this.props.src;
        a.download = this.props.name;
        a.click();
    }

    onOpenContextMenu = () => {
        this.setState({
            contextMenuDisplayed: true,
        });
    }

    onCloseContextMenu = () => {
        this.setState({
            contextMenuDisplayed: false,
        });
    }

    onPermalinkClicked = (ev) => {
        // This allows the permalink to be opened in a new tab/window or copied as
        // matrix.to, but also for it to enable routing within Element when clicked.
        ev.preventDefault();
        dis.dispatch({
            action: 'view_room',
            event_id: this.props.mxEvent.getId(),
            highlighted: true,
            room_id: this.props.mxEvent.getRoomId(),
        });
        this.props.onFinished();
    };

    onStartMoving = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();

        this.setState({moving: true});
        this.initX = ev.pageX - this.lastX;
        this.initY = ev.pageY - this.lastY;
    }

    onMoving = (ev) => {
        ev.stopPropagation();
        ev.preventDefault();

        if (!this.state.moving) return false;

        this.lastX = ev.pageX - this.initX;
        this.lastY = ev.pageY - this.initY;
        this.setState({
            translationX: this.lastX,
            translationY: this.lastY,
        });
    }

    onEndMoving = () => {
        this.setState({moving: false});
    }

    renderContextMenu() {
        let contextMenu = null;
        if (this.state.contextMenuDisplayed) {
            contextMenu = (
                <ContextMenu
                    {...aboveLeftOf(this.contextMenuButton.current.getBoundingClientRect())}
                    onFinished={this.onCloseContextMenu}
                >
                    <MessageContextMenu
                        mxEvent={this.props.mxEvent}
                        permalinkCreator={this.props.permalinkCreator}
                        onFinished={this.onCloseContextMenu}
                    />
                </ContextMenu>
            );
        }

        return (
            <React.Fragment>
                { contextMenu }
            </React.Fragment>
        );
    }

    render() {
        const showEventMeta = !!this.props.mxEvent;

        const rotationDegrees = this.state.rotation + "deg";
        const zoomPercentage = this.state.zoom/100;
        const translatePixelsX = this.state.translationX + "px";
        const translatePixelsY = this.state.translationY + "px";
        // The order of the values is important!
        // First, we translate and only then we rotate, otherwise
        // we would apply the translation to an already rotated
        // image causing it translate in the wrong direction.
        const style = {
            cursor: this.state.moving ? "grabbing" : "grab",
            transform: `translateX(${translatePixelsX})
                        translateY(${translatePixelsY})
                        scale(${zoomPercentage})
                        rotate(${rotationDegrees})`,
        };

        let info;
        if (showEventMeta) {
            const mxEvent = this.props.mxEvent;
            const showTwelveHour = SettingsStore.getValue("showTwelveHourTimestamps");
            let permalink = "#";
            if (this.props.permalinkCreator) {
                permalink = this.props.permalinkCreator.forEvent(this.props.mxEvent.getId());
            }

            const senderName = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
            const messageTimestamp = (

                    <MessageTimestamp showFullDate={true} showTwelveHour={showTwelveHour} ts={mxEvent.getTs()} />

            );
            const avatar = (
                <MemberAvatar
                    member={mxEvent.sender}
                    width={32} height={32}
                    viewUserOnClick={true}
                />
            );

            info = (

                    {avatar}

                        {senderName}
                        {messageTimestamp}

            );
        } else {
            // If there is no event - we're viewing an avatar, we set
            // an empty div here, since the panel uses space-between
            // and we want the same placement of elements
            info = (

            );
        }

        return (
            <FocusLock
                returnFocus={true}
                lockProps={{
                    onKeyDown: this.onKeyDown,
                    role: "dialog",
                }}
                className="mx_ImageView"
                ref={ref => this.focusLock = ref}
            >

                        {info}

                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_rotateCW"
                                    title={_t("Rotate Right")}
                                    onClick={this.onRotateClockwiseClick}>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_rotateCCW"
                                    title={_t("Rotate Left")}
                                    onClick={ this.onRotateCounterClockwiseClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_zoomOut"
                                    title={_t("Zoom out")}
                                    onClick={ this.onZoomOutClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_zoomIn"
                                    title={_t("Zoom in")}
                                    onClick={ this.onZoomInClick }>
                                </AccessibleTooltipButton>
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_download"
                                    title={_t("Download")}
                                    onClick={ this.onDownloadClick }>
                                </AccessibleTooltipButton>
                                <ContextMenuTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_more"
                                    title={_t("Options")}
                                    onClick={this.onOpenContextMenu}
                                    inputRef={this.contextMenuButton}
                                />
                                <AccessibleTooltipButton
                                    className="mx_ImageView_button mx_ImageView_button_close"
                                    title={_t("Close")}
                                    onClick={ this.props.onFinished }>
                                </AccessibleTooltipButton>
                                {this.renderContextMenu()}

                        <img
                            src={this.props.src}
                            title={this.props.name}
                            style={style}
                            className="mx_ImageView_image"
                            draggable={true}
                            onMouseDown={this.onStartMoving}
                            onMouseMove={this.onMoving}
                            onMouseUp={this.onEndMoving}
                            onMouseLeave={this.onEndMoving}
                        />

            </FocusLock>
        );
    }
}
<|endoftext|>


<commit_before>'use strict';

const Generator = require('yeoman-generator');

const Params = require('./params');
const convName = require('./convName');
const prompting = require('./prompting');

const optionNames = [
  'services',
  'envs',
  'sshcfg-path',
  'servers-yaml-path',
];

const paramsHash = {};
optionNames.forEach(name => {
  paramsHash[name] = require(`./params/${convName(name)}`);
});

const params = new Params(
  optionNames.map(key => require(`./params/${convName(key)}`)));

module.exports = class extends Generator {
  constructor(args, opts) {
    const ignoreFiles = opts.ignoreFiles || [];
    delete opts.ignoreFiles;
    super(args, opts);
    this.ignoreFiles = ignoreFiles;
    params.setOptions(this);
  }
  prompting() {
    return prompting(this, params, optionNames);
  }

  writing() {
    const answers = {};
    optionNames.forEach(key => {
      answers[convName(key)] = this.answers[key];
    });
    [
      'README.md',
      'bin',
      'group_vars/all.yml',
      'lib',
      'requirements.dev.in',
      'requirements.in',
      'roles.yml',
      'ssh-keys/.keep'].filter(key => {
        return this.ignoreFiles.indexOf(key) === -1;
      }).forEach(key => {
        this.fs.copy(
          this.templatePath(key),
          this.destinationPath(key));
    });
    if (this.ignoreFiles.indexOf('.gitignore') === -1) {
      this.fs.copy(
        this.templatePath('gitignore'), this.destinationPath('.gitignore'));
    }
    if (this.ignoreFiles.indexOf('.envrc') === -1) {
      this.fs.copy(
        this.templatePath('envrc'), this.destinationPath('.envrc'));
    }
    ['Vagrantfile', 'Makefile', 'ansible.cfg', 'cfg.yml'].filter(key => {
      return this.ignoreFiles.indexOf(key) === -1;
    }).forEach(key => {
      this.fs.copyTpl(
        this.templatePath(key),
        this.destinationPath(key), answers);
    });
    if (this.ignoreFiles.indexOf('servers.yml') === -1) {
      this.fs.copyTpl(
        this.templatePath('servers.yml'),
        this.destinationPath(answers.serversYamlPath), answers);
    }
    if (this.ignoreFiles.indexOf('playbooks') === -1) {
      answers.services.filter(service => {
        return this.ignoreFiles.indexOf(`playbooks/${service}.yml`) === -1;
      }).forEach(service => {
        this.fs.copyTpl(
          this.templatePath('playbooks/service.yml'),
          this.destinationPath(`playbooks/${service}.yml`), {service: service});
      });
    }
    if (this.ignoreFiles.indexOf('group_vars') === -1) {
      answers.services.filter(service => {
        return this.ignoreFiles.indexOf(`group_vars/${service}.yml`) === -1;
      }).forEach(service => {
        this.fs.copyTpl(
          this.templatePath('group_vars/service.yml'),
          this.destinationPath(`group_vars/${service}.yml`), {service: service});
      });
    }
  }

  install() {
    this.spawnCommand('direnv', ['allow']);
    this.spawnCommand('chmod', ['-R', 'a+x', 'bin']);
  }
};
<commit_msg>feat: add the isSubGen option to use this generator as a sub generator<commit_after>'use strict';

const Generator = require('yeoman-generator');

const Params = require('./params');
const convName = require('./convName');
const prompting = require('./prompting');

const optionNames = [
  'services',
  'envs',
  'sshcfg-path',
  'servers-yaml-path',
];

const paramsHash = {};
optionNames.forEach(name => {
  paramsHash[name] = require(`./params/${convName(name)}`);
});

const params = new Params(
  optionNames.map(key => require(`./params/${convName(key)}`)));

module.exports = class extends Generator {
  constructor(args, opts) {
    const isSubGen = opts.isSubGen;
    delete opts.isSubGen;
    const ignoreFiles = opts.ignoreFiles || [];
    delete opts.ignoreFiles;
    super(args, opts);
    this.ignoreFiles = ignoreFiles;
    this.isSubGen = isSubGen;
    if (!isSubGen) {
      params.setOptions(this);
    }
  }
  prompting() {
    if (this.isSubGen) {
      this.answers = this.options;
      return;
    }
    return prompting(this, params, optionNames);
  }

  writing() {
    const answers = {};
    optionNames.forEach(key => {
      answers[convName(key)] = this.answers[key];
    });
    [
      'README.md',
      'bin',
      'group_vars/all.yml',
      'lib',
      'requirements.dev.in',
      'requirements.in',
      'roles.yml',
      'ssh-keys/.keep'].filter(key => {
        return this.ignoreFiles.indexOf(key) === -1;
      }).forEach(key => {
        this.fs.copy(
          this.templatePath(key),
          this.destinationPath(key));
    });
    if (this.ignoreFiles.indexOf('.gitignore') === -1) {
      this.fs.copy(
        this.templatePath('gitignore'), this.destinationPath('.gitignore'));
    }
    if (this.ignoreFiles.indexOf('.envrc') === -1) {
      this.fs.copy(
        this.templatePath('envrc'), this.destinationPath('.envrc'));
    }
    ['Vagrantfile', 'Makefile', 'ansible.cfg', 'cfg.yml'].filter(key => {
      return this.ignoreFiles.indexOf(key) === -1;
    }).forEach(key => {
      this.fs.copyTpl(
        this.templatePath(key),
        this.destinationPath(key), answers);
    });
    if (this.ignoreFiles.indexOf('servers.yml') === -1) {
      this.fs.copyTpl(
        this.templatePath('servers.yml'),
        this.destinationPath(answers.serversYamlPath), answers);
    }
    if (this.ignoreFiles.indexOf('playbooks') === -1) {
      answers.services.filter(service => {
        return this.ignoreFiles.indexOf(`playbooks/${service}.yml`) === -1;
      }).forEach(service => {
        this.fs.copyTpl(
          this.templatePath('playbooks/service.yml'),
          this.destinationPath(`playbooks/${service}.yml`), {service: service});
      });
    }
    if (this.ignoreFiles.indexOf('group_vars') === -1) {
      answers.services.filter(service => {
        return this.ignoreFiles.indexOf(`group_vars/${service}.yml`) === -1;
      }).forEach(service => {
        this.fs.copyTpl(
          this.templatePath('group_vars/service.yml'),
          this.destinationPath(`group_vars/${service}.yml`), {service: service});
      });
    }
  }

  install() {
    this.spawnCommand('direnv', ['allow']);
    this.spawnCommand('chmod', ['-R', 'a+x', 'bin']);
  }
};
<|endoftext|>


<commit_before>const fountain = require('fountain-generator');

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

  configuring: function () {
    this.mergeJson('package.json', {
      dependencies: {
        angular: '^1.5.0-beta.2'
      },
      devDependencies: {
        'angular-mocks': '^1.5.0-beta.2'
      }
    });
  },

  composing: function () {
    this.composeWith('fountain-gulp', { options: this.props });
  },

  writing: function () {
    this.fs.copyTpl(
      this.templatePath('src'),
      this.destinationPath('src'),
      { modules: this.props.modules !== 'inject' }
    );
  }
});
<commit_msg>Fix composition<commit_after>const fountain = require('fountain-generator');

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

  configuring: function () {
    this.mergeJson('package.json', {
      dependencies: {
        angular: '^1.5.0-beta.2'
      },
      devDependencies: {
        'angular-mocks': '^1.5.0-beta.2'
      }
    });
  },

  composing: function () {
    this.composeWith('fountain-gulp', { options: this.props }, {
      local: require.resolve('generator-fountain-gulp/generators/app')
    });
  },

  writing: function () {
    this.fs.copyTpl(
      this.templatePath('src'),
      this.destinationPath('src'),
      { modules: this.props.modules !== 'inject' }
    );
  }
});
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var request = require('request');
var requestPromise = require('request-promise');
var fs = require('fs');
var path = require('path');

module.exports = yeoman.Base.extend({
  prompting: function () {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ' + chalk.red('Azure Functions') + ' generator!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'requestFunctionTemplates',
      message: 'Would you like to see the available templates?',
      default: true
    }];

    return this.prompt(prompts).then(answer => {
      // To access answer later use this.answer.(answer you need);
      this.answer = answer;
    });
  },

  configuring: function () {
    /*
    Notes:

    1. Fetch Templates url for list of templates
    https://api.github.com/repos/Azure/azure-webjobs-sdk-templates/contents/Templates
    2. Parse url json to get list of templates
    3. Put list into prompts and ask user which template to download
    4. Download the requested Template!

    Steps to download the template files:
    1. Use request promise to get the right download url
    2. Match the chosen template with the right url
    3. Download the files to the current directory!
    */

    if (this.answer.requestFunctionTemplates) {
      var listOfTemplates = [];
      var listOfUrls = [];

      var options = {
        uri: 'https://api.github.com/repos/Azure/azure-webjobs-sdk-templates/contents/Templates',
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true
      };

      requestPromise(options)
        .then(templates => {
          this.log('There are %d templates available', templates.length);

          for (let i = 0; i < templates.length; i ++) {
            listOfTemplates[i] = templates[i]['name'];
            listOfUrls[listOfTemplates[i]] = templates[i]['url'];
          }

          var prompts = [{
              type: 'list',
              name: 'templateToUse',
              message: 'Select from one of the available templates...',
              choices: listOfTemplates,
              default: 0
          }];

          return this.prompt(prompts).then(answer => {
            this.answer = answer;
          });
        })
        .then(() => {
          this._downloadTemplate(this.answer.templateToUse, listOfUrls);
        })
        .catch(err => {
          this.log('There was an error in searching for available templates...');
          this.log(err);
        })
    }
  },

  _downloadTemplate: function (templateToUse, listOfUrls) {
    var options = {
      uri: listOfUrls[templateToUse],
      headers: {
          'User-Agent': 'Request-Promise'
      },
      json: true
    };

    requestPromise(options)
      .then(files => {
        for (let i = 0; i < files.length; i ++) {
          var fileName = files[i]['name'];
          var fileUrl = files[i]['download_url'];
          request
            .get(fileUrl)
            .on('error', err => {
              this.log('There was an error when downloading the file ' + fileName);
              this.log(err);
            })
            .pipe(fs.createWriteStream(path.resolve(fileName)));

          this.log('Downloading file ' + fileName + ' to:');
          this.log(path.resolve(fileName));
        }
      })
      .catch(err => {
        this.log('There was an error in searching for the files for the template ' + templateToUse);
        this.log(err);
      })
  }
});<commit_msg>Needs to make sure dependencies are installed<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var request = require('request');
var requestPromise = require('request-promise');
var fs = require('fs');
var path = require('path');

module.exports = yeoman.Base.extend({
  prompting: function () {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ' + chalk.red('Azure Functions') + ' generator!'
    ));

    this.installDependencies();

    var prompts = [{
      type: 'confirm',
      name: 'requestFunctionTemplates',
      message: 'Would you like to see the available templates?',
      default: true
    }];

    return this.prompt(prompts).then(answer => {
      // To access answer later use this.answer.(answer you need);
      this.answer = answer;
    });
  },

  configuring: function () {
    /*
    Notes:

    1. Fetch Templates url for list of templates
    https://api.github.com/repos/Azure/azure-webjobs-sdk-templates/contents/Templates
    2. Parse url json to get list of templates
    3. Put list into prompts and ask user which template to download
    4. Download the requested Template!

    Steps to download the template files:
    1. Use request promise to get the right download url
    2. Match the chosen template with the right url
    3. Download the files to the current directory!
    */

    if (this.answer.requestFunctionTemplates) {
      var listOfTemplates = [];
      var listOfUrls = [];

      var options = {
        uri: 'https://api.github.com/repos/Azure/azure-webjobs-sdk-templates/contents/Templates',
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true
      };

      requestPromise(options)
        .then(templates => {
          this.log('There are %d templates available', templates.length);

          for (let i = 0; i < templates.length; i ++) {
            listOfTemplates[i] = templates[i]['name'];
            listOfUrls[listOfTemplates[i]] = templates[i]['url'];
          }

          var prompts = [{
              type: 'list',
              name: 'templateToUse',
              message: 'Select from one of the available templates...',
              choices: listOfTemplates,
              default: 0
          }];

          return this.prompt(prompts).then(answer => {
            this.answer = answer;
          });
        })
        .then(() => {
          this._downloadTemplate(this.answer.templateToUse, listOfUrls);
        })
        .catch(err => {
          this.log('There was an error in searching for available templates...');
          this.log(err);
        })
    }
  },

  _downloadTemplate: function (templateToUse, listOfUrls) {
    var options = {
      uri: listOfUrls[templateToUse],
      headers: {
          'User-Agent': 'Request-Promise'
      },
      json: true
    };

    requestPromise(options)
      .then(files => {
        for (let i = 0; i < files.length; i ++) {
          var fileName = files[i]['name'];
          var fileUrl = files[i]['download_url'];
          request
            .get(fileUrl)
            .on('error', err => {
              this.log('There was an error when downloading the file ' + fileName);
              this.log(err);
            })
            .pipe(fs.createWriteStream(path.resolve(fileName)));

          this.log('Downloading file ' + fileName + ' to:');
          this.log(path.resolve(fileName));
        }
      })
      .catch(err => {
        this.log('There was an error in searching for the files for the template ' + templateToUse);
        this.log(err);
      })
  }
});<|endoftext|>


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

module.exports = class extends BaseGenerator {
    get initializing() {
        return {
            init() {
                // This adds support for a `--all-entities` flag
                this.option('all-entities', {
                    desc: 'Apply grpc to all entities',
                    type: Boolean,
                    defaults: false
                });
            },
            readConfig() {
                this.jhipsterAppConfig = this.getJhipsterAppConfig();
                if (!this.jhipsterAppConfig) {
                    this.error('Can\'t read .yo-rc.json');
                }
            },
            displayLogo: function () {
                this.log('Welcome to the ' + chalk.red('JHipster grpc') + ' generator! ' + chalk.yellow('v' + packagejs.version + '\n'));
                /*if (this.jhipsterAppConfig.testFrameworks.includes('gatling')) {
                    this.log(chalk.red('Applications using Gatling are currently not supported (see https://github.com/cbornet/generator-jhipster-grpc/issues/4)'));
                    this.abort = true;
                }*/
            },
            checkJhipster() {
                const currentJhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
                const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
                if (!semver.satisfies(currentJhipsterVersion, minimumJhipsterVersion)) {
                    this.warning(`\nYour generated project used an old JHipster version (${currentJhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
                }
            }
        };
    }

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

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

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

        const done = this.async();

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

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

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

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

                this.baseName = this.jhipsterAppConfig.baseName;
                this.mainClass = this.getMainClassName();
                this.packageFolder = this.jhipsterAppConfig.packageFolder;
                this.packageName = this.jhipsterAppConfig.packageName;
                this.applicationType = this.jhipsterAppConfig.applicationType;
                this.authenticationType = this.jhipsterAppConfig.authenticationType;
                this.databaseType = this.jhipsterAppConfig.databaseType;
                this.searchEngine = this.jhipsterAppConfig.searchEngine;
                this.skipUserManagement = this.jhipsterAppConfig.skipUserManagement;
                if (this.applicationType === 'gateway' && this.authenticationType === 'uaa') {
                    this.skipUserManagement = true;
                }
                this.buildTool = this.jhipsterAppConfig.buildTool;

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

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

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

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

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

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

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

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

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

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

                this.template('_profile_info.proto', protoPackageDir + 'profile_info.proto');
                this.template('_ProfileInfoService.java', javaDir + 'grpc/ProfileInfoService.java');
                this.template('_ProfileInfoServiceIntTest.java', testDir + 'grpc/ProfileInfoServiceIntTest.java');

                this.grpcVersion = '1.6.1';
                this.protocVersion = '3.1.0';
                //const guavaVersion = '20.0';
                //const nettyVersion = '4.1.8.Final';
                this.reactiveGrpcVersion = '0.7.2';

                this.addCompileDependency('org.lognet', 'grpc-spring-boot-starter', '2.0.0', this.buildTool);
                // Resolve conflict with springfox
                // Still needed ?
                // this.addCompileDependency('com.google.guava', 'guava', guavaVersion, this.buildTool);
                this.addCompileDependency('com.google.protobuf', 'protobuf-java', this.protocVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-core', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-context', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-netty', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-protobuf', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-stub', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.projectreactor', 'reactor-core', '3.1.1.RELEASE', this.buildTool);
                this.addCompileDependency('com.salesforce.servicelibs', 'reactor-grpc-stub', this.reactiveGrpcVersion, this.buildTool);
                if (this.databaseType === 'cassandra' || ['microservice', 'gateway', 'uaa'].includes(this.applicationType)) {
                    // grpc-java needs netty 4.1
                    // Still needed ?
                    // this.addCompileDependency('io.netty', 'netty-handler', nettyVersion, this.buildTool);
                }

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

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

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

            },

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

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

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

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

module.exports = class extends BaseGenerator {
    get initializing() {
        return {
            init() {
                // This adds support for a `--all-entities` flag
                this.option('all-entities', {
                    desc: 'Apply grpc to all entities',
                    type: Boolean,
                    defaults: false
                });
            },
            readConfig() {
                this.jhipsterAppConfig = this.getJhipsterAppConfig();
                if (!this.jhipsterAppConfig) {
                    this.error('Can\'t read .yo-rc.json');
                }
            },
            displayLogo: function () {
                this.log('Welcome to the ' + chalk.red('JHipster grpc') + ' generator! ' + chalk.yellow('v' + packagejs.version + '\n'));
                /*if (this.jhipsterAppConfig.testFrameworks.includes('gatling')) {
                    this.log(chalk.red('Applications using Gatling are currently not supported (see https://github.com/cbornet/generator-jhipster-grpc/issues/4)'));
                    this.abort = true;
                }*/
            },
            checkJhipster() {
                const currentJhipsterVersion = this.jhipsterAppConfig.jhipsterVersion;
                const minimumJhipsterVersion = packagejs.dependencies['generator-jhipster'];
                if (!semver.satisfies(currentJhipsterVersion, minimumJhipsterVersion)) {
                    this.warning(`\nYour generated project used an old JHipster version (${currentJhipsterVersion})... you need at least (${minimumJhipsterVersion})\n`);
                }
            }
        };
    }

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

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

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

        const done = this.async();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                this.template('_profile_info.proto', protoPackageDir + 'profile_info.proto');
                this.template('_ProfileInfoService.java', javaDir + 'grpc/ProfileInfoService.java');
                this.template('_ProfileInfoServiceIntTest.java', testDir + 'grpc/ProfileInfoServiceIntTest.java');

                this.grpcVersion = '1.6.1';
                this.protocVersion = '3.1.0';
                //const guavaVersion = '20.0';
                //const nettyVersion = '4.1.8.Final';
                this.reactiveGrpcVersion = '0.7.2';

                this.addCompileDependency('org.lognet', 'grpc-spring-boot-starter', '2.0.0', this.buildTool);
                // Resolve conflict with springfox
                // Still needed ?
                // this.addCompileDependency('com.google.guava', 'guava', guavaVersion, this.buildTool);
                this.addCompileDependency('com.google.protobuf', 'protobuf-java', this.protocVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-core', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-context', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-netty', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-protobuf', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.grpc', 'grpc-stub', this.grpcVersion, this.buildTool);
                this.addCompileDependency('io.projectreactor', 'reactor-core', '3.1.1.RELEASE', this.buildTool);
                this.addCompileDependency('com.salesforce.servicelibs', 'reactor-grpc-stub', this.reactiveGrpcVersion, this.buildTool);
                if (this.databaseType === 'cassandra' || ['microservice', 'gateway', 'uaa'].includes(this.applicationType)) {
                    // grpc-java needs netty 4.1
                    // Still needed ?
                    // this.addCompileDependency('io.netty', 'netty-handler', nettyVersion, this.buildTool);
                }

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

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

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

            },

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

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

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

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


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

module.exports = yeoman.generators.Base.extend({
    prompting: function () {
        var done = this.async();

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

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

        this.prompt(prompts, function (props) {
            this.props = props;
            // To access props later use this.props.someOption;

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

    writing: {
        // ToDo:
        // - Check Repo Url
        //   - Generate Travis Image in README
        // - Check project type (bundle, library, app)
        //   - add typ to README
        app: function () {
            var templateParameters = {
                'year': new Date().getFullYear()
            };
            this.fs.copyTpl(
                this.templatePath('_LICENSE'),
                this.destinationPath('LICENSE'),
                templateParameters
            );
            this.fs.copyTpl(
                this.templatePath('_README.md'),
                this.destinationPath('README.md'),
                templateParameters
            );
        }
    },

    install: function () {
        this.installDependencies();
    }
});
<commit_msg>added note<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
    prompting: function () {
        var done = this.async();

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

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

        this.prompt(prompts, function (props) {
            this.props = props;
            // To access props later use this.props.someOption;

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

    writing: {
        // ToDo:
        // - Check Repo Url
        //   - Generate Travis Image in README
        // - Check project type (bundle, library, app)
        //   - add typ to README
        // - add Travis config
        app: function () {
            var templateParameters = {
                'year': new Date().getFullYear()
            };
            this.fs.copyTpl(
                this.templatePath('_LICENSE'),
                this.destinationPath('LICENSE'),
                templateParameters
            );
            this.fs.copyTpl(
                this.templatePath('_README.md'),
                this.destinationPath('README.md'),
                templateParameters
            );
        }
    },

    install: function () {
        this.installDependencies();
    }
});
<|endoftext|>


<commit_before>var terminalContainer = document.getElementById('terminal-container'),
    term = new Terminal(),
    prompt = '> ';

term.open(terminalContainer);
term.fit();

term.prompt = function () {
  term.write('\r\n' + prompt);
};

term.writeln('Welcome to xterm.js');
term.writeln('Just type some keys in the prompt below.');
term.writeln('');
term.prompt();

term.on('key', function (key, ev) {
  var printable = (!ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey);

  if (ev.keyCode == 13) {
    term.prompt();
  } else if (ev.keyCode == 8) {
    /*
     * Do not delete the prompt
     */
    if (term.x > 2) {
      term.write('\b \b');
    }
  } else if (printable) {
    term.write(key);
  }
});<commit_msg>Update main.js<commit_after>var terminalContainer = document.getElementById('terminal-container'),
    term = new Terminal(),
    shellprompt = '> ';

term.open(terminalContainer);
term.fit();

term.prompt = function () {
  term.write('\r\n' + shellprompt);
};

term.writeln('Welcome to xterm.js');
term.writeln('Just type some keys in the prompt below.');
term.writeln('');
term.prompt();

term.on('key', function (key, ev) {
  var printable = (!ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey);

  if (ev.keyCode == 13) {
    term.prompt();
  } else if (ev.keyCode == 8) {
    /*
     * Do not delete the prompt
     */
    if (term.x > 2) {
      term.write('\b \b');
    }
  } else if (printable) {
    term.write(key);
  }
});
<|endoftext|>


<commit_before>const { join } = require('path')
const { src, dest, watch, series, parallel } = require('gulp')
const umd = require('gulp-umd')

const rimraf = require('gulp-rimraf')
const uglify = require('gulp-uglify')
const concat = require('gulp-concat')
const rename = require('gulp-rename')
const eslint = require('gulp-eslint')
const { reload, server } = require('gulp-connect')
const babel = require('gulp-babel')

const sass = require('gulp-sass')
sass.compiler = require('node-sass')

// paths
const distFolder = 'dist'
const jsFiles = 'src/js/**/*'
const sassFiles = 'src/sass/**/*'

const clean = () => {
  return src(join(distFolder, '*'), { read: false })
    .pipe(rimraf())
}

const buildJsRaw = () => {
  return src(jsFiles)
    .pipe(concat({ path: 'metricsgraphics.js' }))
    .pipe(babel({
      presets: ['env']
    }))
    .pipe(umd(
      {
        exports: () => 'MG',
        namespace: () => 'MG'
      }
    ))
    .pipe(dest(distFolder))
    .pipe(rename('metricsgraphics.min.js'))
    .pipe(uglify())
    .pipe(dest(distFolder))
}

const buildJs = series(clean, buildJsRaw)

const lint = () => {
  return src(jsFiles)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
}

const compileSass = () => src(sassFiles)
  .pipe(sass().on('error', sass.logError))
  .pipe(dest(distFolder))

const watchSass = () => watch(sassFiles, compileSass)

const roots = ['dist', 'examples']
const watchables = roots.map(root => `${root}/**/*`)

const devReload = () => src(watchables).pipe(reload())
const devWatch = () => parallel(watch(watchables, devReload), watch(sassFiles, compileSass))

const devServe = () => server({
  root: roots,
  port: 4300,
  livereload: true
})

exports.clean = clean
exports.default = series(lint, buildJs, compileSass)
exports.serve = series(compileSass, devServe, devWatch)
exports.lint = lint
exports.compileSass = compileSass
exports.watchSass = watchSass
<commit_msg>clean up gulpfile<commit_after>const { src, dest, watch } = require('gulp')

const eslint = require('gulp-eslint')

const sass = require('gulp-sass')
sass.compiler = require('node-sass')

// paths
const distFolder = 'dist'
const jsFiles = 'src/js/**/*'
const sassFiles = 'src/sass/**/*'

const lint = () => {
  return src(jsFiles)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
}

const compileSass = () => src(sassFiles)
  .pipe(sass().on('error', sass.logError))
  .pipe(dest(distFolder))

const watchSass = () => watch(sassFiles, compileSass)

exports.lint = lint
exports.compileSass = compileSass
exports.watchSass = watchSass
<|endoftext|>