Пример #1
0
def verbose_cookiecutter(**kwargs):
    from cookiecutter.log import configure_logger
    configure_logger(stream_level='DEBUG')

    print("Run cookiecutter with:")
    pprint(kwargs)
    print()
    result = cookiecutter(**kwargs)
    return result
Пример #2
0
    def do_update_own_boot_file(self, arg):
        """
        Update 'bootstrap_env/boot_bootstrap_env.py' via cookiecutter.

        Only useable on develop installation!

        direct call, e.g.:
        $ pylucid_admin update_own_boot_file
        """
        # Note: Theses packages not available on normal install:
        import bootstrap_env
        from bootstrap_env.utils.cookiecutter_utils import verbose_cookiecutter
        from packaging.version import parse

        # https://packaging.pypa.io/en/latest/version/
        parsed_pylucid_version = parse(pylucid.__version__)

        if parsed_pylucid_version.is_prerelease:
            print("PyLucid v%s is pre release" % parsed_pylucid_version)
            use_pre_release = "y"
        else:
            print("PyLucid v%s is not a pre release" % parsed_pylucid_version)
            use_pre_release = "n"

        bootstrap_env_path = Path(bootstrap_env.__file__).parent
        assert bootstrap_env_path.is_dir()

        repro_path = Path(bootstrap_env_path, "boot_source")

        output_dir = Path(pylucid.__file__)     # .../PyLucid-env/src/pylucid/pylucid/__init__.py
        output_dir = output_dir.parent          # .../PyLucid-env/src/pylucid/pylucid/
        output_dir = output_dir.parent          # .../PyLucid-env/src/pylucid/

        from cookiecutter.log import configure_logger
        configure_logger(stream_level='DEBUG')

        from bootstrap_env.version import __version__ as bootstrap_env_version

        result = verbose_cookiecutter(
            template=str(repro_path),
            no_input=True,
            overwrite_if_exists=True,
            output_dir=str(output_dir),
            extra_context={
                # see: bootstrap_env/boot_source/cookiecutter.json
                "_version": bootstrap_env_version,
                "project_name": "pylucid",
                "package_name": "pylucid",
                "bootstrap_filename": "pylucid_boot",
                "editable_url": "git+https://github.com/jedie/PyLucid.git@master",
                "raw_url": "https://raw.githubusercontent.com/jedie/PyLucid/master",
                "use_pre_release": use_pre_release,
            },
        )
        print("\nbootstrap file created here: %s" % result)
Пример #3
0
def main(template, extra_context, no_input, checkout, verbose, replay,
         overwrite_if_exists, output_dir, config_file, default_config,
         debug_file):
    """Create a project from a Cookiecutter project template (TEMPLATE).

    Cookiecutter is free and open source software, developed and managed by
    volunteers. If you would like to help out or fund the project, please get
    in touch at https://github.com/audreyr/cookiecutter.
    """
    # If you _need_ to support a local template in a directory
    # called 'help', use a qualified path to the directory.
    if template == u'help':
        click.echo(click.get_current_context().get_help())
        sys.exit(0)

    if template == u'ls':
        config_dict = get_user_config(config_file=config_file,
                                      default_config=default_config)
        clone_to_dir = config_dict['cookiecutters_dir']
        import glob
        directories = "\n".join(glob.glob1(clone_to_dir, "*"))
        click.echo('Existing templates:\n' + directories)
        sys.exit(0)

    configure_logger(
        stream_level='DEBUG' if verbose else 'INFO',
        debug_file=debug_file,
    )

    try:
        cookiecutter(template,
                     checkout,
                     no_input,
                     extra_context=extra_context,
                     replay=replay,
                     overwrite_if_exists=overwrite_if_exists,
                     output_dir=output_dir,
                     config_file=config_file,
                     default_config=default_config,
                     password=os.environ.get('COOKIECUTTER_REPO_PASSWORD'))
    except (OutputDirExistsException, InvalidModeException,
            FailedHookException, UnknownExtension, InvalidZipRepository,
            RepositoryNotFound, RepositoryCloneFailed) as e:
        click.echo(e)
        sys.exit(1)
    except UndefinedVariableInTemplate as undefined_err:
        click.echo('{}'.format(undefined_err.message))
        click.echo('Error message: {}'.format(undefined_err.error.message))

        context_str = json.dumps(undefined_err.context,
                                 indent=4,
                                 sort_keys=True)
        click.echo('Context: {}'.format(context_str))
        sys.exit(1)
Пример #4
0
    def create(self, template, verbose, overwrite, **config):
        if verbose:
            log.configure_logger('DEBUG')

        if not self.logger.handlers:
            self.logger.addHandler(logging.StreamHandler())
        self.logger.setLevel(logging.DEBUG)

        with tempfile.NamedTemporaryFile() as cc_yaml_config:
            cc_config = self.read_user_config()
            cc_yaml_config.write(
                yaml.dump(cc_config,
                          default_style='"',
                          default_flow_style=False).encode('utf-8'))
            cc_yaml_config.flush()

            cc_yaml_config_name = cc_yaml_config.name if cc_config else None
            cc_config = main.get_user_config(config_file=cc_yaml_config_name)

            template = repository.expand_abbreviations(
                template, cc_config['abbreviations'])

            url = list(urlparse.urlsplit(template))
            if url[0]:
                url[4], path = '', url[4]
                path = path.strip('/')
                template = urlparse.urlunsplit(url)
            else:
                path = None
                if (os.sep not in template) and not os.path.exists(template):
                    template = find_templates()[template]
                    if template is not None:
                        template = template.get_location()

            print('Generating project from `{}`\n'.format(template))

            try:
                main.cookiecutter(template,
                                  overwrite_if_exists=overwrite,
                                  config_file=cc_yaml_config_name,
                                  **config)
            except exceptions.RepositoryNotFound as e:
                if not path:
                    raise

                repo_dir = e.args[0].splitlines()[-1]
                template = os.path.basename(repo_dir)
                main.cookiecutter(os.path.join(template, path),
                                  overwrite_if_exists=overwrite,
                                  config_file=cc_yaml_config_name,
                                  **config)

            return 0
Пример #5
0
    def do_update_own_boot_file(self, arg):
        """
        Update 'bootstrap_env/boot_bootstrap_env.py' via cookiecutter.

        Only useable on develop installation!

        direct call, e.g.:
        $ pylucid_admin update_own_boot_file
        """
        from packaging.version import parse

        # https://packaging.pypa.io/en/latest/version/
        parsed_pylucid_version = parse(pylucid.__version__)

        if parsed_pylucid_version.is_prerelease:
            print("PyLucid v%s is pre release" % parsed_pylucid_version)
            use_pre_release = "y"
        else:
            print("PyLucid v%s is not a pre release" % parsed_pylucid_version)
            use_pre_release = "n"

        bootstrap_env_path = Path(bootstrap_env.__file__).parent
        assert bootstrap_env_path.is_dir()

        repro_path = Path(bootstrap_env_path, "boot_source")

        output_dir = Path(pylucid.__file__)     # .../PyLucid-env/src/pylucid/pylucid/__init__.py
        output_dir = output_dir.parent          # .../PyLucid-env/src/pylucid/pylucid/
        output_dir = output_dir.parent          # .../PyLucid-env/src/pylucid/

        from cookiecutter.log import configure_logger
        configure_logger(stream_level='DEBUG')

        from bootstrap_env.version import __version__ as bootstrap_env_version

        result = verbose_cookiecutter(
            template=str(repro_path),
            no_input=True,
            overwrite_if_exists=True,
            output_dir=str(output_dir),
            extra_context={
                # see: bootstrap_env/boot_source/cookiecutter.json
                "_version": bootstrap_env_version,
                "project_name": "pylucid",
                "package_name": "pylucid",
                "bootstrap_filename": "pylucid_boot",
                "editable_url": "git+https://github.com/jedie/PyLucid.git@master",
                "raw_url": "https://raw.githubusercontent.com/jedie/PyLucid/master",
                "use_pre_release": use_pre_release,
            },
        )
        print("\nbootstrap file created here: %s" % result)
Пример #6
0
def main(
        template, extra_context, no_input, checkout, verbose,
        replay, overwrite_if_exists, output_dir, config_file,
        default_config, debug_file):
    """Create a project from a Cookiecutter project template (TEMPLATE).

    Cookiecutter is free and open source software, developed and managed by
    volunteers. If you would like to help out or fund the project, please get
    in touch at https://github.com/audreyr/cookiecutter.
    """
    # If you _need_ to support a local template in a directory
    # called 'help', use a qualified path to the directory.
    if template == u'help':
        click.echo(click.get_current_context().get_help())
        sys.exit(0)

    configure_logger(
        stream_level='DEBUG' if verbose else 'INFO',
        debug_file=debug_file,
    )

    try:
        cookiecutter(
            template, checkout, no_input,
            extra_context=extra_context,
            replay=replay,
            overwrite_if_exists=overwrite_if_exists,
            output_dir=output_dir,
            config_file=config_file,
            default_config=default_config,
            password=os.environ.get('COOKIECUTTER_REPO_PASSWORD')
        )
    except (OutputDirExistsException,
            InvalidModeException,
            FailedHookException,
            UnknownExtension,
            InvalidZipRepository,
            RepositoryNotFound,
            RepositoryCloneFailed) as e:
        click.echo(e)
        sys.exit(1)
    except UndefinedVariableInTemplate as undefined_err:
        click.echo('{}'.format(undefined_err.message))
        click.echo('Error message: {}'.format(undefined_err.error.message))

        context_str = json.dumps(
            undefined_err.context,
            indent=4,
            sort_keys=True
        )
        click.echo('Context: {}'.format(context_str))
        sys.exit(1)
Пример #7
0
def main(no_input, verbose, replay, overwrite_if_exists, output_dir,
         config_file, default_config):
    template_name = os.path.basename(os.path.dirname(__file__))
    if replay:
        context = None
    else:
        config_dict = get_user_config(
            config_file=config_file,
            default_config=default_config,
        )
        context = load(config_dict['replay_dir'],
                       template_name)['cookiecutter']
    configure_logger(stream_level='DEBUG' if verbose else 'INFO')
    cookiecutter(template_name,
                 no_input=no_input,
                 extra_context=context,
                 replay=replay,
                 overwrite_if_exists=overwrite_if_exists,
                 output_dir=output_dir,
                 config_file=config_file,
                 default_config=default_config)
Пример #8
0
def info_logger_with_file(debug_file):
    return configure_logger(stream_level="INFO", debug_file=str(debug_file),)
Пример #9
0
def debug_logger():
    return configure_logger(stream_level="DEBUG")
Пример #10
0
def info_logger():
    return configure_logger(stream_level="INFO")
Пример #11
0
def venv_main(name: str,
              language: str,
              out: str,
              metadata: Optional[io.BufferedReader] = None,
              verbose: bool = False):

    #
    # We'll create:
    #
    #   1. A new project from template
    #   2. Virtual environment for the project
    #   3. Install required dependencies
    #

    template_dir = HERE / 'skill_template'
    output_dir = Path(os.path.expanduser(out) if out.startswith('~/') else out)

    # Check if project already exists and ask to overwrite it
    skill_dir = output_dir / '-'.join(['skill', name, language])
    overwrite_if_exists = prompt_overwrite(skill_dir)

    # Read json configuration and replace the variables
    extra_context = read_config(template_dir / 'cookiecutter.json')
    extra_context.update({
        'skill_name': name,
        'programming_language': language
    })

    configure_logger(stream_level='DEBUG' if verbose else 'INFO')

    start = time.time()
    # Run cookiecutter with all parameters set without prompting
    skill_dir = cookiecutter(str(template_dir),
                             extra_context=extra_context,
                             output_dir=str(output_dir),
                             overwrite_if_exists=overwrite_if_exists,
                             no_input=True)
    cookies_time = time.time() - start

    # Create implementation from domain context metadata
    if metadata:
        create_implementation(metadata,
                              Path(skill_dir),
                              extra_context=extra_context)

    # Create virtual environment
    stdout = sys.stdout if verbose else open(os.devnull, 'w')

    venv = Path(skill_dir) / VENV_DIR
    click.secho(f'Creating virtual environment in {venv}', fg='green')
    start = time.time()
    subprocess.check_call((sys.executable, '-m', 'venv', str(venv), '--clear'),
                          stderr=stdout,
                          stdout=stdout)

    # Install SDK in "editable" mode
    click.secho(f'Installing skill SDK for Python', fg='green')

    python = venv / ('Scripts' if os.name == 'nt' else 'bin') / 'python'
    subprocess.check_call(
        (str(python), '-m', 'pip', 'install', '-e', str(HERE.parent)),
        stderr=stdout,
        stdout=stdout)

    venv_time = time.time() - start

    if verbose:
        click.secho(
            f'Timing: cookiecutter took {round(cookies_time, 2)} sec, '
            f'venv took {round(venv_time, 2)}',
            fg='green')

    return 0
Пример #12
0
def info_logger_with_file(debug_file):
    return configure_logger(
        stream_level='INFO',
        debug_file=str(debug_file),
    )
Пример #13
0
def info_logger():
    return configure_logger(stream_level='INFO')
Пример #14
0
def info_logger_with_file(debug_file):
    """Fixture. Call cookiecutter logger setup with `info` debug level + `file`."""
    return configure_logger(stream_level='INFO', debug_file=str(debug_file))
Пример #15
0
def debug_logger():
    """Fixture. Call cookiecutter logger setup with `debug` debug level."""
    return configure_logger(stream_level='DEBUG')
Пример #16
0
def info_logger():
    """Fixture. Call cookiecutter logger setup with `info` debug level."""
    return configure_logger(stream_level='INFO')
Пример #17
0
def main(
    template,
    extra_context,
    no_input,
    checkout,
    verbose,
    replay,
    overwrite_if_exists,
    output_dir,
    config_file,
    default_config,
    debug_file,
    directory,
    skip_if_file_exists,
    accept_hooks,
    replay_file,
    list_installed,
):
    """Create a project from a Cookiecutter project template (TEMPLATE).

    Cookiecutter is free and open source software, developed and managed by
    volunteers. If you would like to help out or fund the project, please get
    in touch at https://github.com/cookiecutter/cookiecutter.
    """
    # Commands that should work without arguments
    if list_installed:
        list_installed_templates(default_config, config_file)
        sys.exit(0)

    # Raising usage, after all commands that should work without args.
    if not template or template.lower() == 'help':
        click.echo(click.get_current_context().get_help())
        sys.exit(0)

    configure_logger(stream_level='DEBUG' if verbose else 'INFO',
                     debug_file=debug_file)

    # If needed, prompt the user to ask whether or not they want to execute
    # the pre/post hooks.
    if accept_hooks == "ask":
        _accept_hooks = click.confirm("Do you want to execute hooks?")
    else:
        _accept_hooks = accept_hooks == "yes"

    if replay_file:
        replay = replay_file

    try:
        cookiecutter(
            template,
            checkout,
            no_input,
            extra_context=extra_context,
            replay=replay,
            overwrite_if_exists=overwrite_if_exists,
            output_dir=output_dir,
            config_file=config_file,
            default_config=default_config,
            password=os.environ.get('COOKIECUTTER_REPO_PASSWORD'),
            directory=directory,
            skip_if_file_exists=skip_if_file_exists,
            accept_hooks=_accept_hooks,
        )
    except (
            ContextDecodingException,
            OutputDirExistsException,
            InvalidModeException,
            FailedHookException,
            UnknownExtension,
            InvalidZipRepository,
            RepositoryNotFound,
            RepositoryCloneFailed,
    ) as e:
        click.echo(e)
        sys.exit(1)
    except UndefinedVariableInTemplate as undefined_err:
        click.echo('{}'.format(undefined_err.message))
        click.echo('Error message: {}'.format(undefined_err.error.message))

        context_str = json.dumps(undefined_err.context,
                                 indent=4,
                                 sort_keys=True)
        click.echo('Context: {}'.format(context_str))
        sys.exit(1)
Пример #18
0
def main(
        template, extra_context, no_input, checkout, verbose,
        replay, overwrite_if_exists, output_dir, config_file,
        default_config, debug_file):
    """Create a project from a Cookiecutter project template (TEMPLATE).

    TEMPLATE is a local path or a link to a cookiecutter project template.
    It can also be help, python, django or pytest for Cookiecutter
    specials.

    Cookiecutter is free and open source software, developed and managed by
    volunteers. If you would like to help out or fund the project, please get
    in touch at https://github.com/audreyr/cookiecutter.
    """
    # If you _need_ to support a local template in a directory
    # called 'help', use a qualified path to the directory.
    if template == u'help':
        click.echo(click.get_current_context().get_help())
        sys.exit(0)
    elif template == u'python':
        template = 'https://github.com/audreyr/cookiecutter-pypackage'
        click.echo(
            'Using default Python package project template {}'.format(template)
        )
    elif template == u'django':
        template = 'https://github.com/pydanny/cookiecutter-django'
        click.echo(
            'Using default Django project template {}'.format(template)
        )
    elif template == u'pytest':
        template = 'https://github.com/pytest-dev/cookiecutter-pytest-plugin'
        click.echo(
            'Using default pytest template {}'.format(template)
        )

    configure_logger(
        stream_level='DEBUG' if verbose else 'INFO',
        debug_file=debug_file,
    )

    try:
        cookiecutter(
            template, checkout, no_input,
            extra_context=extra_context,
            replay=replay,
            overwrite_if_exists=overwrite_if_exists,
            output_dir=output_dir,
            config_file=config_file,
            default_config=default_config,
        )
    except (OutputDirExistsException,
            InvalidModeException,
            FailedHookException,
            UnknownExtension,
            RepositoryNotFound,
            RepositoryCloneFailed) as e:
        click.echo(e)
        sys.exit(1)
    except UndefinedVariableInTemplate as undefined_err:
        click.echo('{}'.format(undefined_err.message))
        click.echo('Error message: {}'.format(undefined_err.error.message))

        context_str = json.dumps(
            undefined_err.context,
            indent=4,
            sort_keys=True
        )
        click.echo('Context: {}'.format(context_str))
        sys.exit(1)
Пример #19
0
def debug_logger():
    return configure_logger(stream_level='DEBUG')