Skip to content

two layers of templating/interpolation no longer works in hook when using replay #1902

@thomasgilgenast

Description

@thomasgilgenast
  • Cookiecutter version: 2.2.3
  • Template project url: NA
  • Python version: 3.8.13
  • Operating System: MacOS

Description:

In 2.2.2, it was possible to use replay files together with two layers of interpolation (templating in a variable from cookiecutter.json that itself used interpolation) in a hooks/pre_gen_project.py hook.

In 2.2.3, this is no longer possible - interpolation is only performed once.

What I've run:

I created a bare-bones example repo for this here but in short:

  • I wrote cookiecutter.json as the first two keys in the example from the docs here:

    {
        "package_name": "my-package",
        "module_name": "{{ cookiecutter.package_name.replace('-', '_') }}"
    }
    
  • I copied hooks/pre_gen_project.py from the docs here

    import re
    import sys
    
    
    MODULE_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'
    
    module_name = '{{ cookiecutter.module_name }}'
    
    if not re.match(MODULE_REGEX, module_name):
        print('ERROR: %s is not a valid Python module name!' % module_name)
    
        # exits with status 1 to indicate failure
        sys.exit(1)
    
  • I wrote a minimal replay.json to match my cookiecutter.json

    {
        "cookiecutter": {
            "package_name": "testpackage",
            "module_name": "testpackage"
        }
    }
    
  • I created a minimal folder structure for the output

    mkdir '{{cookiecutter.module_name}}'
    echo hi > '{{cookiecutter.module_name}}/hi.txt'
    

When I try to run

cookiecutter . -o test

with no replay file and accept the defaults, everything works.

When I try to run

cookiecutter . --replay-file replay.json -o test

I get

  File "/var/folders/_x/lmzd7l2n2q7g0qjyvrzls5wh0000gn/T/tmppfzh8tgj.py", line 7
    module_name = '{{ cookiecutter.package_name.replace('-', '_') }}'
                                                              ^
SyntaxError: invalid syntax
ERROR: Stopping generation because pre_gen_project hook script didn't exit successfully
Hook script failed (exit status: 1)

This SyntaxError comes from the line

module_name = '{{ cookiecutter.module_name }}'

in hooks/pre_gen_project.py - it's interpolated, but only once.

If I downgrade to cookiecutter 2.2.2 everything works as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions