예제 #1
0
def config(ctx, view: bool, section: str) -> None:
    """
    Configure your general settings and Github credentials for reuse.
    Available options (sections) are:

    \b
    - general: set your fullname, email and Github username
    - pat: set your Github personal access token for Github repository creation
    - all: calls general and pat
    """
    if view:
        ConfigCommand.view_current_config()
        sys.exit(0)
    if section == 'general':
        # set the full_name and email for reuse in the creation process
        ConfigCommand.config_general_settings()
    elif section == 'pat':
        # set github username and encrypted personal access token
        ConfigCommand.config_pat()
    elif section == 'all':
        # set everything
        ConfigCommand.all_settings()
        # empty section argument causes a customized error
    elif not section:
        HelpErrorHandling.args_not_provided(ctx, 'config')
        # check if a similar section handle can be used/suggested
    else:
        ConfigCommand.similar_handle(section)
예제 #2
0
def handle_pat_authentification() -> str:
    """
    Try to read the encrypted Personal Access Token for GitHub.
    If this fails (maybe there was no generated key before) notify user to config its credentials for cookietemple.

    :return: The decrypted PAT
    """
    # check if the key and encrypted PAT already exist
    log.debug(
        f"Attempting to read the personal access token from {ConfigCommand.CONF_FILE_PATH}"
    )
    if os.path.exists(ConfigCommand.CONF_FILE_PATH):
        path = Path(ConfigCommand.CONF_FILE_PATH)
        yaml = YAML(typ="safe")
        settings = yaml.load(path)
        if os.path.exists(ConfigCommand.KEY_PAT_FILE) and "pat" in settings:
            pat = decrypt_pat()
            return pat
        else:
            log.debug(
                f"Unable to read the personal access token from {ConfigCommand.CONF_FILE_PATH}"
            )
            console.print(
                "[bold red]Could not find encrypted personal access token!\n")
            console.print(
                "[bold blue]Please navigate to Github -> Your profile -> Settings -> Developer Settings -> Personal access token -> "
                "Generate a new Token")
            console.print(
                "[bold blue]Only tick 'repo'. The token is a hidden input to cookietemple and stored encrypted locally on your machine."
            )
            console.print(
                "[bold blue]For more information please read" +
                "https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line\n\n"
            )
            console.print(
                "[bold blue]Lets move on to set your personal access token for your cookietemple project!"
            )
            # set the PAT
            ConfigCommand.config_pat()
            # if the user wants to create a GitHub repo but accidentally presses no on PAT config prompt
            if not os.path.exists(ConfigCommand.KEY_PAT_FILE):
                console.print(
                    "[bold red]No Github personal access token found. Please set it using [green]cookietemple config github"
                )
                sys.exit(1)
            else:
                pat = decrypt_pat()
            return pat
    else:
        console.print(
            "[bold red]Cannot find a cookietemple config file! Did you delete it?"
        )

    return ""
예제 #3
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)
예제 #4
0
    def prompt_general_template_configuration(self, dot_cookietemple: Optional[dict]):
        """
        Prompts the user for general options that are required by all templates.
        Options are saved in the creator context manager object.
        """
        try:
            """
            Check, if the dot_cookietemple dictionary contains the full name and email (this happens, when dry creating the template while syncing on
            TEMPLATE branch).
            If that's not the case, try to read them from the config file (created with the config command).

            If none of the approaches above succeed (no config file has been found and its not a dry create run), configure the basic credentials and proceed.
            """
            if dot_cookietemple:
                self.creator_ctx.full_name = dot_cookietemple["full_name"]
                self.creator_ctx.email = dot_cookietemple["email"]
            else:
                self.creator_ctx.full_name = load_yaml_file(ConfigCommand.CONF_FILE_PATH)["full_name"]
                self.creator_ctx.email = load_yaml_file(ConfigCommand.CONF_FILE_PATH)["email"]
        except FileNotFoundError:
            # style and automatic use config
            console.print(
                "[bold red]Cannot find a cookietemple config file. Is this your first time using cookietemple?"
            )
            # inform the user and config all settings (with PAT optional)
            console.print("[bold blue]Lets set your name, email and Github username and you´re ready to go!")
            ConfigCommand.all_settings()
            # load mail and full name
            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML(typ="safe")
            settings = yaml.load(path)
            # set full name and mail
            self.creator_ctx.full_name = settings["full_name"]
            self.creator_ctx.email = settings["email"]

        self.creator_ctx.project_name = cookietemple_questionary_or_dot_cookietemple(
            function="text",
            question="Project name",
            default="exploding-springfield",
            dot_cookietemple=dot_cookietemple,
            to_get_property="project_name",
        ).lower()  # type: ignore
        if self.creator_ctx.language == "python":
            self.check_name_available("PyPi", dot_cookietemple)
        self.check_name_available("readthedocs.io", dot_cookietemple)
        self.creator_ctx.project_slug = self.creator_ctx.project_name.replace(" ", "_")  # type: ignore
        self.creator_ctx.project_slug_no_hyphen = self.creator_ctx.project_slug.replace("-", "_")
        self.creator_ctx.project_short_description = cookietemple_questionary_or_dot_cookietemple(
            function="text",
            question="Short description of your project",
            default=f"{self.creator_ctx.project_name}" f". A cookietemple based .",
            dot_cookietemple=dot_cookietemple,
            to_get_property="project_short_description",
        )
        poss_vers = cookietemple_questionary_or_dot_cookietemple(
            function="text",
            question="Initial version of your project",
            default="0.1.0",
            dot_cookietemple=dot_cookietemple,
            to_get_property="version",
        )

        # make sure that the version has the right format
        while not re.match(r"(?<!.)\d+(?:\.\d+){2}(?:-SNAPSHOT)?(?!.)", poss_vers) and not dot_cookietemple:  # type: ignore
            console.print(
                "[bold red]The version number entered does not match semantic versioning.\n"
                + r"Please enter the version in the format \[number].\[number].\[number]!"
            )  # noqa: W605
            poss_vers = cookietemple_questionary_or_dot_cookietemple(
                function="text", question="Initial version of your project", default="0.1.0"
            )
        self.creator_ctx.version = poss_vers

        self.creator_ctx.license = cookietemple_questionary_or_dot_cookietemple(
            function="select",
            question="License",
            choices=[
                "MIT",
                "BSD",
                "ISC",
                "Apache2.0",
                "GNUv3",
                "Boost",
                "Affero",
                "CC0",
                "CCBY",
                "CCBYSA",
                "Eclipse",
                "WTFPL",
                "unlicence",
                "Not open source",
            ],
            default="MIT",
            dot_cookietemple=dot_cookietemple,
            to_get_property="license",
        )
        if dot_cookietemple:
            self.creator_ctx.github_username = dot_cookietemple["github_username"]
            self.creator_ctx.creator_github_username = dot_cookietemple["creator_github_username"]
        else:
            self.creator_ctx.github_username = load_github_username()
            self.creator_ctx.creator_github_username = self.creator_ctx.github_username
예제 #5
0
    def prompt_general_template_configuration(
            self, dot_cookietemple: Optional[dict]):
        """
        Prompts the user for general options that are required by all templates.
        Options are saved in the creator context manager object.
        """
        try:
            """
            Check, if the dot_cookietemple dictionary contains the full name and email (this happens, when dry creating the template while syncing on
            TEMPLATE branch).
            If that's not the case, try to read them from the config file (created with the config command).

            If none of the approaches above succeed (no config file has been found and its not a dry create run), configure the basic credentials and proceed.
            """
            if dot_cookietemple:
                self.creator_ctx.full_name = dot_cookietemple['full_name']
                self.creator_ctx.email = dot_cookietemple['email']
            else:
                self.creator_ctx.full_name = load_yaml_file(
                    ConfigCommand.CONF_FILE_PATH)['full_name']
                self.creator_ctx.email = load_yaml_file(
                    ConfigCommand.CONF_FILE_PATH)['email']
        except FileNotFoundError:
            # style and automatic use config
            console.print(
                '[bold red]Cannot find a cookietemple config file. Is this your first time using cookietemple?'
            )
            # inform the user and config all settings (with PAT optional)
            console.print(
                '[bold blue]Lets set your name, email and Github username and you´re ready to go!'
            )
            ConfigCommand.all_settings()
            # load mail and full name
            path = Path(ConfigCommand.CONF_FILE_PATH)
            yaml = YAML(typ='safe')
            settings = yaml.load(path)
            # set full name and mail
            self.creator_ctx.full_name = settings['full_name']
            self.creator_ctx.email = settings['email']

        self.creator_ctx.project_name = cookietemple_questionary_or_dot_cookietemple(
            function='text',
            question='Project name',
            default='exploding-springfield',
            dot_cookietemple=dot_cookietemple,
            to_get_property='project_name').lower()  # type: ignore
        if self.creator_ctx.language == 'python':
            self.check_name_available("PyPi", dot_cookietemple)
        self.check_name_available("readthedocs.io", dot_cookietemple)
        self.creator_ctx.project_slug = self.creator_ctx.project_name.replace(
            ' ', '_')  # type: ignore
        self.creator_ctx.project_slug_no_hyphen = self.creator_ctx.project_slug.replace(
            '-', '_')
        self.creator_ctx.project_short_description = cookietemple_questionary_or_dot_cookietemple(
            function='text',
            question='Short description of your project',
            default=f'{self.creator_ctx.project_name}'
            f'. A cookietemple based .',
            dot_cookietemple=dot_cookietemple,
            to_get_property='project_short_description')
        poss_vers = cookietemple_questionary_or_dot_cookietemple(
            function='text',
            question='Initial version of your project',
            default='0.1.0',
            dot_cookietemple=dot_cookietemple,
            to_get_property='version')

        # make sure that the version has the right format
        while not re.match(r'(?<!.)\d+(?:\.\d+){2}(?:-SNAPSHOT)?(?!.)',
                           poss_vers) and not dot_cookietemple:  # type: ignore
            console.print(
                '[bold red]The version number entered does not match semantic versioning.\n'
                +
                'Please enter the version in the format \[number].\[number].\[number]!'
            )  # noqa: W605
            poss_vers = cookietemple_questionary_or_dot_cookietemple(
                function='text',
                question='Initial version of your project',
                default='0.1.0')
        self.creator_ctx.version = poss_vers

        self.creator_ctx.license = cookietemple_questionary_or_dot_cookietemple(
            function='select',
            question='License',
            choices=[
                'MIT', 'BSD', 'ISC', 'Apache2.0', 'GNUv3', 'Boost', 'Affero',
                'CC0', 'CCBY', 'CCBYSA', 'Eclipse', 'WTFPL', 'unlicence',
                'Not open source'
            ],
            default='MIT',
            dot_cookietemple=dot_cookietemple,
            to_get_property='license')
        if dot_cookietemple:
            self.creator_ctx.github_username = dot_cookietemple[
                'github_username']
            self.creator_ctx.creator_github_username = dot_cookietemple[
                'creator_github_username']
        else:
            self.creator_ctx.github_username = load_github_username()
            self.creator_ctx.creator_github_username = self.creator_ctx.github_username