[Python] Injecting extra context in Cookiecutter (timestamp, shell variables)

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I read this article and it seems to describe exactly what I need : https://cookiecutter.readthedocs.io/en/1.7.2/advanced/injecting_context.html

    However, it mentions a Python script and I don't know where to place it. My goal is to have it read by default when running cookiecutter <template>.

    My feeling is that, the article idea is to make a fully custom script to run Cookiecutter from python.

    I think it defeats the purpose of having a nice and simple tool easily run from the terminal.

    It also removes the use case of running it directly on my repository : cookiecutter https://github.com/audreyr/cookiecutter-pypackage

    Some context :

    I am making a custom fork of https://github.com/audreyfeldroy/cookiecutter-pypackage

    I really like the original project, however the setup file cookiecutter.json contains hardcoded values concerning the author.

    I want to replace it with :

    {
    "full_name" : "{{cookiecutter.full_name}}",
    "email" : "{{cookiecutter.email}}",
    ...
    }


    With the associated Python code:

    import os
    from cookiecutter.main import cookiecutter

    cookiecutter(
    'cookiecutter-pypackage',
    extra_context={
    full_name = os.popen('git config --get user.name' ).read().strip(),
    email = os.popen('git config --get user.email').read().strip(),
    }
    )


    This way I can share my template without having my (or the author's) name hanging around in whatever stranger's project. But I (and most others) will still have nice default values when running it.

    Any idea how to achieve that so it still runs with cookiecutter native command? I thought about using hooks (https://cookiecutter.readthedocs.io/en/1.7.2/advanced/hooks.html) but I don't think they can handle my usecase.

    Thanks, Aurel

    Continue reading...

Compartilhe esta Página