12

I would like to have a file that is optionally added in my python cookiecutter project.

An example would be in cookiecutter.json have the variable

{"settings_file": true}

which would create a file settings.py at the root of my directory (with maybe some contents).

Does cookiecutter offer an option to do this? Or should I be using the post processing hook to write a script which creates the files (which I feel like is not the most elegant solution).

nichochar
  • 2,720
  • 1
  • 18
  • 16

3 Answers3

13

I'm going to answer my own question, in case someone runs into it: it is not yet implemented as a feature of the project, see ticket for enhancement here: https://github.com/audreyr/cookiecutter/issues/127

The "least ugly" solution I have come up with is to create the files every time, and clean them up during the post hook (you could also create them during the post hook, but would lose cookiecutter templating advantages)

nichochar
  • 2,720
  • 1
  • 18
  • 16
5

According to the official docs, you can use a post-generate hook script (hooks/post_gen_project.py)

(Copying the snippet here for those skimming through)

import os
import sys

REMOVE_PATHS = [
    '{% if cookiecutter.packaging != "pip" %} requirements.txt {% endif %}',
    '{% if cookiecutter.packaging != "poetry" %} poetry.lock {% endif %}',
]

for path in REMOVE_PATHS:
    path = path.strip()
    if path and os.path.exists(path):
        if os.path.isdir(path):
            os.rmdir(path)
        else:
            os.unlink(path)
partmor
  • 71
  • 1
  • 3
0

It is possible to use Jinja templating and conditionals in file names.

As such you can have a file named {% if cookiecutter.settings_file == "true" -%} __main__.py {%- endif %} which will only be created if settings_file is true.

Note that boolean variables are not yet supported in Cookiecutter, although there is a merged PR to add this functionality. One way to solve it now is to use e.g., ["true", "false"] as values.

Ahlqvist
  • 101
  • 3