Пример #1
0
def prompt_github_repo(dot_cookietemple: Optional[dict]) -> Tuple[bool, bool, bool, str]:
    """
    Ask user for all settings needed in order to create and push automatically to GitHub repo.

    :param dot_cookietemple: .cookietemple.yml content if passed
    :return if is git repo, if repo should be private, if user is an organization and if so, the organizations name
    """
    # if dot_cookietemple dict was passed -> return the Github related properties and do NOT prompt for them
    try:
        if dot_cookietemple:
            if not dot_cookietemple['is_github_orga']:
                return dot_cookietemple['is_github_repo'], dot_cookietemple['is_repo_private'], False, ''
            else:
                return dot_cookietemple['is_github_repo'], dot_cookietemple['is_repo_private'], dot_cookietemple['is_github_orga'], \
                       dot_cookietemple['github_orga']
    except KeyError:
        print('[bold red]Missing required Github properties in .cookietemple.yml file!')

    # No dot_cookietemple_dict was passed -> prompt whether to create a Github repository and the required settings
    create_git_repo, private, is_github_org, github_org = False, False, False, ''
    if cookietemple_questionary_or_dot_cookietemple(function='confirm',
                                                    question='Do you want to create a Github repository and push your template to it?',
                                                    default='Yes'):
        create_git_repo = True
        is_github_org = cookietemple_questionary_or_dot_cookietemple(function='confirm',  # type: ignore
                                                                     question='Do you want to create an organization repository?',
                                                                     default='No')
        github_org = cookietemple_questionary_or_dot_cookietemple(function='text',  # type: ignore
                                                                  question='Please enter the name of the Github organization',
                                                                  default='SpringfieldNuclearPowerPlant') if is_github_org else ''
        private = cookietemple_questionary_or_dot_cookietemple(function='confirm',  # type: ignore
                                                               question='Do you want your repository to be private?',
                                                               default='No')

    return create_git_repo, private, is_github_org, github_org
Пример #2
0
    def config_general_settings() -> None:
        """
        Set full_name and email for reuse in any project created further on.
        """
        ConfigCommand.check_ct_config_dir_exists()
        full_name = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                 question='Full name',
                                                                 default='Homer Simpson')
        email = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                             question='Personal or work email',
                                                             default='*****@*****.**')
        github_username = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                       question='Github username',
                                                                       default='HomerGithub')

        # if the configs exist, just update them
        if os.path.exists(ConfigCommand.CONF_FILE_PATH):
            log.debug(f'Configuration was found at {ConfigCommand.CONF_FILE_PATH}. Updating configuration...')
            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML()
            settings = yaml.load(path)

            # update the full_name and email
            settings['full_name'] = full_name
            settings['email'] = email
            settings['github_username'] = github_username
            yaml.dump(settings, Path(ConfigCommand.CONF_FILE_PATH))

        # the configs don´t exist -> create them
        else:
            log.debug(f'Configuration was not found at {ConfigCommand.CONF_FILE_PATH}. Creating a new configuration file.')
            settings = {'full_name': full_name, 'email': email, 'github_username': github_username}
            yaml = YAML()
            yaml.dump(settings, Path(ConfigCommand.CONF_FILE_PATH))
Пример #3
0
 def check_name_available(self, host, dot_cookietemple) -> None:
     """
     Main function that calls the queries for the project name lookup at PyPi and readthedocs.io
     """
     # if project already exists at either PyPi or readthedocs, ask user for confirmation with the option to change the project name
     while TemplateCreator.query_name_available(
             host, self.creator_ctx.project_name
     ) and not dot_cookietemple:  # type: ignore
         console.print(
             f'[bold red]A project named {self.creator_ctx.project_name} already exists at {host}!'
         )
         # provide the user an option to change the project's name
         if cookietemple_questionary_or_dot_cookietemple(
                 function='confirm',
                 question=
                 'Do you want to choose another name for your project?\n'
                 f'Otherwise you will not be able to host your project at {host}!',
                 default='Yes'):
             self.creator_ctx.project_name = cookietemple_questionary_or_dot_cookietemple(
                 function='text',
                 question='Project name',
                 default='Exploding Springfield')
         # continue if the project should be named anyways
         else:
             break
Пример #4
0
 def common_latex_options(self, dot_cookietemple: Optional[dict]) -> None:
     """
     Prompt the user for common thesis/paper data
     """
     self.pub_struct.author = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                           question='Author',
                                                                           default='Homer Simpson',
                                                                           dot_cookietemple=dot_cookietemple,
                                                                           to_get_property='author')
     self.pub_struct.project_name = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                                 question='Project name',
                                                                                 default='PhD Thesis',
                                                                                 dot_cookietemple=dot_cookietemple,
                                                                                 to_get_property='project_name')
     self.pub_struct.project_slug = self.pub_struct.project_name.replace(' ', '_').replace('-', '_')  # type: ignore
     self.pub_struct.title = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                          question='Publication title',
                                                                          default='On how Springfield exploded',
                                                                          dot_cookietemple=dot_cookietemple,
                                                                          to_get_property='title')
     self.pub_struct.university = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                               question='University',
                                                                               default='Homer J. Simpson University',
                                                                               dot_cookietemple=dot_cookietemple,
                                                                               to_get_property='university')
     self.pub_struct.department = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                               question='Department',
                                                                               default='Department of Nuclear Physics',
                                                                               dot_cookietemple=dot_cookietemple,
                                                                               to_get_property='department')
     self.pub_struct.github_username = load_github_username()  # Required for Github support
Пример #5
0
    def handle_website_python(self, dot_cookietemple: Optional[dict]) -> None:
        """
        Handle the website template creation. The user can choose between a basic website setup and a more advanced
        with database support, mail, translation, cli commands for translation, login and register function.
        """
        self.web_struct.web_framework = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="Choose between the following frameworks",
            choices=["flask"],
            default="flask",
            dot_cookietemple=dot_cookietemple,
            to_get_property="web_framework",
        )
        self.web_struct.setup_type = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="Choose between the basic and advanced"
            " (database, translations, deployment scripts) template",
            choices=["basic", "advanced"],
            default="basic",
            dot_cookietemple=dot_cookietemple,
            to_get_property="setup_type",
        )

        self.web_struct.use_frontend = cookietemple_questionary_or_dot_cookietemple(
            function="confirm",
            question="Do you want to initialize your project"
            " with a advanced frontend template?",
            default="Yes",
            dot_cookietemple=dot_cookietemple,
            to_get_property="use_frontend",
        )

        # prompt the user for its frontend template, if he wants so
        if self.web_struct.use_frontend:
            print("[bold blue]The following templates are available:\n")

            # strings that start with https: are recognized by most terminal (emulators) as links
            print("[bold blue]https://html5up.net/solid-state")

            self.web_struct.frontend = cookietemple_questionary_or_dot_cookietemple(
                function="select",  # type: ignore
                question=
                "Choose between the following predefined frontend templates",
                choices=["SolidState", "None"],
                dot_cookietemple=dot_cookietemple,
                to_get_property="frontend",
            ).lower()

        self.web_struct.url = cookietemple_questionary_or_dot_cookietemple(
            function="text",
            question="Project URL (if already existing)",
            default="dummy.com",
            dot_cookietemple=dot_cookietemple,
            to_get_property="url",
        )
Пример #6
0
    def config_pat() -> None:
        """
        Set the personal access token (PAT) for automatic Github repo creation.
        """
        ConfigCommand.check_ct_config_dir_exists()
        try:
            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML()
            settings = yaml.load(path)
            if not all(attr in settings for attr in ['full_name', 'github_username', 'email']):
                print('[bold red]The cookietemple config file misses some required attributes!')
                print('[bold blue]Lets set them before setting your Github personal access token!')
                ConfigCommand.config_general_settings()

        except FileNotFoundError:
            print('[bold red]Cannot find a cookietemple config file. Is this your first time using cookietemple?')
            print('[bold blue]Lets create one before setting your Github personal access token!')
            ConfigCommand.config_general_settings()

        if cookietemple_questionary_or_dot_cookietemple(function='confirm',
                                                        question='Do you want to configure your GitHub personal access token right now?\n'
                                                        'You can still configure it later by calling    cookietemple config pat',
                                                        default='Yes'):
            print('[bold blue]cookietemple requires your Github Access token to have full repository and workflow permissions!')
            access_token = cookietemple_questionary_or_dot_cookietemple('password', 'Please enter your Github Access token')
            access_token_b = access_token.encode('utf-8')  # type: ignore

            # ask for confirmation since this action will delete the PAT irrevocably if the user has not saved it anywhere else
            if not cookietemple_questionary_or_dot_cookietemple(function='confirm',
                                                                question='You´re about to update your personal access token. This action cannot be undone!\n'
                                                                         'Do you really want to continue?',
                                                                default='Yes'):
                sys.exit(1)

            # encrypt the given PAT and save the encryption key and encrypted PAT in separate files
            print('[bold blue]Generating key for encryption.')
            log.debug('Generating personal access key.')
            key = Fernet.generate_key()
            fer = Fernet(key)
            log.debug('Encrypting personal access token. ')
            print('[bold blue]Encrypting personal access token.')
            encrypted_pat = fer.encrypt(access_token_b)

            # write key
            log.debug(f'Writing key to {ConfigCommand.KEY_PAT_FILE}')
            with open(ConfigCommand.KEY_PAT_FILE, 'wb') as f:
                f.write(key)

            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML()
            settings = yaml.load(path)
            settings['pat'] = encrypted_pat
            log.debug(f'Dumping configuration to {ConfigCommand.CONF_FILE_PATH}')
            yaml.dump(settings, Path(ConfigCommand.CONF_FILE_PATH))
Пример #7
0
 def cli_java_options(self, dot_cookietemple: Optional[dict]) -> None:
     """ Prompts for cli-java specific options and saves them into the CookietempleTemplateStruct """
     self.cli_struct.group_domain = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                                 question='Domain (e.g. the org of org.apache)',
                                                                                 default='com',
                                                                                 dot_cookietemple=dot_cookietemple,
                                                                                 to_get_property='group_domain')
     self.cli_struct.group_organization = cookietemple_questionary_or_dot_cookietemple(function='text',
                                                                                       question='Organization (e.g. the apache of org.apache)',
                                                                                       default='organization',
                                                                                       dot_cookietemple=dot_cookietemple,
                                                                                       to_get_property='group_organization')
     self.cli_struct.main_class = self.cli_struct.project_slug_no_hyphen.capitalize()
Пример #8
0
    def handle_website_python(self, dot_cookietemple: Optional[dict]) -> None:
        """
        Handle the website template creation. The user can choose between a basic website setup and a more advanced
        with database support, mail, translation, cli commands for translation, login and register function.
        """
        self.web_struct.web_framework = cookietemple_questionary_or_dot_cookietemple(
            function='select',
            question='Choose between the following frameworks',
            choices=['flask'],
            default='flask',
            dot_cookietemple=dot_cookietemple,
            to_get_property='web_framework')
        self.web_struct.setup_type = cookietemple_questionary_or_dot_cookietemple(
            function='select',
            question='Choose between the basic and advanced'
            ' (database, translations, deployment scripts) template',
            choices=['basic', 'advanced'],
            default='basic',
            dot_cookietemple=dot_cookietemple,
            to_get_property='setup_type')

        self.web_struct.use_frontend = cookietemple_questionary_or_dot_cookietemple(
            function='confirm',
            question='Do you want to initialize your project'
            ' with a advanced frontend template?',
            default='Yes',
            dot_cookietemple=dot_cookietemple,
            to_get_property='use_frontend')

        # prompt the user for its frontend template, if he wants so
        if self.web_struct.use_frontend:
            print('[bold blue]The following templates are available:\n')

            # strings that start with https: are recognized by most terminal (emulators) as links
            print('[bold blue]https://html5up.net/solid-state')

            self.web_struct.frontend = cookietemple_questionary_or_dot_cookietemple(
                function='select',  # type: ignore
                question=
                'Choose between the following predefined frontend templates',
                choices=['SolidState', 'None'],
                dot_cookietemple=dot_cookietemple,
                to_get_property='frontend').lower()

        self.web_struct.url = cookietemple_questionary_or_dot_cookietemple(
            function='text',
            question='Project URL (if already existing)',
            default='dummy.com',
            dot_cookietemple=dot_cookietemple,
            to_get_property='url')
Пример #9
0
    def config_general_settings() -> None:
        """
        Set full_name and email for reuse in any project created further on.
        """
        ConfigCommand.check_ct_config_dir_exists()
        full_name = cookietemple_questionary_or_dot_cookietemple(
            function="text", question="Full name", default="Homer Simpson")
        email = cookietemple_questionary_or_dot_cookietemple(
            function="text",
            question="Personal or work email",
            default="*****@*****.**")
        github_username = cookietemple_questionary_or_dot_cookietemple(
            function="text", question="Github username", default="HomerGithub")
        create_ct_topic = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question=
            "Automatically create a cookietemple Github topic for new projects?",
            choices=["Yes", "No"],
            default="Yes",
        )

        # if the configs exist, just update them
        if os.path.exists(ConfigCommand.CONF_FILE_PATH):
            log.debug(
                f"Configuration was found at {ConfigCommand.CONF_FILE_PATH}. Updating configuration..."
            )
            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML()
            settings = yaml.load(path)

            # update the full_name and email
            settings["full_name"] = full_name
            settings["email"] = email
            settings["github_username"] = github_username
            settings["create_ct_topic"] = create_ct_topic
            yaml.dump(settings, Path(ConfigCommand.CONF_FILE_PATH))

        # the configs don´t exist -> create them
        else:
            log.debug(
                f"Configuration was not found at {ConfigCommand.CONF_FILE_PATH}. Creating a new configuration file."
            )
            settings = {
                "full_name": full_name,
                "email": email,
                "github_username": github_username,
                "create_ct_topic": create_ct_topic,
            }
            yaml = YAML()
            yaml.dump(settings, Path(ConfigCommand.CONF_FILE_PATH))
Пример #10
0
 def web_python_options(self, dot_cookietemple: Optional[dict]):
     """ Prompts for web-python specific options and saves them into the CookietempleTemplateStruct """
     self.web_struct.command_line_interface = cookietemple_questionary_or_dot_cookietemple(
         function='select',
         question='Choose a command line library',
         choices=['Click', 'Argparse', 'No command-line interface'],
         default='Click',
         dot_cookietemple=dot_cookietemple,
         to_get_property='command_line_interface')
     self.web_struct.testing_library = cookietemple_questionary_or_dot_cookietemple(
         function='select',
         question='Choose a testing library',
         choices=['pytest', 'unittest'],
         default='pytest',
         dot_cookietemple=dot_cookietemple,
         to_get_property='testing_library')
Пример #11
0
 def handle_thesis_latex(self, dot_cookietemple: Optional[dict]) -> None:
     self.pub_struct.degree = cookietemple_questionary_or_dot_cookietemple(
         function='text',
         question='Degree',
         default='PhD',
         dot_cookietemple=dot_cookietemple,
         to_get_property='degree')
Пример #12
0
    def create_template_without_subdomain(self, domain_path: str) -> None:
        """
        Creates a chosen template that does **not** have a subdomain.
        Calls cookiecutter on the main chosen template.

        :param domain_path: Path to the template, which is still in cookiecutter format
        """
        # Target directory is already occupied -> overwrite?
        occupied = os.path.isdir(
            f'{os.getcwd()}/{self.creator_ctx.project_slug}')
        if occupied:
            self.directory_exists_warning()

            # Confirm proceeding with overwriting existing directory
            if cookietemple_questionary_or_dot_cookietemple(
                    'confirm', 'Do you really want to continue?',
                    default='No'):
                cookiecutter(
                    f'{domain_path}/{self.creator_ctx.domain}_{self.creator_ctx.language.lower()}',
                    no_input=True,
                    overwrite_if_exists=True,
                    extra_context=self.creator_ctx_to_dict())
            else:
                print('[bold red]Aborted! Canceled template creation!')
                sys.exit(0)
        else:
            cookiecutter(
                f'{domain_path}/{self.creator_ctx.domain}_{self.creator_ctx.language.lower()}',
                no_input=True,
                overwrite_if_exists=True,
                extra_context=self.creator_ctx_to_dict())
Пример #13
0
def choose_domain(path: Path, domain: Union[str, bool], dot_cookietemple: Optional[dict]):
    """
    Prompts the user for the template domain.
    Creates the .cookietemple file.
    Prompts the user whether or not to create a Github repository

    :param domain: Template domain
    :param dot_cookietemple: Dictionary created from the .cookietemple.yml file. None if no .cookietemple.yml file was used.
    """
    if not domain:
        domain = cookietemple_questionary_or_dot_cookietemple(function='select',
                                                              question='Choose the project\'s domain',
                                                              choices=['cli', 'lib', 'gui', 'web', 'pub'],
                                                              default='cli',
                                                              dot_cookietemple=dot_cookietemple,
                                                              to_get_property='domain')

    switcher = {
        'cli': CliCreator,
        'web': WebCreator,
        'gui': GuiCreator,
        'lib': LibCreator,
        'pub': PubCreator
    }

    creator_obj: Union[CliCreator, WebCreator, GuiCreator, LibCreator, PubCreator] = switcher.get(domain.lower())()  # type: ignore
    creator_obj.create_template(path, dot_cookietemple)
Пример #14
0
    def lint(self, is_create, skip_external):
        super().lint_project(self, self.methods)

        # Call autopep8, if needed
        if is_create:
            print('[blue]Running autopep8 to fix pep8 issues in place')
            autopep8 = Popen([
                'autopep8', self.path, '--recursive', '--in-place',
                '--pep8-passes', '2000'
            ],
                             universal_newlines=True,
                             shell=False,
                             close_fds=True)
            (autopep8_stdout, autopep8_stderr) = autopep8.communicate()
        elif skip_external:
            pass
        elif cookietemple_questionary_or_dot_cookietemple(
                function='confirm',
                question='Do you want to run autopep8 to fix pep8 issues?',
                default='n'):
            print('[blue]Running autopep8 to fix pep8 issues in place')
            autopep8 = Popen([
                'autopep8', self.path, '--recursive', '--in-place',
                '--pep8-passes', '2000'
            ],
                             universal_newlines=True,
                             shell=False,
                             close_fds=True)
            (autopep8_stdout, autopep8_stderr) = autopep8.communicate()
Пример #15
0
    def create_template_with_subdomain(self, domain_path: str,
                                       subdomain: str) -> None:
        """
        Creates a chosen template that **does** have a subdomain.
        Calls cookiecutter on the main chosen template.

        :param domain_path: Path to the template, which is still in cookiecutter format
        :param subdomain: Subdomain of the chosen template
        """
        occupied = os.path.isdir(f'{self.CWD}/{self.creator_ctx.project_slug}')
        if occupied:
            self.directory_exists_warning()

            # Confirm proceeding with overwriting existing directory
            if cookietemple_questionary_or_dot_cookietemple(
                    'confirm', 'Do you really want to continue?',
                    default='Yes'):
                delete_dir_tree(
                    Path(f'{self.CWD}/{self.creator_ctx.project_slug}'))
                cookiecutter(
                    f'{domain_path}/{subdomain}_{self.creator_ctx.language.lower()}',
                    no_input=True,
                    overwrite_if_exists=True,
                    extra_context=self.creator_ctx_to_dict())

            else:
                console.print('[bold red]Aborted! Canceled template creation!')
                sys.exit(0)
        else:
            cookiecutter(
                f'{domain_path}/{subdomain}_{self.creator_ctx.language.lower()}',
                no_input=True,
                overwrite_if_exists=True,
                extra_context=self.creator_ctx_to_dict())
Пример #16
0
def choose_domain(path: Path, domain: Union[str, bool],
                  dot_cookietemple: Optional[dict]):
    """
    Prompts the user for the template domain.
    Creates the .cookietemple file.
    Prompts the user whether or not to create a Github repository

    :param domain: Template domain
    :param dot_cookietemple: Dictionary created from the .cookietemple.yml file. None if no .cookietemple.yml file was used.
    """
    if not domain:
        domain = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="Choose the project's domain",
            choices=["cli", "lib", "gui", "web", "pub"],
            default="cli",
            dot_cookietemple=dot_cookietemple,
            to_get_property="domain",
        )

    switcher = {
        "cli": CliCreator,
        "web": WebCreator,
        "gui": GuiCreator,
        "lib": LibCreator,
        "pub": PubCreator
    }

    creator_obj: Union[CliCreator, WebCreator, GuiCreator, LibCreator,
                       PubCreator] = switcher.get(
                           domain.lower())()  # type: ignore
    creator_obj.create_template(path, dot_cookietemple)
Пример #17
0
    def create_template_with_subdomain_framework(self, domain_path: str, subdomain: str, framework: str) -> None:
        """
        Creates a chosen template that **does** have a subdomain.
        Calls cookiecutter on the main chosen template.

        :param domain_path: Path to the template, which is still in cookiecutter format
        :param subdomain: Subdomain of the chosen template
        :param framework: Chosen framework
        """
        occupied = os.path.isdir(f"{self.CWD}/{self.creator_ctx.project_slug}")
        if occupied:
            self.directory_exists_warning()

            # Confirm proceeding with overwriting existing directory
            if cookietemple_questionary_or_dot_cookietemple(
                "confirm", "Do you really want to continue?", default="Yes"
            ):
                cookiecutter(
                    f"{domain_path}/{subdomain}_{self.creator_ctx.language.lower()}/{framework}",
                    no_input=True,
                    overwrite_if_exists=True,
                    extra_context=self.creator_ctx_to_dict(),
                )

            else:
                console.print("[bold red]Aborted! Canceled template creation!")
                sys.exit(0)
        else:
            cookiecutter(
                f"{domain_path}/{subdomain}_{self.creator_ctx.language.lower()}/{framework}",
                no_input=True,
                overwrite_if_exists=True,
                extra_context=self.creator_ctx_to_dict(),
            )
Пример #18
0
 def handle_thesis_latex(self, dot_cookietemple: Optional[dict]) -> None:
     self.pub_struct.degree = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Degree",
         default="PhD",
         dot_cookietemple=dot_cookietemple,
         to_get_property="degree",
     )
Пример #19
0
 def web_python_options(self, dot_cookietemple: Optional[dict]):
     """ Prompts for web-python specific options and saves them into the CookietempleTemplateStruct """
     self.web_struct.command_line_interface = cookietemple_questionary_or_dot_cookietemple(
         function="select",
         question="Choose a command line library",
         choices=["Click", "Argparse", "No command-line interface"],
         default="Click",
         dot_cookietemple=dot_cookietemple,
         to_get_property="command_line_interface",
     )
     self.web_struct.testing_library = cookietemple_questionary_or_dot_cookietemple(
         function="select",
         question="Choose a testing library",
         choices=["pytest", "unittest"],
         default="pytest",
         dot_cookietemple=dot_cookietemple,
         to_get_property="testing_library",
     )
Пример #20
0
 def common_latex_options(self, dot_cookietemple: Optional[dict]) -> None:
     """
     Prompt the user for common thesis/paper data
     """
     self.pub_struct.author = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Author",
         default="Homer Simpson",
         dot_cookietemple=dot_cookietemple,
         to_get_property="author",
     )
     self.pub_struct.project_slug = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Project name",
         default="PhD Thesis",
         dot_cookietemple=dot_cookietemple,
         to_get_property="project_name",
     ).replace(  # type: ignore
         " ", "_")
     self.pub_struct.project_slug_no_hyphen = self.pub_struct.project_slug.replace(
         "-", "_")
     self.pub_struct.title = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Publication title",
         default="On how Springfield exploded",
         dot_cookietemple=dot_cookietemple,
         to_get_property="title",
     )
     self.pub_struct.university = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="University",
         default="Homer J. Simpson University",
         dot_cookietemple=dot_cookietemple,
         to_get_property="university",
     )
     self.pub_struct.department = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Department",
         default="Department of Nuclear Physics",
         dot_cookietemple=dot_cookietemple,
         to_get_property="department",
     )
     self.pub_struct.github_username = load_github_username(
     )  # Required for Github support
Пример #21
0
 def website_flask_options(self, dot_cookietemple: Optional[dict]) -> None:
     """
     Prompt for flask template options
     """
     # prompt username for virtual machine (needed for example when deploying from a Linux VM)
     self.web_struct.vmusername = cookietemple_questionary_or_dot_cookietemple(
         function='text',
         question='Virtual machine username (if already existing)',
         default='cookietempleuser',
         dot_cookietemple=dot_cookietemple,
         to_get_property='vmusername')
Пример #22
0
 def check_upgrade_cookietemple() -> None:
     """
     Checks whether the locally installed version of cookietemple is the latest.
     If not it prompts whether to upgrade and runs the upgrade command if desired.
     """
     if not UpgradeCommand.check_cookietemple_latest():
         if cookietemple_questionary_or_dot_cookietemple(
                 function='confirm',
                 question='Do you want to upgrade?',
                 default='y'):
             UpgradeCommand.upgrade_cookietemple()
Пример #23
0
 def handle_web_project_type_python(
         self, dot_cookietemple: Optional[dict]) -> None:
     """
     Determine the type of web application
     """
     self.web_struct.webtype = cookietemple_questionary_or_dot_cookietemple(
         function='select',
         question='Choose between the following web domains',
         choices=['website'],
         default='website',
         dot_cookietemple=dot_cookietemple,
         to_get_property='webtype')
Пример #24
0
    def create_template(self, path: Path, dot_cookietemple: Optional[dict]):
        """
        Handles the CLI domain. Prompts the user for the language, general and domain specific options.
        """
        self.cli_struct.language = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="Choose the project's primary language",
            choices=["python", "java"],
            default="python",
            dot_cookietemple=dot_cookietemple,
            to_get_property="language",
        )

        # prompt the user to fetch general template configurations
        super().prompt_general_template_configuration(dot_cookietemple)

        # switch case statement to prompt the user to fetch template specific configurations
        switcher: Dict[str, Any] = {
            "python": self.cli_python_options,
            "java": self.cli_java_options,
        }
        switcher.get(self.cli_struct.language)(
            dot_cookietemple)  # type: ignore

        (
            self.cli_struct.is_github_repo,
            self.cli_struct.is_repo_private,
            self.cli_struct.is_github_orga,
            self.cli_struct.github_orga,
        ) = prompt_github_repo(dot_cookietemple)

        if self.cli_struct.is_github_orga:
            self.cli_struct.github_username = self.cli_struct.github_orga
        # create the chosen and configured template
        super().create_template_without_subdomain(self.TEMPLATES_CLI_PATH)

        # switch case statement to fetch the template version
        switcher_version = {
            "python": self.CLI_PYTHON_TEMPLATE_VERSION,
            "java": self.CLI_JAVA_TEMPLATE_VERSION
        }
        self.cli_struct.template_version, self.cli_struct.template_handle = (
            switcher_version.get(self.cli_struct.language),  # type: ignore
            f"cli-{self.cli_struct.language.lower()}",  # type: ignore
        )

        # perform general operations like creating a GitHub repository and general linting
        super().process_common_operations(
            path=Path(path).resolve(),
            domain="cli",
            language=self.cli_struct.language,
            dot_cookietemple=dot_cookietemple,
        )
Пример #25
0
def bump_version(ctx, new_version, project_dir, downgrade, tag) -> None:
    """
    Bump the version of an existing cookietemple project.

    INFO on valid versions: All versions must match the format like 1.0.0 or 1.1.0-SNAPSHOT; these are the only valid
    version formats cookietemple allows. A valid version therefore contains a three digits (in the range from 0 to however large it will grow)
    separated by two dots.
    Optional is the -SNAPSHOT at the end (for JVM templates especially). NOTE that versions like 1.2.3.4 or 1.2 WILL NOT be recognized as valid versions as
    well as no substring of them will be recognized.

    Unless the user uses downgrade mode via the -d flag, a downgrade of a version is never allowed. Note that bump-version with the new version
    equals the current version is never allowed, either with or without -d.

    Users can create a commit tag for the version bump commit by using the --tag/-t flag.
    """
    create_tag = True if tag else False
    version_bumper = VersionBumper(project_dir, downgrade)
    # suggest valid version if none was given
    if not new_version:
        new_version = version_bumper.choose_valid_version()
    # if the path entered ends with a trailing slash remove it for consistent output
    if str(project_dir).endswith("/"):
        project_dir = Path(
            str(project_dir).replace(
                str(project_dir)[len(str(project_dir)) - 1:], ""))

    # lint before run bump-version
    version_bumper.lint_before_bump()
    # only run bump-version if conditions are met
    if version_bumper.can_run_bump_version(new_version):
        # only run "sanity" checker when the downgrade flag is not set
        if not downgrade:
            # if the check fails, ask the user for confirmation
            if version_bumper.check_bump_range(
                    version_bumper.CURRENT_VERSION.split("-")[0],
                    new_version.split("-")[0]):
                version_bumper.bump_template_version(new_version, project_dir,
                                                     create_tag)
            elif cookietemple_questionary_or_dot_cookietemple(
                    function="confirm",
                    question=
                    f"Bumping from {version_bumper.CURRENT_VERSION} to {new_version} seems not reasonable.\n"
                    f"Do you really want to bump the project version?",
                    default="n",
            ):
                console.print("\n")
                version_bumper.bump_template_version(new_version, project_dir,
                                                     create_tag)
        else:
            version_bumper.bump_template_version(new_version, project_dir,
                                                 create_tag)
    else:
        sys.exit(1)
Пример #26
0
    def create_template(self, path: Path, dot_cookietemple: Optional[Dict]):
        self.gui_struct.language = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="Choose between the following languages",
            choices=["java"],
            dot_cookietemple=dot_cookietemple,
            to_get_property="language",
        )

        # prompt the user to fetch general template configurations
        super().prompt_general_template_configuration(dot_cookietemple)

        # switch case statement to prompt the user to fetch template specific configurations
        switcher: Dict[str, Any] = {
            "java": self.gui_java_options,
        }
        switcher.get(self.gui_struct.language.lower())(
            dot_cookietemple)  # type: ignore

        (
            self.gui_struct.is_github_repo,
            self.gui_struct.is_repo_private,
            self.gui_struct.is_github_orga,
            self.gui_struct.github_orga,
        ) = prompt_github_repo(dot_cookietemple)

        if self.gui_struct.is_github_orga:
            self.gui_struct.github_username = self.gui_struct.github_orga
        # create the gui template
        super().create_template_without_subdomain(self.TEMPLATES_GUI_PATH)

        # switch case statement to fetch the template version
        switcher_version = {
            "java": self.GUI_JAVA_TEMPLATE_VERSION,
        }

        self.gui_struct.template_version, self.gui_struct.template_handle = (
            switcher_version.get(
                self.gui_struct.language.lower()),  # type: ignore
            f"gui-{self.gui_struct.language.lower()}",  # type: ignore
        )  # type: ignore

        # perform general operations like creating a GitHub repository and general linting
        super().process_common_operations(
            path=Path(path).resolve(),
            domain="gui",
            language=self.gui_struct.language,
            dot_cookietemple=dot_cookietemple,
        )
Пример #27
0
    def update_sync_token(project_name: str, gh_username: str = '') -> None:
        """
        Update the sync token secret for the repository.

        :param project_name Name of the users project
        :param gh_username The Github username (only gets passed, if the repo is an orga repo)
        """
        gh_username = load_yaml_file(ConfigCommand.CONF_FILE_PATH)['github_username'] if not gh_username else gh_username
        # get the personal access token for user authentification
        log.debug('Asking for updated sync token value.')
        updated_sync_token = cookietemple_questionary_or_dot_cookietemple(function='password',
                                                                          question='Please enter your updated sync token value')
        print(f'[bold blue]\nUpdating sync secret for project {project_name}.')
        create_sync_secret(gh_username, project_name, updated_sync_token)
        print(f'[bold blue]\nSuccessfully updated sync secret for project {project_name}.')
Пример #28
0
 def gui_java_options(self, dot_cookietemple: Optional[Dict]) -> None:
     """
     Prompt the user for all gui-java specific properties
     """
     # The user id is automatically determined from the full_name as first letter of first name and sur name
     full_name_split = self.creator_ctx.full_name.split()  # type: ignore
     self.gui_struct.id = (f"{full_name_split[0][0]}{full_name_split[1][0]}"
                           if len(full_name_split) > 1 else
                           f"{full_name_split[0][0]}")
     self.gui_struct.organization = cookietemple_questionary_or_dot_cookietemple(
         function="text",
         question="Organization",
         default="organization",
         dot_cookietemple=dot_cookietemple,
         to_get_property="organization",
     )
Пример #29
0
    def create_template(self, path: Path, dot_cookietemple: Optional[dict]):
        """
        Prompts the user for the publication type and forwards to subsequent prompts.
        Creates the pub template.
        """
        # latex is default language

        self.pub_struct.pubtype = cookietemple_questionary_or_dot_cookietemple(function='select',
                                                                               question='Choose between the following publication types',
                                                                               choices=['thesis'],
                                                                               dot_cookietemple=dot_cookietemple,
                                                                               to_get_property='pubtype')

        if not os.path.exists(ConfigCommand.CONF_FILE_PATH):
            print('[bold red]Cannot find a Cookietemple config file! Is this your first time with Cookietemple?\n')
            print('[bold blue]Lets set your configs for Cookietemple and you are ready to go!\n')
            ConfigCommand.all_settings()

        # switch case statement to prompt the user to fetch template specific configurations
        switcher: Dict[str, Any] = {
            'latex': self.common_latex_options,
        }
        switcher.get(self.pub_struct.language.lower(), lambda: 'Invalid language!')(dot_cookietemple)  # type: ignore

        self.handle_pub_type(dot_cookietemple)

        self.pub_struct.is_github_repo, self.pub_struct.is_repo_private, self.pub_struct.is_github_orga, self.pub_struct.github_orga \
            = prompt_github_repo(dot_cookietemple)

        if self.pub_struct.is_github_orga:
            self.pub_struct.github_username = self.pub_struct.github_orga
        # create the pub template
        super().create_template_with_subdomain(self.TEMPLATES_PUB_PATH, self.pub_struct.pubtype)  # type: ignore

        # switch case statement to fetch the template version
        switcher_version = {
            'latex': self.PUB_LATEX_TEMPLATE_VERSION,
        }

        self.pub_struct.template_version = switcher_version.get(self.pub_struct.language.lower(), lambda: 'Invalid language!')
        self.pub_struct.template_version, self.pub_struct.template_handle = switcher_version.get(
            self.pub_struct.language.lower(), lambda: 'Invalid language!'), f'pub-{self.pub_struct.pubtype}-{self.pub_struct.language.lower()}'

        # perform general operations like creating a GitHub repository and general linting, but skip common_files copying and rst linting
        super().process_common_operations(path=Path(path).resolve(), skip_common_files=True, skip_fix_underline=True,
                                          domain='pub', subdomain=self.pub_struct.pubtype, language=self.pub_struct.language,
                                          dot_cookietemple=dot_cookietemple)
Пример #30
0
    def create_template(self, path: Path, dot_cookietemple: Optional[dict]):
        """
        Handles the LIB domain. Prompts the user for the language, general and domain specific options.
        """

        self.lib_struct.language = cookietemple_questionary_or_dot_cookietemple(
            function='select',
            question='Choose the project\'s primary language',
            choices=['cpp'],
            default='cpp',
            dot_cookietemple=dot_cookietemple,
            to_get_property='language')

        # prompt the user to fetch general template configurations
        super().prompt_general_template_configuration(dot_cookietemple)

        # switch case statement to prompt the user to fetch template specific configurations
        switcher: Dict[str, Any] = {
            'cpp': self.lib_cpp_options,
        }
        switcher.get(self.lib_struct.language)(
            dot_cookietemple)  # type: ignore

        self.lib_struct.is_github_repo, \
            self.lib_struct.is_repo_private, \
            self.lib_struct.is_github_orga, \
            self.lib_struct.github_orga \
            = prompt_github_repo(dot_cookietemple)

        if self.lib_struct.is_github_orga:
            self.lib_struct.github_username = self.lib_struct.github_orga
        # create the chosen and configured template
        super().create_template_without_subdomain(self.TEMPLATES_LIB_PATH)

        # switch case statement to fetch the template version
        switcher_version = {
            'cpp': self.LIB_CPP_TEMPLATE_VERSION,
        }
        self.lib_struct.template_version, self.lib_struct.template_handle\
            = switcher_version.get(self.lib_struct.language), f'lib-{self.lib_struct.language.lower()}'  # type: ignore

        # perform general operations like creating a GitHub repository and general linting
        super().process_common_operations(path=Path(path).resolve(),
                                          domain='lib',
                                          language=self.lib_struct.language,
                                          dot_cookietemple=dot_cookietemple)